Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

416 KB
Raw Blame
using System.Security.Cryptography;
using System.Diagnostics;
using System.Text.Json;
using System.Text.Json.Serialization;
using Aetheris.Kernel.Core.Diagnostics;
using System.Text.RegularExpressions;
using Aetheris.Forge.Abstractions.FirmamentInterop;
using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Brep.Verification;
using Aetheris.Kernel.Core.Brep.Tessellation;
using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Step242;
using Aetheris.Kernel.Core.Visualization;
using Aetheris.Kernel.Firmament;
using Aetheris.Kernel.Firmament.Assembly;
using Aetheris.Kernel.Firmament.Drawing;
using Aetheris.Kernel.Firmament.FirmamentV2;
using Aetheris.Kernel.Firmament.Materializer;
using Aetheris.Firmament.FrictionLab.CIRLab;
using Aetheris.FEA.Abaqus;
using Aetheris.FEA.Firmament;
using Aetheris.FEA.Mechanics;
using Aetheris.Semantics;
using Aetheris.Modules.BuiltIn;
using Aetheris.Piping;
using Aetheris.PlasticShell;
using Aetheris.Surfacing;
using Aetheris.Geometry;
using Aetheris.SheetMetal;
using Aetheris.Sculpture;
using Aetheris.Kernel.Firmament.Structural;
using Aetheris.Kernel.Firmament.Piping;

namespace Aetheris.CLI;

internal static class SideHoleGoldenPathArtifacts
{
    public const string StepFileName = "side-hole.step";
    public const string JsonFileName = "side-hole.trace.json";
    public const string TextFileName = "side-hole.trace.txt";
    public const string ManifestFileName = "manifest.json";

    public static AirTraceArtifactsSummary Write(string outDir, AirTraceReport report)
    {
        Directory.CreateDirectory(outDir);
        var stem = IsFirmamentV2SideHole(report) ? V2Stem(report) : "side-hole";
        var artifacts = new AirTraceArtifactsSummary(
            Path.Combine(outDir, stem + ".step"),
            Path.Combine(outDir, stem + ".trace.json"),
            Path.Combine(outDir, stem + ".trace.txt"),
            Path.Combine(outDir, ManifestFileName));
        File.WriteAllText(artifacts.Step, StepText(report, stem));
        return artifacts;
    }

    public static string Manifest(AirTraceReport report, AirTraceArtifactsSummary artifacts) => JsonSerializer.Serialize(new
    {
        milestone = IsFirmamentV2SideHole(report) ? "AIR-FIRMAMENT-X6" : "AIR-REGION-X13",
        syntaxVersion = report.FirmamentV2?.SyntaxVersion,
        fixture = report.FixturePath,
        stage = report.ActualStageReached,
        parentIntegration = report.FirmamentV2?.ParentIntegration ?? "Integrated",
        shellClosure = report.FirmamentV2?.ShellClosure ?? "Closed",
        stepSmoke = report.FirmamentV2?.StepSmoke ?? "Succeeded",
        route = report.FirmamentV2?.SemanticIntent?.RouteEvidence,
        radius = report.FirmamentV2?.SemanticIntent?.Radius,
        tool = report.FirmamentV2?.SemanticIntent?.Tool,
        attachTargetSource = report.FirmamentV2?.SemanticIntent?.AttachTargetSource,
        attachResolvedSelector = report.FirmamentV2?.SemanticIntent is null ? null : $"face({report.FirmamentV2.SemanticIntent.AttachFace})",
        throughTargetSource = report.FirmamentV2?.SemanticIntent?.ThroughTargetSource,
        throughResolvedSelector = report.FirmamentV2?.SemanticIntent is null ? null : $"face({report.FirmamentV2.SemanticIntent.ThroughFace})",
        throughSelector = report.FirmamentV2?.SemanticIntent is null ? null : $"face({report.FirmamentV2.SemanticIntent.ThroughFace})",
        center = report.FirmamentV2?.SemanticIntent is null ? null : new { u = report.FirmamentV2.SemanticIntent.CenterU, v = report.FirmamentV2.SemanticIntent.CenterV, explicitValue = report.FirmamentV2.SemanticIntent.CenterExplicit, frame = report.FirmamentV2.SemanticIntent.CenterSelectorFrame },
        step = Path.GetFileName(artifacts.Step),
        traceJson = Path.GetFileName(artifacts.TraceJson),
        traceText = Path.GetFileName(artifacts.TraceText),
        sourcePath = IsFirmamentV2SideHole(report) ? "FirmamentV2Parser" : "FirmamentFixtureMetadata",
        controlledFixtureOnly = true,
        generalSideHoleSupport = false
    }, CliRunner.JsonOptions);

    private static bool IsFirmamentV2SideHole(AirTraceReport report) =>
        report.FirmamentV2 is { SyntaxVersion: "FirmamentV2", SemanticIntent: not null };

    private static string V2Stem(AirTraceReport report)
    {
        var radius = report.FirmamentV2!.SemanticIntent!.Radius;
        var centerU = report.FirmamentV2!.SemanticIntent!.CenterU;
        var centerV = report.FirmamentV2!.SemanticIntent!.CenterV;
        if (report.FirmamentV2!.SemanticIntent!.Route == "-X->+X" && (report.FirmamentV2!.SemanticIntent!.AttachTargetKind == "Alias" || report.FirmamentV2!.SemanticIntent!.ThroughTargetKind == "Alias")) return "side-hole-aliases-reverse-x-v2";
        if (report.FirmamentV2!.SemanticIntent!.Route == "-X->+X") return "side-hole-reverse-x-v2";
        if (report.FirmamentV2!.SemanticIntent!.Route == "+Y->-Y" && (report.FirmamentV2!.SemanticIntent!.AttachTargetKind == "Alias" || report.FirmamentV2!.SemanticIntent!.ThroughTargetKind == "Alias")) return "side-hole-aliases-y-axis-v2";
        if (report.FirmamentV2!.SemanticIntent!.Route == "+Y->-Y") return "side-hole-y-axis-v2";
        if (report.FirmamentV2!.SemanticIntent!.Route == "-Y->+Y") return "side-hole-reverse-y-v2";
        if (report.FirmamentV2!.SemanticIntent!.Route == "+Z->-Z" && (report.FirmamentV2!.SemanticIntent!.AttachTargetKind == "Alias" || report.FirmamentV2!.SemanticIntent!.ThroughTargetKind == "Alias")) return "side-hole-aliases-z-axis-v2";
        if (report.FirmamentV2!.SemanticIntent!.Route == "+Z->-Z") return "side-hole-z-axis-v2";
        if (report.FirmamentV2!.SemanticIntent!.Route == "-Z->+Z") return "side-hole-reverse-z-v2";
        if (report.FirmamentV2!.SemanticIntent!.AttachTargetKind == "Alias" || report.FirmamentV2!.SemanticIntent!.ThroughTargetKind == "Alias") return "side-hole-aliases-v2";
        if (Math.Abs(centerU) > 1e-12 || Math.Abs(centerV) > 1e-12)
        {
            static string Tok(double v) => v.ToString("0.############", System.Globalization.CultureInfo.InvariantCulture).Replace('.', '_').Replace("-", "neg");
            var parts = new List<string>();
            if (Math.Abs(centerU) > 1e-12) parts.Add($"y{Tok(centerU)}");
            if (Math.Abs(centerV) > 1e-12) parts.Add($"z{Tok(centerV)}");
            return $"side-hole-center-{string.Join("-", parts)}-v2";
        }
        if (Math.Abs(radius - 1.0) < 1e-12) return "side-hole-v2";
        var token = radius.ToString("0.############", System.Globalization.CultureInfo.InvariantCulture).Replace('.', '_');
        return $"side-hole-radius-{token}-v2";
    }

    private static string StepText(AirTraceReport report, string stem) => "ISO-10303-21;\n" +
        "HEADER;\nFILE_DESCRIPTION(('AIR-REGION-X13 controlled side-hole golden path artifact'),'2;1');\n" +
        $"FILE_NAME('{stem}.step','2026-06-18T00:00:00Z',('Aetheris'),('Aetheris'),'Aetheris.CLI trace','Aetheris','');\n" +
        "FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }'));\nENDSEC;\n" +
        "DATA;\n" +
        $"/* controlled fixture only: {report.FixturePath} */\n" +
        "/* stage=region-parent-integrated; parentIntegration=Integrated; shellClosure=Closed; stepSmoke=Succeeded */\n" +
        "/* materialized: CutEntryLoop, CutExitLoop, CutWallFace, RegionIntegrationPatchConsumed */\n" +
        "/* cylindrical cut wall evidence; CIR analysis-only; Boolean unused/not generally admitted */\n" +
        $"#1=PRODUCT('{(IsFirmamentV2SideHole(report) ? "AIR-FIRMAMENT-X9-SIDE-HOLE-V2" : "AIR-REGION-X13-SIDE-HOLE")}','controlled side-hole golden path','generated-on-demand fixture artifact',());\n" +
        "ENDSEC;\nEND-ISO-10303-21;\n";
}

public static class CliRunner
{
    private sealed record CompareSideResult(
        bool Success,
        string StepPath,
        AnalyzeResult? Analysis,
        StepAnalyzer.VolumeAnalysisResult? Volume,
        string? ErrorKind,
        string? Error,
        string? Classification = null,
        int? RigidRootCount = null);
    private const string TopLevelUsage = "Usage: aetheris <command> [options]";
    private const string BuildUsage = "Usage: aetheris build <file.firmament|file.firmasm> [--output <path>] [--locked] [--json]";
    private const string MeshUsage = "Usage: aetheris mesh <file.firmament|file.firmfixture|file.firmasm|file.step> [--format stl|obj|glb|assembly-json|display-json] [--output <path>] [--step-output <path> (display-json only)] [--debug-ir <path>] [--json] (glb: MeshState sources)";
    private const string ValidateUsage = "Usage: aetheris validate <file.firmament|file.firmfixture> [--locked] [--forge-pack <path>] [--parse-only] [--explain] [--shadow [--ast]] [--json]";
    private const string InspectProfileUsage = "Usage: aetheris inspect-profile <file.firmament> [--json]";
    private const string InspectSpansUsage = "Usage: aetheris inspect-spans <file.firmament> --json";
    private const string InspectComposeUsage = "Usage: aetheris inspect-compose <file.firmament> --json [--materialize]";
    private const string InspectSelectionsUsage = "Usage: aetheris inspect-selections <file.firmament> --json";
    private const string AnalyzeUsage = "Usage: aetheris analyze <file.step> [--face <id>] [--edge <id>] [--vertex <id>] [--json]";
    private const string AnalyzeMapUsage = "Usage: aetheris analyze map <file.step> (--plane <xy|xz|yz> --direction <+x|-x|+y|-y|+z|-z> | --views six --llm) --resolution <NxM> [--point <u,v>] [--rank-probes|--evidence-bundle] --json";
    private const string AnalyzeSectionUsage = "Usage: aetheris analyze section <file.step> ((--xy|--xz|--yz) --offset <value>|--origin <x,y,z> --normal <x,y,z>) [--out <section.svg>] [--json]";
    private const string AnalyzeVolumeUsage = "Usage: aetheris analyze volume <file.step> [--approximate --resolution <N>] [--json]";
    private const string AnalyzeCompareUsage = "Usage: aetheris analyze compare <reference.step> <candidate.step> [--approximate-volume --resolution <N>] [--shape [--shape-resolution <N>]] [--json]";
    private const string AnalyzeCompoundUsage = "Usage: aetheris analyze compound <file.step> [--json]";
    private const string AnalyzeAssemblyUsage = "Usage: aetheris analyze assembly <file.step> [--json]";
    private const string SectionsUsage = "Usage: aetheris sections <artifact.step> --axis Z --levels <z,...> [--epsilon <mm>] --json";
    private const string VerifyUsage = "Usage: aetheris verify <file.firmament|file.step> [--expected-volume <value>] [--cad-assistant] [--cad-assistant-path <path>] [--timeout <seconds>] [--evidence-dir <path>] [--require-external] [--json]";
    private const string InspectUsage = "Usage: aetheris inspect <file.firmament|file.firmasm|file.step> [--json] [assembly: --profile --repeat <1..16>]";
    private const string ViewUsage = "Usage: aetheris view <file.firmament|file.step> [--cadmata-path <path>] [--json]";
    private const string MatchUsage = "Usage: aetheris match <file.step> <concept.firmament> [--linear-tolerance <mm>] [--angular-tolerance <deg>] [--json]";
    private const string TraceUsage = "Usage: aetheris trace (--case <name>|--fixture <path>) [--out-dir <dir>] [--json]";
    private const string CanonUsage = "Usage: aetheris canon <file.step> --out <canonical.step> [--mode deterministic|production] [--json]";
    private const string AsmExecUsage = "Usage: aetheris asm exec <file.firmasm> [--json]";
    private const string AsmExportUsage = "Usage: aetheris asm export <file.firmasm> --out <directory> [--json]";
    private const string AsmInspectUsage = "Usage: aetheris asm inspect <assembly.firmament|assembly.firmasm> [--json] [--profile] [--repeat <1..16>] [--out <report.json>]";
    private const string AsmImportStepUsage = "Usage: aetheris asm import-step <assembly.step> --out <directory> [--json]";
    private const string AsmExportAp242Usage = "Usage: aetheris asm export-ap242 <assembly.firmament|assembly.firmasm> --out <assembly.step> [--json]";
    private const string ExperimentalUsage = "Usage: aetheris experimental <airchamfer-cube|airchamfer-corpus|prismatic-corpus|prismatic-map|loop-chamfer-corpus|heightfield-art> [options]";
    private const string ExperimentalHeightFieldArtUsage = "Usage: aetheris experimental heightfield-art <plastic-shell.firmament> --out <art.step> [--json]";
    private const string ExperimentalAirChamferCubeUsage = "Usage: aetheris experimental airchamfer-cube --out <path> [--json]";
    private const string ExperimentalAirChamferCorpusUsage = "Usage: aetheris experimental airchamfer-corpus --out-dir <dir> [--json]";
    private const string ExperimentalPrismaticCorpusUsage = "Usage: aetheris experimental prismatic-corpus --out-dir <dir> [--json]";
    private const string ExperimentalPrismaticMapUsage = "Usage: aetheris experimental prismatic-map --case <case> --rows <N> --cols <N> --json";
    private const string FeaUsage = "Usage: aetheris fea <analysis.firmament> [--lattice <nx,ny,nz>] [--rotate <x,y,z-degrees>] [--experimental-preconditioner <identity|jacobi|block-jacobi|ic0>] [--experimental-equilibration <true|false>] [--out-dir <directory>] [--json]";
    private const string DrawingUsage = "Usage: aetheris drawing <compile|generate> <drawing.firmament|part.firmament|model.step> --out-dir <directory> [--drawn-by <name> --date <yyyy-MM-dd>] [--checked-by <name> --checked-date <yyyy-MM-dd>] [--approved-by <name> --approved-date <yyyy-MM-dd>] [--json] | generate options: [--linear-tolerance <mm>] [--angular-tolerance <degrees>] [--material <name>] [--reference-only] | aetheris drawing <inspect|render|crop|notes> ...";
    private const string SheetMetalUsage = "Usage: aetheris sheetmetal recognize <part.step> [--plan <recognition.json>] [--json] | aetheris sheetmetal recover-flat <part.step> --out-dir <directory> [--recognition-plan <recognition.json>] [--json] | aetheris sheetmetal compare-flat <recovered-flat.json> <native.firmament> [--semantic] [--json] | aetheris sheetmetal inspect <part.step|part.firmament> [--k-factor <0..1>] [--json] | aetheris sheetmetal paths <part.firmament> [--json] | aetheris sheetmetal recover <part.step> --out-dir <directory> [--json] | aetheris sheetmetal compare <part.step|part.firmament> <intent.firmament> [--semantic] [--json] | aetheris sheetmetal flatten <part.step|part.firmament> [--step <flat.step>] [--firmament <recovered.firmament>] [--svg <flat.svg>] [--k-factor <0..1>] [--json]";
    private const string ExperimentalLoopChamferCorpusUsage = "Usage: aetheris experimental loop-chamfer-corpus --out-dir <dir> [--json]";
    private const string SculptureUsage = "Usage: aetheris sculpture build <sol-1.sculpture.json> [--out <sol-1.step>] [--evidence <sol-1.evidence.json>] [--preview <sol-1.preview.svg>] [--json]";
    private const string SectionChainUsage = "Usage: aetheris section-chain <build|inspect|validate> <file.firmament|flagship|flagship-g0|twist|two-profile> [--out <model.step>] [--json]";
    private const string WireframeUsage = "Usage: aetheris wireframe <model.step> [--out <preview.svg>] [--view <iso|iso-z|front|top|right>] [--density <2..32>] [--samples <8..256>] [--json]";

    internal static readonly JsonSerializerOptions JsonOptions = new()
    {
        WriteIndented = true,
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        // Numerical diagnostics may intentionally expose an unbounded conditioning proxy.
        NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals
    };

    static CliRunner()
    {
        JsonOptions.Converters.Add(new JsonStringEnumConverter());
    }

    public static int Run(string[] args, TextWriter stdout, TextWriter stderr)
        => Run(args, stdout, stderr, new SystemCadmataProcessLauncher(), AppContext.BaseDirectory);

    private static int WriteThreeDmHelp(string operation, TextWriter stdout)
    {
        CommandHelp.Write(stdout, $"aetheris-3dm {operation} <model.3dm> [--json]",
            "3DM interoperability is an optional tool. Install it with: dotnet tool install --global Aetheris.ThreeDm.CLI --prerelease",
            $"aetheris-3dm {operation} model.3dm --json");
        return 0;
    }

    private static int MissingThreeDmTool(TextWriter stderr)
    {
        stderr.WriteLine("aetheris-3dm-required: 3DM interoperability is an optional tool. Install with 'dotnet tool install --global Aetheris.ThreeDm.CLI --prerelease', then use 'aetheris-3dm inspect' or 'aetheris-3dm recover'.");
        return 1;
    }

    internal static int Run(string[] args, TextWriter stdout, TextWriter stderr, ICadmataProcessLauncher cadmataLauncher, string cliBaseDirectory)
    {
        if (args.Length == 0)
        {
            stderr.WriteLine(TopLevelUsage);
            stderr.WriteLine("Run 'aetheris --help' for command discovery and examples.");
            return 1;
        }

        if (IsTopLevelHelpRequest(args[0]))
        {
            WriteTopLevelHelp(stdout);
            return 0;
        }

        if (IsVersionFlag(args[0]))
        {
            stdout.WriteLine($"aetheris {GetDisplayVersion()}");
            return 0;
        }

        try
        {
            return args[0] switch
            {
                "build" => RunBuild(args.Skip(1).ToArray(), stdout, stderr),
                "mesh" => RunMesh(args.Skip(1).ToArray(), stdout, stderr),
                "validate" => RunValidate(args.Skip(1).ToArray(), stdout, stderr),
                "frontend-shadow" => FrontendShadowCommand.Run(args.Skip(1).ToArray(), stdout, stderr),
                "format" => RunFormat(args.Skip(1).ToArray(), stdout, stderr),
                "imported-features" => ImportedFeaturesCommand.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),
                "lock" => DependencyLockCommand.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),
                "inspect" => RunInspect(args.Skip(1).ToArray(), stdout, stderr),
                "measure" => FirmamentMeasureCommand.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),
                "inspect-3dm" => args.Length == 2 && IsHelpFlag(args[1]) ? WriteThreeDmHelp("inspect", stdout) : MissingThreeDmTool(stderr),
                "recover-3dm" => args.Length == 2 && IsHelpFlag(args[1]) ? WriteThreeDmHelp("recover", stdout) : MissingThreeDmTool(stderr),
                "inspect-profile" => RunInspectProfile(args.Skip(1).ToArray(), stdout, stderr),
                "inspect-spans" => RunInspectSpans(args.Skip(1).ToArray(), stdout, stderr),
                "inspect-compose" => RunInspectCompose(args.Skip(1).ToArray(), stdout, stderr),
                "inspect-selections" => RunInspectSelections(args.Skip(1).ToArray(), stdout, stderr),
                "sections" => RunSections(args.Skip(1).ToArray(), stdout, stderr),
                "analyze" => RunAnalyze(args.Skip(1).ToArray(), stdout, stderr),
                "fea" => RunFea(args.Skip(1).ToArray(), stdout, stderr),
                "drawing" => RunDrawing(args.Skip(1).ToArray(), stdout, stderr),
                "presentation" => Presentation3DCommand.Run(args.Skip(1).ToArray(), stdout, stderr),
                "verify" => RunVerify(args.Skip(1).ToArray(), stdout, stderr),
                "view" => RunView(args.Skip(1).ToArray(), stdout, stderr, cadmataLauncher, cliBaseDirectory),
                "match" => RunMatch(args.Skip(1).ToArray(), stdout, stderr),
                "trace" => RunTrace(args.Skip(1).ToArray(), stdout, stderr),
                "canon" => RunCanon(args.Skip(1).ToArray(), stdout, stderr),
                "asm" => RunAsm(args.Skip(1).ToArray(), stdout, stderr),
                "garment" => GarmentCommand.Run(args.Skip(1).ToArray(), stdout, stderr),
                "scene" => SceneCommand.Run(args.Skip(1).ToArray(), stdout, stderr),
                "experimental" => RunExperimental(args.Skip(1).ToArray(), stdout, stderr),
                "modules" => RunModules(args.Skip(1).ToArray(), stdout, stderr),
                "sheetmetal" => RunSheetMetal(args.Skip(1).ToArray(), stdout, stderr),
                "sculpture" => RunSculpture(args.Skip(1).ToArray(), stdout, stderr),
                "section-chain" => RunSectionChain(args.Skip(1).ToArray(), stdout, stderr),
                "wireframe" => RunWireframe(args.Skip(1).ToArray(), stdout, stderr),
                "reconstruct" => ReconstructionCli.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),
                "continuum" => ContinuumToolsCli.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),
                _ => UnknownCommand(args[0], stderr)
            };
        }
        catch (FileNotFoundException ex)
        {
            var diagnostic = new FirmamentV2ValidationDiagnostic("source-file-not-found", "error",
                $"Source or referenced input file '{ex.FileName}' was not found. Check the path and the working directory.")
            { SourceFile = ex.FileName, Stage = "Input", LocationNote = "No source span is available because the file could not be opened." };
            if (args.Contains("--json", StringComparer.Ordinal))
                stdout.WriteLine(JsonSerializer.Serialize(new { command = args[0], success = false, diagnostics = new[] { diagnostic } }, JsonOptions));
            else stderr.WriteLine($"{ex.FileName}: error {diagnostic.Code}: {diagnostic.Message}");
            return 1;
        }
        catch (Exception ex)
        {
            stderr.WriteLine(ex.Message);
            return 1;
        }
    }

    private static int RunFormat(string[] args, TextWriter stdout, TextWriter stderr)
    {
        const string usage = "Usage: aetheris format <file.firmament|file.firmasm>... [--write] [--json] (convention spellings; preserves layout and authored identities)";
        if (args.Length == 0 || IsHelpFlag(args[0])) { CommandHelp.Write(stdout, usage, "Format canonical Firmament spellings while preserving layout and authored names. Add --write to update the source.", "aetheris format bracket.firmament --write"); return args.Length == 0 ? 1 : 0; }
        var write = args.Contains("--write", StringComparer.Ordinal);
        var json = args.Contains("--json", StringComparer.Ordinal);
        var paths = args.Where(a => a is not ("--write" or "--json")).ToArray();
        if (paths.Length == 0 || paths.Any(p => p.StartsWith('-') || Path.GetExtension(p) is not (".firmament" or ".firmasm")))
        { stderr.WriteLine(usage); return 1; }
        // Prepare the entire batch before writing; a missing input cannot leave a partial sweep.
        var formats = paths.Distinct(StringComparer.OrdinalIgnoreCase).Select(path =>
        {
            var fullPath = Path.GetFullPath(path);
            return FirmamentLanguageAnalysisService.FormatConventions(File.ReadAllText(fullPath), fullPath, "cli");
        }).ToArray();
        if (write)
            foreach (var format in formats.Where(f => f.Changed)) File.WriteAllText(format.Document, format.Text, new System.Text.UTF8Encoding(false));
        if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "format", mode = "conventions", written = write,
            validation = "spelling equivalence; validate the consuming project separately", files = formats.Select(f => new { path = f.Document, changed = f.Changed }) }, JsonOptions));
        else foreach (var format in formats)
            stdout.WriteLine(write ? $"{format.Document}: {(format.Changed ? "formatted" : "unchanged")}" : format.Text);
        return 0;
    }

    private static int RunVerify(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0])) { WriteVerifyHelp(stdout); return args.Length == 0 ? 1 : 0; }
        var stepPath = args[0];
        var json = false;
        var requestCadAssistant = false;
        var requireExternal = false;
        double? expectedVolume = null;
        string? cadPath = null;
        string? evidenceRoot = null;
        var timeout = TimeSpan.FromSeconds(30);
        for (var i = 1; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--cad-assistant": requestCadAssistant = true; break;
                case "--cad-assistant-path" when i + 1 < args.Length: cadPath = args[++i]; requestCadAssistant = true; break;
                case "--timeout" when i + 1 < args.Length && double.TryParse(args[++i], out var seconds) && seconds > 0d: timeout = TimeSpan.FromSeconds(seconds); break;
                case "--evidence-dir" when i + 1 < args.Length: evidenceRoot = args[++i]; break;
                case "--expected-volume" when i + 1 < args.Length && double.TryParse(args[++i], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var expected) && expected >= 0d: expectedVolume = expected; break;
                case "--require-external": requireExternal = true; requestCadAssistant = true; break;
                case "--json": json = true; break;
                default: stderr.WriteLine($"Unknown verify option '{args[i]}'."); stderr.WriteLine(VerifyUsage); return 1;
            }
        }
        if (string.Equals(Path.GetExtension(stepPath), ".firmament", StringComparison.OrdinalIgnoreCase))
        {
            var sourceText = File.Exists(stepPath) ? File.ReadAllText(stepPath) : string.Empty;
            if (PlasticShellFirmament.LooksLikePlasticShell(sourceText))
            {
                var plastic = PlasticShellFirmament.Compile(sourceText, Path.GetFullPath(stepPath));
                var plasticExport = plastic.State is null ? null : PlasticShellStepExporter.Export(plastic.State, plastic.ModelName);
                if (!plastic.IsSuccess || plasticExport?.IsSuccess != true || plasticExport.Step is null)
                {
                    var messages = plastic.Diagnostics.Select(x => $"{x.Code}: {x.Message}").Concat(plasticExport?.Diagnostics.Select(x => $"{x.Code}: {x.Message}") ?? []);
                    if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "verify", success = false, input = Path.GetFullPath(stepPath), diagnostics = messages }, JsonOptions));
                    else foreach (var message in messages) stderr.WriteLine($"error: {message}");
                    return 1;
                }
                var plasticStepPath = Path.ChangeExtension(Path.GetFullPath(stepPath), ".step"); File.WriteAllText(plasticStepPath, plasticExport.Step); stepPath = plasticStepPath;
            }
            else if (SculptingAuthoring.IsSculptingSource(sourceText))
            {
                var sculpt = SculptingAuthoring.Compile(sourceText);
                if (sculpt.OutputMesh is not null) return MeshSculptCommand.Write(sculpt, stepPath, null, "step", "verify", json, stdout, stderr);
                var sculptExport = sculpt.OutputState is null ? null : SculptStepExporter.Export(sculpt.OutputState, sculpt.ModelName);
                if (!sculpt.IsSuccess || sculptExport?.IsSuccess != true || sculptExport.Step is null)
                {
                    var messages = sculpt.Diagnostics.Select(x => $"{x.Code}: {x.Message}").Concat(sculptExport?.Diagnostics.Select(x => $"{x.Code}: {x.Message}") ?? []);
                    if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "verify", success = false, input = Path.GetFullPath(stepPath), diagnostics = messages }, JsonOptions));
                    else foreach (var message in messages) stderr.WriteLine($"error: {message}");
                    return 1;
                }
                var sculptStepPath = Path.ChangeExtension(Path.GetFullPath(stepPath), ".step"); File.WriteAllText(sculptStepPath, sculptExport.Step); stepPath = sculptStepPath;
            }
            else
            {
            var build = FirmamentBuildAndExport.Run(stepPath);
            if (!build.IsSuccess)
            {
                if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "verify", success = false, input = Path.GetFullPath(stepPath), diagnostics = build.Diagnostics.Select(d => new { d.Source, d.Message, severity = d.Severity.ToString() }) }, JsonOptions));
                else { stderr.WriteLine("Verification stopped because build failed."); foreach (var diagnostic in build.Diagnostics) stderr.WriteLine($"error: {diagnostic.Message}"); }
                return 1;
            }
            stepPath = build.Value.OutputPath;
            }
        }
        else if (!string.Equals(Path.GetExtension(stepPath), ".step", StringComparison.OrdinalIgnoreCase) && !string.Equals(Path.GetExtension(stepPath), ".stp", StringComparison.OrdinalIgnoreCase))
        {
            stderr.WriteLine("Verify expects Firmament (.firmament) or STEP (.step, .stp) input.");
            return 1;
        }
        if (!File.Exists(stepPath)) { stderr.WriteLine($"STEP artifact '{stepPath}' does not exist."); return 1; }
        var fullPath = Path.GetFullPath(stepPath);
        var hash = Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(fullPath))).ToLowerInvariant();
        var fixtureName = Path.GetFileNameWithoutExtension(fullPath);
        var evidenceDir = Path.GetFullPath(evidenceRoot ?? Path.Combine("artifacts", "local", "verification", fixtureName, hash));
        Directory.CreateDirectory(evidenceDir);
        File.Copy(fullPath, Path.Combine(evidenceDir, "model.step"), overwrite: true);

        object report;
        CadAssistantInspectionResult? external = null;
        BrepMassPropertiesResult? massProperties = null;
        AnalyzeResult? reimportAnalysis = null;
        try
        {
            var import = Step242Importer.ImportBody(File.ReadAllText(fullPath));
            if (!import.IsSuccess) throw new InvalidOperationException(string.Join("; ", import.Diagnostics.Select(d => d.Message)));
            massProperties = BrepMassProperties.Evaluate(import.Value);
            reimportAnalysis = StepAnalyzer.AnalyzeImportedBody(import.Value, fullPath);
            if (requestCadAssistant)
            {
                external = CadAssistantInspection.Inspect(fullPath, new CadAssistantInspectionOptions(cadPath, timeout, evidenceDir));
            }
            var overall = massProperties.Status == BrepMassPropertiesStatus.Unavailable
                ? "BRepRejected"
                : external?.Status == CadAssistantInspectionStatus.Unavailable
                ? "ExternalInspectionPending"
                : external is null ? "ExternalInspectionPending"
                : external.Status is CadAssistantInspectionStatus.Displayed or CadAssistantInspectionStatus.InspectionCompleted ? "ExternallyDisplayed"
                : massProperties.Status != BrepMassPropertiesStatus.Unavailable ? "BRepVerified" : "Rejected";
            ArtifactMassComparisonEvidence? comparison = null;
            if (expectedVolume.HasValue && massProperties.Status != BrepMassPropertiesStatus.Unavailable)
            {
                var delta = massProperties.AbsoluteVolume - expectedVolume.Value;
                var relative = expectedVolume.Value > 1e-12d ? delta / expectedVolume.Value : delta;
                comparison = new ArtifactMassComparisonEvidence(expectedVolume.Value, massProperties.AbsoluteVolume, delta, relative, Math.Abs(delta) <= (massProperties.ErrorBound ?? 0d));
            }
            report = new ArtifactVerificationResult(
                new ArtifactIdentity(fullPath, hash, evidenceDir),
                new ArtifactProducerEvidence("ArtifactOnly", "verify consumes an existing STEP artifact; compiler preflight evidence is not reconstructed."),
                massProperties,
                comparison,
                new ArtifactStepReimportEvidence("Valid", reimportAnalysis),
                (object?)external ?? new { status = "NotRequested", availability = "Unknown" },
                overall);
        }
        catch (Exception ex)
        {
            report = new { artifact = new { path = fullPath, sha256 = hash, evidenceDirectory = evidenceDir }, overallAdmission = "Rejected", error = ex.Message };
        }
        var reportPath = Path.Combine(evidenceDir, "verification-report.json");
        File.WriteAllText(reportPath, JsonSerializer.Serialize(report, JsonOptions));
        if (massProperties is not null) File.WriteAllText(Path.Combine(evidenceDir, "mass-properties.json"), JsonSerializer.Serialize(massProperties, JsonOptions));
        if (reimportAnalysis is not null) File.WriteAllText(Path.Combine(evidenceDir, "aetheris-analyze.json"), JsonSerializer.Serialize(reimportAnalysis, JsonOptions));
        if (external is not null) File.WriteAllText(Path.Combine(evidenceDir, "cad-assistant-inspection.json"), JsonSerializer.Serialize(external, JsonOptions));
        File.WriteAllText(Path.Combine(evidenceDir, "verification-summary.md"), $"# Artifact verification\n\n- Artifact: `{fullPath}`\n- SHA-256: `{hash}`\n- Report: `verification-report.json`\n- External inspection: `{external?.Status.ToString() ?? "NotRequested"}`\n");
        if (json) stdout.WriteLine(JsonSerializer.Serialize(report, JsonOptions));
        else stdout.WriteLine($"Verification report: {reportPath}");
        return requireExternal && external?.Status == CadAssistantInspectionStatus.Unavailable ? 2 : 0;
    }

    private static int RunMatch(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0]))
        {
            WriteMatchHelp(stdout);
            return args.Length == 0 ? 1 : 0;
        }
        if (args.Length < 2 || args[0].StartsWith("-", StringComparison.Ordinal) || args[1].StartsWith("-", StringComparison.Ordinal)) { stderr.WriteLine(MatchUsage); return 1; }
        var step = args[0]; var concept = args[1]; var json = false; var linear = 0.01d; var angular = 0.1d;
        for (var i = 2; i < args.Length; i++)
        {
            if (args[i] == "--json") { json = true; continue; }
            if (args[i] == "--linear-tolerance" && i + 1 < args.Length && double.TryParse(args[++i], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out linear) && linear >= 0) continue;
            if (args[i] == "--angular-tolerance" && i + 1 < args.Length && double.TryParse(args[++i], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out angular) && angular >= 0) continue;
            stderr.WriteLine($"Unknown or invalid match option '{args[i]}'."); stderr.WriteLine(MatchUsage); return 1;
        }
        var report = ConceptStepMatcher.Match(step, concept, new(linear, angular, linear));
        if (json) stdout.WriteLine(JsonSerializer.Serialize(new { conceptStepMatch = report }, JsonOptions));
        else stdout.WriteLine($"{report.Status}: {report.ConceptStruct} against {step} ({report.Members.Count} members)");
        return report.Status is ConceptStepOverallStatus.Conflicted or ConceptStepOverallStatus.InvalidConcept or ConceptStepOverallStatus.InvalidStep ? 1 : 0;
    }

    private static int RunBuild(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0)
        {
            stderr.WriteLine(BuildUsage);
            stderr.WriteLine("Run 'aetheris build --help' for examples.");
            return 1;
        }

        if (IsHelpFlag(args[0]))
        {
            WriteBuildHelp(stdout);
            return 0;
        }

        if (args[0].StartsWith("-", StringComparison.Ordinal))
        {
            stderr.WriteLine("Build requires <file.firmament> as the first argument.");
            stderr.WriteLine(BuildUsage);
            return 1;
        }

        var sourcePath = args[0];
        string? outPath = null;
        var json = false;
        var locked = false;

        for (var i = 1; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--output" when i + 1 < args.Length:
                case "--out" when i + 1 < args.Length: // Compatibility alias; prefer --output in public help.
                    outPath = args[++i];
                    break;
                case "--output":
                case "--out":
                    stderr.WriteLine("Build option --output requires a path value.");
                    stderr.WriteLine(BuildUsage);
                    return 1;
                case "--json":
                    json = true;
                    break;
                case "--locked":
                    locked = true;
                    break;
                case "-h":
                case "--help":
                    WriteBuildHelp(stdout);
                    return 0;
                default:
                    stderr.WriteLine($"Unknown build option '{args[i]}'.");
                    stderr.WriteLine(BuildUsage);
                    return 1;
            }
        }

        FirmamentCommandDomain? domain = null;
        if (File.Exists(sourcePath))
        {
            if (!DependencyLockCommand.Verify(sourcePath, locked, json, stdout, stderr, JsonOptions, "build")) return 1;
            var source = File.ReadAllText(sourcePath);
            var frontend = FirmamentFrontendSchemas.Select(source);
            if (!frontend.IsSuccess) return WriteFrontendRejection(frontend, source, sourcePath, "build", json, stdout, stderr);
            source = frontend.Source;
            domain = FirmamentCommandRouting.Select(source, sourcePath, frontend.Schema);
            if((domain == FirmamentCommandDomain.Drawing||domain == FirmamentCommandDomain.Analysis) && outPath is not null && Path.GetExtension(outPath).Equals(".step",StringComparison.OrdinalIgnoreCase))
            {
                var diagnostic=FirmamentBuildAdmissionValidation.Present(new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed,KernelDiagnosticSeverity.Error,
                    "firmament-product-output-directory-required: Drawing and Analysis builds produce artifact directories. Use --out <directory>; export the geometry source separately for STEP.","Firmament.Build"),sourcePath,source);
                if(json)stdout.WriteLine(JsonSerializer.Serialize(new {command="build",success=false,diagnostics=new[]{diagnostic}},JsonOptions));
                else stderr.WriteLine($"{sourcePath}:{diagnostic.Line}:{diagnostic.Column}: {diagnostic.Severity} {diagnostic.Code}: {diagnostic.Message}");
                return 1;
            }
            if(domain == FirmamentCommandDomain.Drawing)
                return RunDrawing(["compile",sourcePath,"--out-dir",outPath??Path.GetFullPath(Path.Combine("artifacts","local","drawing",Path.GetFileNameWithoutExtension(sourcePath))),..(json?new[]{"--json"}:[])],stdout,stderr);
            if (domain == FirmamentCommandDomain.Analysis)
                return RunFea([sourcePath,"--out-dir",outPath??Path.GetFullPath(Path.Combine("artifacts","local","analysis",Path.GetFileNameWithoutExtension(sourcePath))),..(json?new[]{"--json"}:[])],stdout,stderr);
            if (domain == FirmamentCommandDomain.Garment)
            { stderr.WriteLine("garment-step-export-unsupported: Fabric is a material-space surface; use garment build or garment drape."); return 1; }
            if (domain == FirmamentCommandDomain.Scene)
            { stderr.WriteLine("scene-step-export-unsupported: Scene is a spatial product; use scene export-usd or scene export-glb."); return 1; }
            if (domain == FirmamentCommandDomain.Assembly)
                return RunAsmExportAp242([sourcePath, "--out", outPath ?? Path.GetFullPath(Path.Combine("artifacts", "local", "build", Path.GetFileNameWithoutExtension(sourcePath) + ".step")), .. (json ? new[] { "--json" } : [])], stdout, stderr);
            if (domain == FirmamentCommandDomain.SectionChain)
                return RunSectionChain(["build", sourcePath, .. (outPath is null ? Array.Empty<string>() : ["--out", outPath]), .. (json ? new[] { "--json" } : [])], stdout, stderr);
        }
        if (domain == FirmamentCommandDomain.PlasticShell)
            return RunPlasticShellBuild(sourcePath, outPath, json, stdout, stderr);
        if (domain == FirmamentCommandDomain.Mold)
            return RunMoldBuild(sourcePath, outPath, json, stdout, stderr);
        if (domain == FirmamentCommandDomain.SheetMetal)
            return RunSheetMetalAuthoredBuild(sourcePath, outPath, json, stdout, stderr);
        if (domain == FirmamentCommandDomain.Sculpting)
            return RunSculptingBuild(sourcePath, outPath, json, stdout, stderr);

        var build = FirmamentBuildAndExport.Run(sourcePath, outPath);
        var diagnosticSource = File.ReadAllText(sourcePath);
        if (!build.IsSuccess)
        {
            if (json)
            {
                stdout.WriteLine(JsonSerializer.Serialize(new
                {
                    command = "build",
                    success = false,
                    input = Path.GetFullPath(sourcePath),
                    diagnostics = build.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, sourcePath, diagnosticSource))
                }, JsonOptions));
            }
            else
            {
                stderr.WriteLine("Build failed:");
                foreach (var diagnostic in build.Diagnostics)
                {
                    var presented = FirmamentBuildAdmissionValidation.Present(diagnostic, sourcePath, diagnosticSource);
                    stderr.WriteLine($"{sourcePath}({presented.Line},{presented.Column}): {presented.Severity} {presented.Code}: {presented.Message}");
                }
            }

            return 1;
        }

        if (json)
        {
            stdout.WriteLine(JsonSerializer.Serialize(new
            {
                command = "build",
                success = true,
                input = build.Value.SourcePath,
                output = build.Value.OutputPath,
                sourcePath = build.Value.SourcePath,
                outputPath = build.Value.OutputPath,
                model = build.Value.Export.DocumentName ?? build.Value.Export.ExportedFeatureId,
                conceptIr = build.Value.Export.ConceptIr,
                air = build.Value.Export.Air,
                plateau = build.Value.Export.Plateau,
                roundedBox = build.Value.Export.RoundedBox,
                hollow = build.Value.Export.Hollow,
                lattice = build.Value.Export.Lattice,
                combined = build.Value.Export.Combined,
                standardPart = build.Value.Export.StandardPart,
                wireForm = build.Value.Export.WireForm,
                sweep = build.Value.Export.Sweep,
                assertions = build.Value.Export.Assertions,
                geometryAssertions = build.Value.Export.GeometryAssertions,
                features = build.Value.Export.Features,
                engineeringFeatures = build.Value.Export.EngineeringFeatures,
                materializedFeatures = build.Value.Export.MaterializedFeatures,
                edgeFinishPlanning = build.Value.Export.EdgeFinishPlanning,
                ribPlanning = build.Value.Export.RibPlanning,
                patterns = build.Value.Export.Patterns,
                perforation = build.Value.Export.Perforation,
                structural = build.Value.Export.Structural,
                piping = build.Value.Export.Piping,
                gear = build.Value.Export.Gear,
                thread = build.Value.Export.Thread,
                featureCount = (build.Value.Export.Features?.Count ?? 0) + (build.Value.Export.EngineeringFeatures?.Count ?? 0) + (build.Value.Export.Perforation is null ? 0 : 1) + (build.Value.Export.ImportedHoleRevision is null ? 0 : 1) + (build.Value.Export.ImportedHoleRemoval is null ? 0 : 1),
                inlineStepMigration = build.Value.Export.InlineStepMigration,
                importedHoleRevision = build.Value.Export.ImportedHoleRevision,
                importedHoleRemoval = build.Value.Export.ImportedHoleRemoval,
                inlineStepReplacementAssist = build.Value.Export.InlineStepReplacementAssist,
                diagnostics = build.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, sourcePath, diagnosticSource)),
                pmiExportEvidence = new
                {
                    datum = (build.Value.Export.DatumInspection ?? []).Select(d => new { kind = "datum", name = d.Label, exportSupport = "supported", exportEvidence = "found", target = d.Target }),
                    diameter = (build.Value.Export.DimensionInspection ?? []).Where(d => string.Equals(d.Kind, "Diameter", StringComparison.Ordinal)).Select(d => new { kind = "diameter", name = d.CandidateName ?? d.Target, exportSupport = "supported", exportEvidence = "found", target = d.Target, nominal = d.Value })
                }
            }, JsonOptions));
        }
        else
        {
            stdout.WriteLine($"Built {Path.GetFileName(build.Value.SourcePath)}");
            stdout.WriteLine($"STEP: {build.Value.OutputPath}");
            stdout.WriteLine($"Model: {build.Value.Export.DocumentName ?? build.Value.Export.ExportedFeatureId}");
            if (build.Value.Export.StandardPart is { } standardPart)
                stdout.WriteLine($"Standard part: {standardPart.Family} via {standardPart.Template ?? "direct record"} ({standardPart.SemanticDescendants.Count} semantic descendants)");
            if (build.Value.Export.WireForm is { } wireForm)
                stdout.WriteLine($"WireForm: {wireForm.OperationCount} operations, {wireForm.DiameterMm:G6} mm diameter, {wireForm.TotalWireLengthMm:G12} mm stock length ({wireForm.Cylinders} cylinders, {wireForm.Tori} tori)");
            if (build.Value.Export.Sweep is { } sweep)
                stdout.WriteLine($"Sweep: {sweep.SegmentCount} analytic path segments, {sweep.Diameter:G6} mm diameter, {sweep.CenterlineLength:G6} mm centerline ({sweep.Cylinders} cylinders, {sweep.Tori} tori)");
            if (build.Value.Export.Structural is { } structure)
                stdout.WriteLine($"Structure: {structure.Members.Count} members, {structure.Joints.Count} joints, {structure.CutList.Count} cut-list groups; cut list: {structure.CutListArtifactPath}");
            if (build.Value.Export.Piping is { } piping)
                stdout.WriteLine($"Piping system: {piping.Connections.Count} connections, {piping.Routes.Count} routes, {piping.PipeSegments.Count} pipe segments, {piping.Fittings.Count} fittings, {piping.Nozzles.Count} equipment nozzles, {piping.Mates.Count} endpoint mates; routing report: {piping.RoutingReportArtifactPath}");
            if (build.Value.Export.Gear is { } gear)
                stdout.WriteLine($"Gear: {gear.Gears[0].Family} {gear.Gears[0].Name}, {gear.Gears[0].Teeth?.ToString() ?? "n/a"} teeth ({gear.Representation})");
            if (build.Value.Export.Thread is { } thread)
                stdout.WriteLine($"Thread: {thread.MajorDiameterMm:G6} mm major, {thread.RootDiameterMm:G6} mm root, {thread.PitchMm:G6} mm pitch, {thread.Turns} turns");
            foreach (var diagnostic in build.Diagnostics.Where(diagnostic => diagnostic.Severity == KernelDiagnosticSeverity.Warning))
                stderr.WriteLine($"- [Warning] {diagnostic.Source}: {diagnostic.Message}");
        }

        return 0;
    }

    private static int RunSectionChain(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0]))
        {
            stdout.WriteLine("Materialize an ordered semantic SectionChain through local ruled/G0 or polynomial/G1 pairwise transitions.");
            stdout.WriteLine(SectionChainUsage);
            return args.Length == 0 ? 1 : 0;
        }
        if (args.Length < 2 || args[0] is not ("build" or "inspect" or "validate")) { stderr.WriteLine(SectionChainUsage); return 1; }
        var operation = args[0]; var witness = args[1]; string? output = null; var json = false;
        for (var index = 2; index < args.Length; index++)
        {
            if (args[index] == "--json") json = true;
            else if (args[index] == "--out" && index + 1 < args.Length) output = Path.GetFullPath(args[++index]);
            else { stderr.WriteLine(SectionChainUsage); return 1; }
        }
        SectionChainMaterializationResult materialized;
        SectionChain chain;
        IReadOnlyList<SectionChainProfileDerivation>? profileDerivations = null;
        IReadOnlyList<SectionChainBoundaryEditInspection>? boundaryEdits = null;
        IReadOnlyList<FirmamentV2CanonicalPatternDecl>? patterns = null;
        if (File.Exists(witness))
        {
            var authored = SectionChainAuthoringParser.CompileFile(witness);
            if (!authored.IsSuccess || authored.Chain is null || authored.Materialization is null)
            {
                var source = File.ReadAllText(witness);
                var diagnostics = authored.Diagnostics.Select(message => FirmamentBuildAdmissionValidation.Present(
                    new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, "Firmament.SectionChain"), witness, source)).ToArray();
                var failure = new { command = $"section-chain {operation}", success = false, input = Path.GetFullPath(witness), diagnostics };
                if (json) stdout.WriteLine(JsonSerializer.Serialize(failure, JsonOptions));
                else WriteFrontendDiagnostics(diagnostics, stderr);
                return 1;
            }
            chain = authored.Chain; materialized = authored.Materialization;
            profileDerivations = authored.ProfileDerivations;
            boundaryEdits = authored.BoundaryEdits;
            patterns = authored.Patterns;
        }
        else
        {
            chain = witness switch
            {
                "flagship" => SectionChainTemplates.ErgonomicFairingG1(),
                "flagship-g0" => SectionChainTemplates.ErgonomicFairing("surf-x4-section-chain-ergonomic-g0", smooth: false),
                "twist" => SectionChainTemplates.TwistWitness(),
                "two-profile" => SectionChainTemplates.TwoProfileRuled(),
                _ => throw new ArgumentException($"Unknown SectionChain witness '{witness}'.")
            };
            materialized = SectionChainMaterializer.Materialize(chain);
        }
        output ??= Path.GetFullPath(Path.Combine("artifacts", "local", "surf-x3", chain.StableId + ".step"));
        if (!materialized.IsSuccess)
        {
            var failure = new { command = "section-chain build", success = false, witness, diagnostics = materialized.Diagnostics };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(failure, JsonOptions));
            else foreach (var diagnostic in materialized.Diagnostics) stderr.WriteLine($"error: {diagnostic.Code}: {diagnostic.Message}");
            return 1;
        }
        if (operation is "inspect" or "validate")
        {
            var inspection = new
            {
                command = $"section-chain {operation}", success = true, chain.StableId,
                profileDerivations,
                boundaryEdits,
                patterns,
                sections = chain.Sections.Select(section => new { section.SectionId, section.Frame, profile = section.Profile.StableId, spans = section.Profile.Spans.Select(span => span.SpanId), seam = section.Profile.SeamSpanId }),
                chain.Correspondence,
                resolvedCorrespondence = Enumerable.Range(0, chain.Sections.Count - 1).Select(index => new
                {
                    source = chain.Sections[index].SectionId, target = chain.Sections[index + 1].SectionId,
                    resolution = chain.Correspondence.Any(item => item.SourceSectionId == chain.Sections[index].SectionId && item.TargetSectionId == chain.Sections[index + 1].SectionId) ? "Explicit" : "InferredSemanticIdentity",
                    spans = chain.Sections[index].Profile.Spans.Select((span, spanIndex) => new { source = span.SpanId, target = chain.Sections[index + 1].Profile.Spans[spanIndex].SpanId })
                }),
                chain.TransitionPolicy, chain.Continuity, chain.SmoothPolicy, chain.StartTermination, chain.EndTermination,
                transitions = materialized.Transitions, pcurves = materialized.Pcurves, selfIntersection = materialized.SelfIntersection,
                continuityEvidence = materialized.ContinuityEvidence, smoothSelection = materialized.SmoothSelection,
                profileNormalization = materialized.ProfileNormalization, geometricJoins = materialized.GeometricJoins,
                diagnostics = materialized.Diagnostics
            };
            stdout.WriteLine(JsonSerializer.Serialize(inspection, JsonOptions));
            return 0;
        }
        var export = Step242Exporter.ExportBody(materialized.Body!, options: new Step242ExportOptions { ProductName = chain.StableId });
        if (!export.IsSuccess)
        {
            foreach (var diagnostic in export.Diagnostics) stderr.WriteLine($"error: {diagnostic.Message}");
            return 1;
        }
        Directory.CreateDirectory(Path.GetDirectoryName(output)!); File.WriteAllText(output, export.Value);
        var previewPath = Path.ChangeExtension(output, ".preview.svg");
        if (materialized.PreviewSvg is not null) File.WriteAllText(previewPath, materialized.PreviewSvg);
        var reimport = Step242Importer.ImportBody(export.Value);
        var surfaces = materialized.Body!.Geometry.Surfaces.Select(item => item.Value.Kind).GroupBy(kind => kind)
            .ToDictionary(group => group.Key.ToString(), group => group.Count(), StringComparer.Ordinal);
        var report = new
        {
            command = "section-chain build", success = true, witness, output, preview = previewPath, sha256 = Hash(export.Value),
            sectionChain = new
            {
                chain.StableId, sectionCount = chain.Sections.Count, transitionCount = materialized.Transitions.Count,
                sections = chain.Sections.Select(section => new { section.SectionId, frame = section.Frame, profile = section.Profile.StableId, spans = section.Profile.Spans.Select(span => span.SpanId), seam = section.Profile.SeamSpanId }),
                correspondence = chain.Correspondence,
                resolvedCorrespondence = Enumerable.Range(0, chain.Sections.Count - 1).Select(index => new
                {
                    source = chain.Sections[index].SectionId, target = chain.Sections[index + 1].SectionId,
                    resolution = chain.Correspondence.Any(item => item.SourceSectionId == chain.Sections[index].SectionId && item.TargetSectionId == chain.Sections[index + 1].SectionId) ? "Explicit" : "InferredSemanticIdentity",
                    spans = chain.Sections[index].Profile.Spans.Select((span, spanIndex) => new { source = span.SpanId, target = chain.Sections[index + 1].Profile.Spans[spanIndex].SpanId })
                }),
                transitionPolicy = chain.TransitionPolicy,
                continuity = chain.Continuity, smoothPolicy = chain.SmoothPolicy,
                startTermination = chain.StartTermination, endTermination = chain.EndTermination,
                structure = materialized.StructureKind, transitions = materialized.Transitions
            },
            topology = new { bodies = materialized.Body.Topology.Bodies.Count(), shells = materialized.Body.Topology.Shells.Count(), faces = materialized.Body.Topology.Faces.Count(), edges = materialized.Body.Topology.Edges.Count(), vertices = materialized.Body.Topology.Vertices.Count() },
            surfaceInventory = surfaces, rationalProductSurfaces = 0, facetedProductFallback = 0, pcurves = materialized.Pcurves,
            selfIntersection = materialized.SelfIntersection,
            continuityEvidence = materialized.ContinuityEvidence, smoothSelection = materialized.SmoothSelection,
                profileNormalization = materialized.ProfileNormalization, geometricJoins = materialized.GeometricJoins,
            stepReimport = new { success = reimport.IsSuccess, diagnostics = reimport.Diagnostics.Select(item => item.Message) },
            timingsMilliseconds = materialized.Timing
        };
        var evidencePath = Path.ChangeExtension(output, ".evidence.json");
        File.WriteAllText(evidencePath, JsonSerializer.Serialize(report, JsonOptions));
        if (json) stdout.WriteLine(JsonSerializer.Serialize(report, JsonOptions));
        else stdout.WriteLine($"Built SectionChain '{chain.StableId}' ({chain.Sections.Count} sections, {materialized.Transitions.Count} transitions).\nSTEP: {output}\nEvidence: {evidencePath}\nSHA-256: {Hash(export.Value)}\nSTEP reimport: {(reimport.IsSuccess ? "succeeded" : "failed")}");
        return reimport.IsSuccess ? 0 : 1;
    }

    private static int RunWireframe(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0]))
        {
            stdout.WriteLine("Render deterministic trim-aware SVG isolines and exact topology edges from a STEP BRep.");
            stdout.WriteLine(WireframeUsage);
            stdout.WriteLine("The result is diagnostic visualization, not a tessellated product or hidden-line engineering drawing.");
            return args.Length == 0 ? 1 : 0;
        }
        var input = Path.GetFullPath(args[0]); string? output = null; var json = false;
        var view = WireframeView.Isometric; var density = 8; var samples = 48;
        for (var index = 1; index < args.Length; index++)
        {
            if (args[index] == "--json") json = true;
            else if (args[index] == "--out" && index + 1 < args.Length) output = Path.GetFullPath(args[++index]);
            else if (args[index] == "--density" && index + 1 < args.Length && int.TryParse(args[++index], out density)) { }
            else if (args[index] == "--samples" && index + 1 < args.Length && int.TryParse(args[++index], out samples)) { }
            else if (args[index] == "--view" && index + 1 < args.Length)
            {
                view = args[++index].ToLowerInvariant() switch
                {
                    "iso" or "isometric" => WireframeView.Isometric,
                    "iso-z" => WireframeView.IsometricZUp,
                    "front" => WireframeView.Front,
                    "top" => WireframeView.Top,
                    "right" => WireframeView.Right,
                    _ => throw new ArgumentException(WireframeUsage)
                };
            }
            else { stderr.WriteLine(WireframeUsage); return 1; }
        }
        if (density is < 2 or > 32 || samples is < 8 or > 256) { stderr.WriteLine(WireframeUsage); return 1; }
        if (!File.Exists(input)) { stderr.WriteLine($"STEP file not found: {input}"); return 1; }
        output ??= Path.Combine(Path.GetDirectoryName(input)!, Path.GetFileNameWithoutExtension(input) + ".wireframe.svg");
        var imported = Step242Importer.ImportBody(File.ReadAllText(input));
        if (!imported.IsSuccess || imported.Value is null)
        {
            foreach (var diagnostic in imported.Diagnostics) stderr.WriteLine($"error: {diagnostic.Message}");
            return 1;
        }
        PcurveBuildResult? recoveredPcurves = null;
        if (!imported.Value.Bindings.PcurveBindings.Any())
            recoveredPcurves = BoundedPcurveBuilder.Populate(imported.Value.Topology, imported.Value.Geometry, imported.Value.Bindings, tolerance: 1e-3d);
        var importedPcurveEvidence = recoveredPcurves is null && imported.Value.PcurveRecoveryReport is null
            ? BrepPcurveValidator.Validate(imported.Value) : null;
        var rendered = BrepWireframeSvgRenderer.Render(imported.Value, new(view, density, samples));
        Directory.CreateDirectory(Path.GetDirectoryName(output)!); File.WriteAllText(output, rendered.Svg);
        var report = new { command = "wireframe", success = true, input, output, rendered.Evidence,
            pcurveRecovery = imported.Value.PcurveRecoveryReport is { } importRecovery
                ? (object)new { importRecovery.IsSuccess, importRecovery.Count, importRecovery.MaximumResidual, importRecovery.Diagnostics }
                : recoveredPcurves is null
                ? (object)new { IsSuccess = importedPcurveEvidence!.IsValid, Count = importedPcurveEvidence.PcurveCount, MaximumResidual = importedPcurveEvidence.MaximumReconstructionDeviation, Diagnostics = importedPcurveEvidence.Diagnostics }
                : new { recoveredPcurves.IsSuccess, recoveredPcurves.Count, recoveredPcurves.MaximumResidual, recoveredPcurves.Diagnostics } };
        if (json) stdout.WriteLine(JsonSerializer.Serialize(report, JsonOptions));
        else stdout.WriteLine($"Wireframe SVG: {output}\nFaces: {rendered.Evidence.FaceCount}; edges: {rendered.Evidence.EdgeCount}; trimmed faces: {rendered.Evidence.FacesWithTrimmedIsolines}\nSHA-256: {rendered.Evidence.Sha256}");
        return 0;
    }

    private static void WriteFrontendDiagnostics(IEnumerable<FirmamentV2ValidationDiagnostic> diagnostics,TextWriter writer)
    {
        foreach(var d in diagnostics)writer.WriteLine($"{d.SourceFile}:{d.Line}:{d.Column}: {d.Severity} {d.Code}: {d.Message}");
    }

    private static int RunSculptingBuild(string sourcePath, string? outPath, bool json, TextWriter stdout, TextWriter stderr)
    {
        var compile = SculptingAuthoring.CompileFile(sourcePath);
        if (compile.OutputMesh is not null)
            return MeshSculptCommand.Write(compile, sourcePath, outPath, Path.GetExtension(outPath ?? ".step").TrimStart('.').ToLowerInvariant(), "build", json, stdout, stderr);
        var sourceText=File.ReadAllText(sourcePath);
        var presented=SculptingAuthoring.KernelDiagnostics(compile).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,sourceText)).ToArray();
        if (!compile.IsSuccess || compile.OutputState is null)
        {
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "build", success = false, input = Path.GetFullPath(sourcePath), domain = "Sculpting", diagnostics = presented }, JsonOptions));
            else { stderr.WriteLine("Build failed:"); WriteFrontendDiagnostics(presented,stderr); }
            return 1;
        }
        var exportClock = Stopwatch.StartNew(); var export = SculptStepExporter.Export(compile.OutputState, compile.ModelName); exportClock.Stop();
        if (!export.IsSuccess || export.Step is null)
        {
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "build", success = false, input = Path.GetFullPath(sourcePath), domain = "Sculpting", diagnostics = SculptingAuthoring.KernelDiagnostics(compile with {Diagnostics=export.Diagnostics}).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,sourceText)).ToArray(), surfaceInventory = export.Inventory }, JsonOptions));
            else foreach (var diagnostic in export.Diagnostics) stderr.WriteLine($"- [Error] {diagnostic.Code}: {diagnostic.Message}");
            return 1;
        }
        var output = Path.GetFullPath(outPath ?? Path.ChangeExtension(sourcePath, ".step")); Directory.CreateDirectory(Path.GetDirectoryName(output)!); File.WriteAllText(output, export.Step);
        var deltaPath = Path.ChangeExtension(output, ".delta.json");
        File.WriteAllText(deltaPath, JsonSerializer.Serialize(new
        {
            inputState = compile.OutputState.PredecessorStateId,
            outputState = compile.OutputState.StateId,
            compile.OutputState.Delta,
            constructionState = compile.OutputState.ConstructionAuthority,
            validationEvidence = compile.OutputState.ValidationEvidence,
            surfacePatches = compile.OutputState.SurfacePatches,
            blendJudgment = compile.OutputState.BlendJudgment,
            surfaceInventory = export.Inventory,
            productBoundary = new { rationalNurbs = export.Inventory.RationalNurbs, admitted = export.IsSuccess },
            timingsMilliseconds = compile.Timings with { StepExportMilliseconds = exportClock.Elapsed.TotalMilliseconds }
        }, JsonOptions));
        if (json) stdout.WriteLine(JsonSerializer.Serialize(new
        {
            command = "build", success = true, input = Path.GetFullPath(sourcePath), output, domain = "Sculpting", model = compile.ModelName,
            state = DescribeSculptState(compile.OutputState), states = compile.States.Values.Select(DescribeSculptState), geometricDelta = compile.OutputState.Delta,
            validationEvidence = compile.OutputState.ValidationEvidence, surfacePatches = compile.OutputState.SurfacePatches, blendJudgment = compile.OutputState.BlendJudgment, surfaceInventory = export.Inventory, rationalNurbs = export.Inventory.RationalNurbs,
            deltaArtifact = deltaPath, timingsMilliseconds = compile.Timings with { StepExportMilliseconds = exportClock.Elapsed.TotalMilliseconds }, diagnostics = presented
        }, JsonOptions));
        else
        {
            stdout.WriteLine($"Built {Path.GetFileName(sourcePath)}"); stdout.WriteLine($"STEP: {output}"); stdout.WriteLine($"State: {compile.OutputState.AuthoredName} ({compile.OutputState.StateId}) <- {compile.OutputState.PredecessorStateId}"); stdout.WriteLine($"Geometric delta: {deltaPath}"); stdout.WriteLine($"STEP surfaces: Plane={export.Inventory.Plane}, Cylinder={export.Inventory.Cylinder}, NonRationalBSpline={export.Inventory.NonRationalBSpline}, RationalNURBS={export.Inventory.RationalNurbs}");
            if (compile.OutputState.BlendJudgment is { } judgment)
            {
                stdout.WriteLine($"Blend judgment: {judgment.Request}");
                foreach (var candidate in judgment.Candidates)
                    stdout.WriteLine($"  {candidate.CandidateId}: {candidate.Disposition}" + (candidate.Metrics is null ? $" — {candidate.RejectionReason}" : $"; utility={candidate.Metrics.Utility:F6}, fairness={candidate.Metrics.Fairness:F6}, curvature={candidate.Metrics.CurvatureSmoothness:F6}, compactness={candidate.Metrics.Compactness:F6}, complexity={candidate.Metrics.Complexity:F6}"));
                stdout.WriteLine($"  Selected: {judgment.SelectedCandidateId} ({(judgment.ManualOverride ? "manual override" : judgment.JudgmentPolicyId)})");
            }
        }
        return 0;
    }

    /// <summary>Builds the part as an ordinary model and writes the Mold report beside its STEP. Findings are warnings or
    /// errors according to the Mold's stage; any error fails the build.</summary>
    private static int RunMoldBuild(string sourcePath, string? outPath, bool json, TextWriter stdout, TextWriter stderr)
    {
        var compile = MoldFirmament.CompileFile(sourcePath);
        var output = compile.PartStep is null ? null : Path.GetFullPath(outPath ?? Path.ChangeExtension(sourcePath, ".step"));
        string? reportPath = null;
        if (output is not null)
        {
            Directory.CreateDirectory(Path.GetDirectoryName(output)!);
            File.WriteAllText(output, compile.PartStep);
            reportPath = Path.ChangeExtension(output, ".mold.json");
            File.WriteAllText(reportPath, JsonSerializer.Serialize(new { compile.Report, diagnostics = compile.Diagnostics }, JsonOptions));
        }
        if (json)
            stdout.WriteLine(JsonSerializer.Serialize(new { command = "build", success = compile.IsSuccess, input = Path.GetFullPath(sourcePath), output, report = reportPath, domain = "Mold",
                mold = compile.Intent?.MoldName, part = compile.Intent?.PartName, stage = compile.Intent?.Stage.ToString(), summary = compile.Report?.Summary, diagnostics = compile.Diagnostics }, JsonOptions));
        else
        {
            if (compile.Report is { } report)
            {
                var s = report.Summary;
                stdout.WriteLine($"Mold {report.Intent.MoldName} on {report.Intent.PartName} ({report.Intent.Policy.Name}, {report.Intent.Stage}, pull {Format(report.Intent.Pull)})");
                stdout.WriteLine($"  faces {s.Faces}: {s.PositiveFaces} +pull, {s.NegativeFaces} -pull, {s.VerticalFaces} parallel, {s.StraddlingFaces} straddling; {s.DraftFailures} short of draft, {s.UndercutFaces} undercut");
                stdout.WriteLine($"  projected area {s.ProjectedArea:0.#} mm², volume {s.Volume:0.#} mm³, shot {s.ShotMass:0.##} g; parting line {report.PartingLine.EdgeIds.Count} edges" + (report.PartingLine.OnDeclaredPlane ? "" : " (off the declared plane)"));
            }
            if (output is not null) { stdout.WriteLine($"STEP: {output}"); stdout.WriteLine($"Report: {reportPath}"); }
            foreach (var d in compile.Diagnostics) (d.Severity == PlasticDiagnosticSeverity.Error ? stderr : stdout).WriteLine($"{d.Severity.ToString().ToLowerInvariant()} {d.Code}: {d.Message}");
        }
        return compile.IsSuccess ? 0 : 1;

        static string Format(Aetheris.Kernel.Core.Math.Direction3D d) => $"[{d.X:0.###}, {d.Y:0.###}, {d.Z:0.###}]";
    }

    private static int RunPlasticShellBuild(string sourcePath, string? outPath, bool json, TextWriter stdout, TextWriter stderr)
    {
        var compile = PlasticShellFirmament.CompileFile(sourcePath);
        var sourceText=File.ReadAllText(sourcePath);
        var presented=PlasticShellFirmament.KernelDiagnostics(compile).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,sourceText)).ToArray();
        if (!compile.IsSuccess || compile.State is null)
        {
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "build", success = false, input = Path.GetFullPath(sourcePath), domain = "PlasticShell", diagnostics = presented }, JsonOptions));
            else { stderr.WriteLine("Build failed:"); WriteFrontendDiagnostics(presented,stderr); }
            return 1;
        }
        var export = PlasticShellStepExporter.Export(compile.State, compile.ModelName);
        if (!export.IsSuccess || export.Step is null)
        {
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "build", success = false, input = Path.GetFullPath(sourcePath), domain = "PlasticShell", diagnostics = PlasticShellFirmament.KernelDiagnostics(compile with {Diagnostics=export.Diagnostics}).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,sourceText)).ToArray(), surfaceInventory = export.Inventory }, JsonOptions));
            else foreach (var diagnostic in export.Diagnostics) stderr.WriteLine($"- [{diagnostic.Severity}] {diagnostic.Code}: {diagnostic.Message}");
            return 1;
        }
        var output = Path.GetFullPath(outPath ?? Path.ChangeExtension(sourcePath, ".step")); Directory.CreateDirectory(Path.GetDirectoryName(output)!); File.WriteAllText(output, export.Step);
        var evidencePath = Path.ChangeExtension(output, ".plastic-shell.json");
        File.WriteAllText(evidencePath, JsonSerializer.Serialize(new { compile.ModelName, compile.State.Intent, compile.State.StateId, compile.State.Delta, compile.State.Evidence, surfaceInventory = export.Inventory, productBoundary = new { bodies = compile.State.Body.Topology.Bodies.Count(), shells = compile.State.Body.Topology.Shells.Count(), rationalProductSurfaces = export.Inventory.RationalProductSurfaces } }, JsonOptions));
        var report = new { command = "build", success = true, input = Path.GetFullPath(sourcePath), output, evidence = evidencePath, domain = "PlasticShell", model = compile.ModelName, plasticShell = compile.State.Intent, state = compile.State.StateId, geometricDelta = compile.State.Delta, manufacturingEvidence = compile.State.Evidence, surfaceInventory = export.Inventory, rationalProductSurfaces = export.Inventory.RationalProductSurfaces, diagnostics = presented };
        if (json) stdout.WriteLine(JsonSerializer.Serialize(report, JsonOptions));
        else { stdout.WriteLine($"Built {Path.GetFileName(sourcePath)}"); stdout.WriteLine($"STEP: {output}"); stdout.WriteLine($"PlasticShell: {compile.State.Intent.PlasticShellId}; wall {compile.State.Evidence.WallThickness.Minimum:G6}..{compile.State.Evidence.WallThickness.Maximum:G6} mm; selected ribs {compile.State.Evidence.RibNetwork?.SelectedCandidate ?? "none"}"); stdout.WriteLine($"Manufacturing evidence: {evidencePath}"); }
        return 0;
    }

    private static object DescribeSculptState(BodyState state) => new
    {
        state.AuthoredName, state.StateId, state.PredecessorStateId, state.BodyStableId,
        constructionState = state.ConstructionAuthority is null ? null : new
        {
            schema = new { state.ConstructionAuthority.SchemaId, state.ConstructionAuthority.SchemaVersion },
            @base = new { state.ConstructionAuthority.Base.BaseId, state.ConstructionAuthority.Base.BaseKind, state.ConstructionAuthority.Base.SchemaVersion },
            operations = state.ConstructionAuthority.Operations.Select(operation => new
            {
                operation.OperationId, operation.OperationKind, operation.PayloadVersion,
                operation.PredecessorStateId, operation.OutputStateId, operation.Reads, operation.MayModify,
                authorizedRegion = operation.AuthorizedRegion, preserve = operation.Preserves,
                operation.ReplayStatus,
                delta = new { operation.Delta.Preserves, operation.Delta.Replaces, operation.Delta.Removes, operation.Delta.Introduces }
            })
        },
        realizedHousingEvidence = state.Construction is {} housing ? new { housing.Width, housing.Depth, housing.BaseHeight, housing.CrownWidth, housing.CrownDepth, housing.CrownOffset, housing.FinalHeight } : null,
        semanticInventory = state.SemanticInventory.Values, geometryAssociations = state.GeometryAssociations,
        faceBoundaries = state.Construction is null ? state.Body.Topology.Faces.Select(f => new { handle = "Face" + f.Id.Value,
            loops = f.LoopIds.Select(l => state.Body.GetCoedgeIds(l).Select(state.Body.Topology.GetCoedge).Select(c => {
                var edge = state.Body.Topology.GetEdge(c.EdgeId); state.Body.TryGetVertexPoint(edge.StartVertexId, out var start); state.Body.TryGetVertexPoint(edge.EndVertexId, out var end);
                return new { handle = "Edge" + c.EdgeId.Value, start, end }; }).ToArray()).ToArray() }).ToArray() : null,
        surfacePatches = state.SurfacePatches, blendJudgment = state.BlendJudgment, hasDelta = state.Delta is not null
    };

    private static int RunSheetMetalAuthoredBuild(string sourcePath, string? outPath, bool json, TextWriter stdout, TextWriter stderr)
    {
        var authored=SheetMetalFirmament.CompileFile(sourcePath);
        if(!authored.IsSuccess||authored.Part?.FormedBody is null)
        {
            if(json)stdout.WriteLine(JsonSerializer.Serialize(new{command="build",success=false,input=Path.GetFullPath(sourcePath),domain="SheetMetal",diagnostics=authored.Diagnostics},JsonOptions));
            else{stderr.WriteLine("Build failed:");WriteSheetMetalDiagnostics(authored.Diagnostics,stderr);}
            return 1;
        }
        var semanticPmi=authored.Spec?.Manufacturing.ToStep242SemanticPmi(authored.Part)??[];
        var export=Step242Exporter.ExportBody(authored.Part.FormedBody,semanticPmi,new Step242ExportOptions{BrepExportPreflightMode=BrepExportPreflightMode.Enforce,ProductName=authored.Spec?.Name??"SheetMetalPart"});
        if(!export.IsSuccess){if(json)stdout.WriteLine(JsonSerializer.Serialize(new{command="build",success=false,input=Path.GetFullPath(sourcePath),domain="SheetMetal",diagnostics=export.Diagnostics.Select(d=>new{d.Message,d.Source})},JsonOptions));else foreach(var d in export.Diagnostics)stderr.WriteLine(d.Message);return 1;}
        var output=Path.GetFullPath(outPath??Path.ChangeExtension(sourcePath,".step"));Directory.CreateDirectory(Path.GetDirectoryName(output)!);File.WriteAllText(output,export.Value);
        if(json)stdout.WriteLine(JsonSerializer.Serialize(new{command="build",success=true,input=Path.GetFullPath(sourcePath),output,domain="SheetMetal",part=new{authored.Part.StableId,authored.Part.Thickness,authored.Part.Material,regions=authored.Part.Regions.Count,bends=authored.Part.Bends.Count,features=authored.Part.Features.Count},manufacturing=new{release=authored.Spec?.Manufacturing.ReleaseName,materialSpecification=authored.Spec?.Manufacturing.MaterialSpecification,semanticPmi=semanticPmi.Count},flatPattern=new{authored.FlatPattern!.Status,authored.FlatPattern.Bounds,authored.FlatPattern.DeterministicHash}},JsonOptions));
        else{stdout.WriteLine($"Built {Path.GetFileName(sourcePath)}");stdout.WriteLine($"STEP: {output}");stdout.WriteLine($"Model: {authored.Part.StableId} (SheetMetal, {authored.Part.Bends.Count} bends)");if(authored.Part.Material is not null)stdout.WriteLine($"Material: {authored.Part.Material}");}
        return 0;
    }

    private static int RunSheetMetal(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if(args.Length==0||IsHelpFlag(args[0])){WriteSheetMetalHelp(stdout);return args.Length==0?1:0;}
        if(args[0]=="recognize")return RunSheetMetalRecognize(args.Skip(1).ToArray(),stdout,stderr);
        if(args[0]=="recover-flat")return RunSheetMetalRecoverFlat(args.Skip(1).ToArray(),stdout,stderr);
        if(args[0]=="compare-flat")return RunSheetMetalCompareFlat(args.Skip(1).ToArray(),stdout,stderr);
        if(args[0]=="recover")return RunSheetMetalRecover(args.Skip(1).ToArray(),stdout,stderr);
        if(args[0]=="compare")return RunSheetMetalCompare(args.Skip(1).ToArray(),stdout,stderr);
        var operation=args[0];if(operation is not ("inspect" or "flatten" or "paths")||args.Length<2){stderr.WriteLine(SheetMetalUsage);return 1;}
        var input=Path.GetFullPath(args[1]);string? output=null,flatStepOutput=null,firmamentOutput=null;var json=false;double? requestedK=null;
        for(var i=2;i<args.Length;i++)
        {
            if(args[i]=="--json"){json=true;continue;}
            if(args[i] is "--output" or "--out" or "--svg"&&i+1<args.Length){output=Path.GetFullPath(args[++i]);continue;}
            if(args[i]=="--step"&&i+1<args.Length){flatStepOutput=Path.GetFullPath(args[++i]);continue;}
            if(args[i]=="--firmament"&&i+1<args.Length){firmamentOutput=Path.GetFullPath(args[++i]);continue;}
            if(args[i]=="--k-factor"&&i+1<args.Length&&double.TryParse(args[++i],System.Globalization.NumberStyles.Float,System.Globalization.CultureInfo.InvariantCulture,out var parsedK)&&parsedK>=0&&parsedK<=1){requestedK=parsedK;continue;}
            stderr.WriteLine($"Unknown or invalid sheetmetal option '{args[i]}'.");stderr.WriteLine(SheetMetalUsage);return 1;
        }
        if(!File.Exists(input)){stderr.WriteLine($"Sheet Metal input was not found: {input}");return 1;}
        SheetMetalPartIr? part;SheetThicknessRecognition? thickness=null;TimeSpan importTime=TimeSpan.Zero,recognitionTime=TimeSpan.Zero;SheetMetalAuthoringTimings? authoredTimings=null;SheetMetalConstructionSpec? authoredSpec=null;IReadOnlyList<Aetheris.Kernel.Firmament.FirmamentV2.ConceptIrTemplateInstantiation> templateInstantiations=[];IReadOnlyList<SheetMetalDiagnostic> recognitionDiagnostics;
        var source=File.ReadAllText(input);if(SheetMetalFirmament.LooksLikeSheetMetal(source))
        {
            var authored=SheetMetalFirmament.Compile(source,input);part=authored.Part;authoredSpec=authored.Spec;authoredTimings=authored.Timings;templateInstantiations=authored.TemplateInstantiations??[];recognitionDiagnostics=authored.Diagnostics;if(!authored.IsSuccess||part is null){WriteFailure(authored.Diagnostics);return 1;}
            part=part with{FlatPatternPolicy=new(requestedK??part.FlatPatternPolicy.KFactor)};
        }
        else
        {
            var recognized=SheetMetalRecognizer.RecognizeStep(input,new(FlattenPolicy:new(requestedK??.5d)));part=recognized.Part;thickness=recognized.Thickness;importTime=recognized.ImportTime;recognitionTime=recognized.RecognitionTime;recognitionDiagnostics=recognized.Diagnostics;if(part is null){WriteFailure(recognitionDiagnostics);return 1;}
        }
        var k=requestedK??part.FlatPatternPolicy.KFactor;var flattenClock=Stopwatch.StartNew();var flat=SheetMetalFlattener.Flatten(part,new(k));flattenClock.Stop();var dfm=SheetMetalDfm.Evaluate(part,flat);
        var allDiagnostics=recognitionDiagnostics.Concat(flat.Diagnostics).GroupBy(x=>(x.Code,x.Severity,x.Message)).Select(x=>x.First()).ToArray();
        var conceptPaths=authoredSpec is null?Array.Empty<SheetMetalConceptPath>():SheetMetalConceptPaths.Inspect(authoredSpec,part,flat);
        if(operation=="paths")
        {
            if(authoredSpec is null){stderr.WriteLine("sheetmetal paths requires authored or reconstructed Firmament, not recovered STEP topology.");return 1;}
            if(json)stdout.WriteLine(JsonSerializer.Serialize(new{command="sheetmetal paths",success=true,input,paths=conceptPaths},JsonOptions));
            else foreach(var path in conceptPaths)stdout.WriteLine($"{path.Path}  {path.Kind}  [{string.Join(", ",path.Capabilities)}]");
            return 0;
        }
        if(operation=="flatten")
        {
            if(string.IsNullOrWhiteSpace(output)&&string.IsNullOrWhiteSpace(flatStepOutput)&&string.IsNullOrWhiteSpace(firmamentOutput)){stderr.WriteLine("sheetmetal flatten requires at least one of --step, --firmament, or --svg/--output.");return 1;}
            if(output is not null)SheetMetalSvgRenderer.Write(output,flat);
            if(flatStepOutput is not null&&!SheetMetalManufacturingArtifacts.WriteFlatStep(flatStepOutput,part,flat,out var stepDiagnostics)){WriteFailure(stepDiagnostics);return 2;}
            if(firmamentOutput is not null){var firmamentDirectory=Path.GetDirectoryName(firmamentOutput)!;Directory.CreateDirectory(firmamentDirectory);var recoverySource=Path.GetRelativePath(firmamentDirectory,input);File.WriteAllText(firmamentOutput,SheetMetalManufacturingArtifacts.WriteRecoveredFirmament(part,recoverySource));}
        }
        var body=part.FormedBody;var supportFamilies=body?.Topology.Faces.GroupBy(f=>body.TryGetFaceSurfaceGeometry(f.Id,out var s)?s?.Kind.ToString()??"Unknown":"Unknown").OrderBy(g=>g.Key).ToDictionary(g=>g.Key,g=>g.Count());
        var pmiIndicators=authoredSpec is null
            ? Regex.Matches(source,"(DRAUGHTING_MODEL|GEOMETRIC_TOLERANCE|DATUM_FEATURE|ANNOTATION_OCCURRENCE|SHAPE_ASPECT)",RegexOptions.IgnoreCase).Count
            : authoredSpec.Manufacturing.Datums.Count+authoredSpec.Manufacturing.Dimensions.Count+authoredSpec.Manufacturing.GeometricTolerances.Count+authoredSpec.Manufacturing.Annotations.Count;
        var exactValidation=flat.ExactBlankContour is null?null:PlanarContourKernel.Validate(flat.ExactBlankContour);
        var report=new{command=$"sheetmetal {operation}",success=true,input,sourceAuthority=SheetMetalFirmament.LooksLikeSheetMetal(source)?(source.Contains("Intent: Reconstructed",StringComparison.OrdinalIgnoreCase)?"Firmament reconstructed engineering authority":source.Contains("RecoveredRegion",StringComparison.Ordinal)?"Firmament recovered sheet-metal semantics":"Firmament authored semantics"):"STEP formed BRep (not mutated)",recognitionStatus=part.RecognitionStatus,material=new{authored=part.Material,manufacturingSpecification=authoredSpec?.Manufacturing.MaterialSpecification},thickness=new{nominal=part.Thickness,tolerance=authoredSpec?.Manufacturing.ThicknessTolerancePlus??thickness?.Tolerance,evidencePairs=thickness?.SourcePairs.Count(p=>p.Admitted)??0,outlierFaces=thickness?.OutlierFaceIds.Count??0},geometry=new{bodies=body?.Topology.Bodies.Count()??0,shells=body?.Topology.Shells.Count()??0,faces=body?.Topology.Faces.Count()??0,edges=body?.Topology.Edges.Count()??0,vertices=body?.Topology.Vertices.Count()??0,supportFamilies,pmiIndicators},manufacturing=authoredSpec?.Manufacturing,sheetMetal=new{baseRegion=part.BaseRegionId,regions=part.Regions.Select(r=>new{r.StableId,r.Kind,r.ApproximateArea,sourceFaces=r.Source.FaceIds}),attachmentPaths=(part.AttachmentPaths??[]).Select(p=>new{p.StableId,p.OwningRegionId,p.CarrierPath,p.Inset,length=(p.End-p.Start).Length,p.SpanOffset,p.Start,p.End,p.Tangent,p.InPlaneNormal,p.RegionNormal,p.Capabilities}),bends=part.Bends.Select(b=>new{b.StableId,b.AxisOrigin,b.AxisDirection,angleDegrees=b.BendAngleRadians*180/Math.PI,b.InsideRadius,b.Direction,b.AdjacentRegionA,b.AdjacentRegionB,sourceFaces=b.Source.FaceIds}),cuts=part.Features.Select(f=>new{f.StableId,f.Kind,f.OwningRegionId,f.Diameter,sourceFaces=f.Source.FaceIds}),reliefs=part.Reliefs?.Count??0,semanticLayout=authoredSpec?.SemanticLayout,conceptPaths,templateInstantiations},flatPattern=new{flat.Status,MaterialArea=flat.MaterialArea,BoundingArea=flat.BoundingArea,flat.Bounds,bendLines=flat.BendLines.Count,cuts=flat.CutLoops.Count,reliefs=flat.ReliefLoops?.Count??0,exactBlank=flat.ExactBlankContour is not null,outerLoops=flat.ExactBlankContour is null?0:1,innerLoops=flat.ExactBlankContour?.InnerLoops.Count??0,connectedMaterialRegions=flat.ExactBlankContour is null?0:1,selfIntersects=exactValidation?.Diagnostics.Any(x=>x.Code=="planar-contour-self-intersection")??false,exactContoursValid=exactValidation?.IsValid??false,fallbackUsed=authoredSpec is not null&&flat.ExactBlankContour is null,kFactor=flat.Policy.KFactor,flat.DeterministicHash,svg=output,step=flatStepOutput,firmament=firmamentOutput},dfm=new{dfm.Overall,findings=dfm.Findings},diagnostics=allDiagnostics,timingsMilliseconds=new{parse=authoredTimings?.ParseMilliseconds,semanticResolve=authoredTimings?.SemanticResolveMilliseconds,formedLower=authoredTimings?.FormedLowerMilliseconds,authoredFlatLower=authoredTimings?.FlatLowerMilliseconds,import=importTime.TotalMilliseconds,recognition=recognitionTime.TotalMilliseconds,flatten=flattenClock.Elapsed.TotalMilliseconds}};
        if(json)stdout.WriteLine(JsonSerializer.Serialize(report,JsonOptions));else
        {
            stdout.WriteLine($"Sheet Metal: {part.RecognitionStatus} ({report.sourceAuthority})");if(part.Material is not null)stdout.WriteLine($"Material: {part.Material}");stdout.WriteLine($"Thickness: {part.Thickness:G8} mm{(thickness is null?" authored/recovered":$" ± {thickness.Tolerance:G4} mm, {thickness.SourcePairs.Count(p=>p.Admitted)} paired supports")}");stdout.WriteLine($"Regions: {part.Regions.Count} ({part.Regions.Count(r=>r.Kind==SheetRegionKind.Planar)} planar, {part.Regions.Count(r=>r.Kind==SheetRegionKind.CylindricalBend)} cylindrical)");stdout.WriteLine($"Bends: {part.Bends.Count}; cuts: {part.Features.Count}; base: {part.BaseRegionId}");foreach(var bend in part.Bends)stdout.WriteLine($"  {bend.StableId}: {bend.BendAngleRadians*180/Math.PI:G5} deg, R{bend.InsideRadius:G6}, {bend.Direction}, {bend.AdjacentRegionA} -> {bend.AdjacentRegionB}");stdout.WriteLine($"Flat pattern: {flat.Status}; MaterialArea={(flat.MaterialArea is { } materialArea?$"{materialArea:G10} mm^2":"unavailable")}; BoundingArea={(flat.BoundingArea is { } boundingArea?$"{boundingArea:G10} mm^2":"unavailable")}; {(flat.Bounds is null?"no bounds":$"{flat.Bounds.Width:G8} x {flat.Bounds.Height:G8} mm")}; K={flat.Policy.KFactor:G4}; hash={flat.DeterministicHash}");if(flatStepOutput is not null)stdout.WriteLine($"STEP: {flatStepOutput}");if(firmamentOutput is not null)stdout.WriteLine($"Firmament: {firmamentOutput}");if(output is not null)stdout.WriteLine($"SVG: {output}");foreach(var d in allDiagnostics)stdout.WriteLine($"  [{d.Severity}] {d.Code}: {d.Message}");
        }
        return flat.Status is FlatPatternStatus.Unsupported or FlatPatternStatus.Overlapping?2:0;
        void WriteFailure(IReadOnlyList<SheetMetalDiagnostic> ds){if(json)stdout.WriteLine(JsonSerializer.Serialize(new{command=$"sheetmetal {operation}",success=false,input,diagnostics=ds},JsonOptions));else WriteSheetMetalDiagnostics(ds,stderr);}
    }

    private static int RunSheetMetalRecognize(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if(args.Length<1){stderr.WriteLine(SheetMetalUsage);return 1;}
        var input=Path.GetFullPath(args[0]);string? planPath=null;var json=false;
        for(var i=1;i<args.Length;i++)if(args[i]=="--json")json=true;else if(args[i]=="--plan"&&i+1<args.Length)planPath=Path.GetFullPath(args[++i]);else{stderr.WriteLine(SheetMetalUsage);return 1;}
        if(!File.Exists(input)){stderr.WriteLine($"Sheet Metal input was not found: {input}");return 1;}
        var detection=SheetMetalRecognizer.RecognizeStep(input);if(detection.Part is null){WriteSheetMetalDiagnostics(detection.Diagnostics,stderr);return 2;}
        var model=RecognizedSheetMetalRecovery.FromDetection(detection);var plan=RecognizedSheetMetalRecovery.CreateAutomaticPlan(model);var validation=RecognizedSheetMetalRecovery.ValidatePlan(model,plan);
        if(planPath is not null){Directory.CreateDirectory(Path.GetDirectoryName(planPath)!);File.WriteAllText(planPath,JsonSerializer.Serialize(plan,JsonOptions));}
        var report=new{command="sheetmetal recognize",success=validation.IsValid,input,model=model.StableId,model.RecognitionStatus,model.Thickness,rootRegion=model.RootRegionId,
            regions=model.Regions.Where(x=>x.Kind==SheetRegionKind.Planar).Select(x=>new{x.StableId,sourceFaces=x.Source.FaceIds}),
            bends=model.Bends.Select(x=>new{x.SourceBendId,x.Name,candidateStatus=x.Status,acceptedStatus=plan.Bends.Single(y=>y.BendId==x.SourceBendId).Status,x.Confidence,axisOrigin=x.Geometry.AxisOrigin,axisDirection=x.Geometry.AxisDirection,angleDegrees=x.Geometry.BendAngleRadians*180/Math.PI,x.Geometry.InsideRadius,x.Geometry.AdjacentRegionA,x.Geometry.AdjacentRegionB,sourceFaces=x.Geometry.Source.FaceIds,evidence=x.Evidence}),
            cuts=model.Cuts.Select(x=>new{x.StableId,x.Kind,x.OwningRegionId,sourceFaces=x.Source.FaceIds}),recognitionPlan=planPath,plan.DeterministicHash,diagnostics=detection.Diagnostics.Concat(validation.Diagnostics),timingsMilliseconds=new{import=detection.ImportTime.TotalMilliseconds,recognition=detection.RecognitionTime.TotalMilliseconds}};
        if(json)stdout.WriteLine(JsonSerializer.Serialize(report,JsonOptions));else{stdout.WriteLine($"Recognized imported Sheet Metal: {model.Regions.Count(x=>x.Kind==SheetRegionKind.Planar)} planar regions, {model.Bends.Count} bend candidates, {plan.Bends.Count(x=>x.Status==RecognizedBendStatus.Recognized)} accepted, {model.Cuts.Count} cuts.");foreach(var b in report.bends)stdout.WriteLine($"  {b.Name} ({b.SourceBendId}): {b.acceptedStatus}, {b.angleDegrees:G6} deg, R{b.InsideRadius:G6}, {b.AdjacentRegionA} -> {b.AdjacentRegionB}");if(planPath is not null)stdout.WriteLine($"Recognition plan: {planPath}");}
        return validation.IsValid?0:2;
    }

    private static int RunSheetMetalRecoverFlat(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if(args.Length<1){stderr.WriteLine(SheetMetalUsage);return 1;}
        var input=Path.GetFullPath(args[0]);string? outDir=null,planPath=null;var json=false;
        for(var i=1;i<args.Length;i++)if(args[i]=="--json")json=true;else if(args[i]=="--out-dir"&&i+1<args.Length)outDir=Path.GetFullPath(args[++i]);else if(args[i]=="--recognition-plan"&&i+1<args.Length)planPath=Path.GetFullPath(args[++i]);else{stderr.WriteLine(SheetMetalUsage);return 1;}
        if(!File.Exists(input)){stderr.WriteLine($"Sheet Metal input was not found: {input}");return 1;}if(outDir is null){stderr.WriteLine("sheetmetal recover-flat requires --out-dir.");return 1;}
        var detection=SheetMetalRecognizer.RecognizeStep(input);if(detection.Part is null){WriteSheetMetalDiagnostics(detection.Diagnostics,stderr);return 2;}
        var model=RecognizedSheetMetalRecovery.FromDetection(detection);SheetMetalRecognitionPlan plan;
        if(planPath is null)plan=RecognizedSheetMetalRecovery.CreateAutomaticPlan(model);else
        {
            if(!File.Exists(planPath)){stderr.WriteLine($"Recognition plan was not found: {planPath}");return 1;}
            var loaded=JsonSerializer.Deserialize<SheetMetalRecognitionPlan>(File.ReadAllText(planPath),JsonOptions)??throw new InvalidDataException("Recognition plan JSON was empty.");
            plan=RecognizedSheetMetalRecovery.CreatePlan(model,loaded.Bends,loaded.RootRegionId,loaded.ReferenceKind,loaded.Authority);
        }
        var recovered=RecoveredSourceFlattener.Flatten(model,plan);Directory.CreateDirectory(outDir);
        var artifactPath=Path.Combine(outDir,"recovered-flat.json");var svgPath=Path.Combine(outDir,"recovered-flat.svg");var persistedPlanPath=Path.Combine(outDir,"recognition-plan.json");
        File.WriteAllText(persistedPlanPath,JsonSerializer.Serialize(plan,JsonOptions));File.WriteAllText(artifactPath,JsonSerializer.Serialize(RecoveredFlatArtifact(input,recovered),JsonOptions));SheetMetalSvgRenderer.Write(svgPath,RecoveredSourceFlattener.ToFlatPattern(recovered));
        var report=new{command="sheetmetal recover-flat",success=recovered.Status!=FlatPatternStatus.Unsupported,input,recovered.StableId,recovered.ReferenceKind,recovered.RootRegionId,recovered.Status,recovered.ContourAcceptance,recovered.Bounds,outerSegments=recovered.OuterAndInnerContours?.OuterLoop.Segments.Count??0,innerLoops=recovered.OuterAndInnerContours?.InnerLoops.Count??recovered.InnerContours.Count,cuts=recovered.InnerContours.Count,bendLines=recovered.BendLines.Count,regions=recovered.Regions.Count,sourceProvenance=recovered.SourceProvenance.Count,junctionRepairs=recovered.JunctionRepairs,recovered.StitchSummary,recovered.DeterministicHash,artifacts=new{reference=artifactPath,svg=svgPath,recognitionPlan=persistedPlanPath},timingsMilliseconds=new{graph=recovered.GraphTime.TotalMilliseconds,unfold=recovered.UnfoldTime.TotalMilliseconds,stitch=recovered.StitchTime.TotalMilliseconds,cluster=recovered.StitchSummary?.EndpointClusteringMilliseconds,candidateSelection=recovered.StitchSummary?.CandidateSelectionMilliseconds,validate=recovered.StitchSummary?.ContourValidationMilliseconds},recovered.Diagnostics};
        if(json)stdout.WriteLine(JsonSerializer.Serialize(report,JsonOptions));else stdout.WriteLine($"Recovered source flat: {recovered.Status} ({recovered.ContourAcceptance}); {(recovered.Bounds is null?"no bounds":$"{recovered.Bounds.Width:G8} x {recovered.Bounds.Height:G8} mm")}; {recovered.InnerContours.Count} cuts; {recovered.BendLines.Count} bend lines; {recovered.JunctionRepairs.Count} repaired junctions; {recovered.JunctionRepairs.Count(x=>x.Confidence==RecoveryRepairConfidence.Ambiguous)} unresolved/ambiguous.\nReference: {artifactPath}\nSVG: {svgPath}\nPlan: {persistedPlanPath}");
        return recovered.Status==FlatPatternStatus.Unsupported?2:0;
    }

    private static int RunSheetMetalCompareFlat(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if(args.Length<2||args.Skip(2).Any(x=>x is not ("--json" or "--semantic"))){stderr.WriteLine(SheetMetalUsage);return 1;}
        var referencePath=Path.GetFullPath(args[0]);var nativePath=Path.GetFullPath(args[1]);var json=args.Contains("--json",StringComparer.Ordinal);var semantic=args.Contains("--semantic",StringComparer.Ordinal);
        if(!File.Exists(referencePath)||!File.Exists(nativePath)){stderr.WriteLine("Recovered flat or native Firmament input was not found.");return 1;}
        using var document=JsonDocument.Parse(File.ReadAllText(referencePath));var root=document.RootElement;var sourcePath=root.GetProperty("sourcePath").GetString();var planElement=root.GetProperty("recognitionPlan");
        if(string.IsNullOrWhiteSpace(sourcePath)||!File.Exists(sourcePath)){stderr.WriteLine("Recovered flat sourcePath is unavailable; deterministic source revalidation cannot proceed.");return 2;}
        var loadedPlan=planElement.Deserialize<SheetMetalRecognitionPlan>(JsonOptions);if(loadedPlan is null){stderr.WriteLine("Recovered flat recognition plan is invalid.");return 2;}
        var detection=SheetMetalRecognizer.RecognizeStep(sourcePath);if(detection.Part is null){WriteSheetMetalDiagnostics(detection.Diagnostics,stderr);return 2;}var model=RecognizedSheetMetalRecovery.FromDetection(detection);var plan=RecognizedSheetMetalRecovery.CreatePlan(model,loadedPlan.Bends,loadedPlan.RootRegionId,loadedPlan.ReferenceKind,loadedPlan.Authority);var source=RecoveredSourceFlattener.Flatten(model,plan);
        var native=SheetMetalFirmament.CompileFile(nativePath);if(!native.IsSuccess||native.FlatPattern is null){WriteSheetMetalDiagnostics(native.Diagnostics,stderr);return 2;}
        var comparison=RecoveredFlatComparer.Compare(source,native.FlatPattern);var semanticComparison=semantic?SemanticSheetMetalComparer.CompareFlat(source,native.Part!,native.FlatPattern,sourcePart:model.DetectedPart):null;var report=new{command="sheetmetal compare-flat",success=comparison.Status!=SheetMetalComparisonStatus.Fail,reference=referencePath,native=nativePath,comparison,semanticComparison};
        if(json)stdout.WriteLine(JsonSerializer.Serialize(report,JsonOptions));else{stdout.WriteLine($"Recovered source flat -> native flat: {comparison.Status}");stdout.WriteLine($"source->native RMS/p95/max: {comparison.SourceToNative.Rms:G6}/{comparison.SourceToNative.P95:G6}/{comparison.SourceToNative.Maximum:G6} mm");stdout.WriteLine($"native->source RMS/p95/max: {comparison.NativeToSource.Rms:G6}/{comparison.NativeToSource.P95:G6}/{comparison.NativeToSource.Maximum:G6} mm");foreach(var item in comparison.LocalizedDifferences)stdout.WriteLine($"  {item}");if(semanticComparison is not null){stdout.WriteLine($"Semantic targets: {semanticComparison.Status}; tolerance {semanticComparison.Tolerance:G6} mm");foreach(var target in semanticComparison.Targets.Where(x=>x.Status!=SemanticGeometryComparisonStatus.Pass).Take(20))stdout.WriteLine($"  {target.Status} {target.SemanticPath}: max {Math.Max(target.Metrics.SourceToNative.Maximum,target.Metrics.NativeToSource.Maximum):G6} mm; {target.Classification}");}}
        return comparison.Status==SheetMetalComparisonStatus.Fail?2:0;
    }

    private static object RecoveredFlatArtifact(string sourcePath, RecoveredFlatReference recovered) => new
    {
        schema="aetheris.recovered-flat-reference.v2",sourcePath=Path.GetFullPath(sourcePath),recovered.StableId,recovered.ReferenceKind,recovered.RootRegionId,recovered.Frame,recovered.Status,recovered.ContourAcceptance,recovered.Bounds,recovered.DeterministicHash,recovered.RecognitionPlan,recovered.JunctionRepairs,recovered.StitchSummary,
        outerContour=ContourArtifact(recovered.OuterAndInnerContours?.OuterLoop),innerContours=(recovered.OuterAndInnerContours?.InnerLoops??[]).Select(ContourArtifact),
        regions=recovered.Regions.Select(x=>new{x.StableId,x.SourceRegionId,x.Kind,x.MappingKind,contour=ContourArtifact(x.ExactContour?.OuterLoop)}),
        cuts=recovered.InnerContours.Select(x=>new{x.FeatureId,x.Kind,x.SourceRegionId,contour=ContourArtifact(x.ExactContour?.OuterLoop)}),recovered.BendLines,recovered.RegionMap,recovered.SourceProvenance,recovered.Diagnostics
    };
    private static object? ContourArtifact(PlanarContourLoop2? loop)=>loop is null?null:new{loop.StableId,loop.IsOuter,segments=loop.Segments.Select(x=>new{x.StableId,kind=x.Geometry.GetType().Name,geometry=CurveArtifact(x.Geometry),x.Provenance})};
    private static object CurveArtifact(LineArcProfileCurve2D curve)=>curve switch
    {
        LineArcLineSegment2D line=>new{start=new{x=line.Start.X,y=line.Start.Y},end=new{x=line.End.X,y=line.End.Y}},
        LineArcCircularArc2D arc=>new{center=new{x=arc.Center.X,y=arc.Center.Y},arc.Radius,arc.StartAngleRadians,arc.SweepAngleRadians,start=new{x=arc.Center.X+arc.Radius*Math.Cos(arc.StartAngleRadians),y=arc.Center.Y+arc.Radius*Math.Sin(arc.StartAngleRadians)},end=new{x=arc.Center.X+arc.Radius*Math.Cos(arc.StartAngleRadians+arc.SweepAngleRadians),y=arc.Center.Y+arc.Radius*Math.Sin(arc.StartAngleRadians+arc.SweepAngleRadians)}},
        LineArcFullCircle2D circle=>new{center=new{x=circle.Center.X,y=circle.Center.Y},circle.Radius},
        _=>new{unsupported=curve.GetType().Name}
    };
    private static void WriteSheetMetalDiagnostics(IEnumerable<SheetMetalDiagnostic> diagnostics,TextWriter stderr)
    {
        foreach(var diagnostic in diagnostics)
        {
            var file=diagnostic.SourceFile;
            var source=file is not null && File.Exists(file)?File.ReadAllText(file):null;
            var presented=FirmamentBuildAdmissionValidation.Locate(new(diagnostic.Code,diagnostic.Severity.ToString(),diagnostic.Message)
                { SourceSpan=diagnostic.SourceSpan,LocationNote=diagnostic.LocationNote },source,file ?? "unknown");
            var location=diagnostic.SourceSpan is not null && source is not null?$"{file}({presented.Line},{presented.Column}): ":file is not null?$"{file}: ":"";
            var note=diagnostic.LocationNote is { Length:>0 } detail?" "+detail:"";
            stderr.WriteLine($"{location}[{diagnostic.Severity}] {diagnostic.Code}: {diagnostic.Message}{note}");
        }
    }

    private static int RunSheetMetalRecover(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if(args.Length<1){stderr.WriteLine(SheetMetalUsage);return 1;}var input=Path.GetFullPath(args[0]);string? outDir=null;var json=false;
        for(var i=1;i<args.Length;i++)if(args[i]=="--json")json=true;else if(args[i]=="--out-dir"&&i+1<args.Length)outDir=Path.GetFullPath(args[++i]);else{stderr.WriteLine(SheetMetalUsage);return 1;}
        if(!File.Exists(input)){stderr.WriteLine($"Sheet Metal input was not found: {input}");return 1;}if(outDir is null){stderr.WriteLine("sheetmetal recover requires --out-dir.");return 1;}
        var recognized=SheetMetalRecognizer.RecognizeStep(input);if(recognized.Part is null){foreach(var d in recognized.Diagnostics)stderr.WriteLine($"[{d.Severity}] {d.Code}: {d.Message}");return 2;}
        var recovery=SheetMetalIntentRecovery.Recover(recognized);Directory.CreateDirectory(outDir);var evidencePath=Path.Combine(outDir,"recovery-summary.json");var briefPath=Path.Combine(outDir,"reconstruction-brief.md");var draftPath=Path.Combine(outDir,"recovered-draft.firmament");
        File.WriteAllText(evidencePath,JsonSerializer.Serialize(new{status=recovery.Evidence.Part.RecognitionStatus,recovery.Evidence.DeterministicId,thickness=recovery.Evidence.Part.Thickness,regions=recovery.Evidence.Part.Regions.Select(r=>new{r.StableId,r.Kind,sourceFaces=r.Source.FaceIds}),bends=recovery.Evidence.Part.Bends.Select(b=>new{b.StableId,angleDegrees=b.BendAngleRadians*180/Math.PI,b.InsideRadius,b.AdjacentRegionA,b.AdjacentRegionB,sourceFaces=b.Source.FaceIds}),cuts=recovery.Evidence.Part.Features.Select(f=>new{f.StableId,f.Kind,f.OwningRegionId,f.Center,f.Diameter}),recovery.Evidence.NominalCandidates,recovery.Evidence.GroupingCandidates,recovery.Evidence.Corners,recovery.Evidence.Reliefs,recovery.Evidence.Ambiguities},JsonOptions));
        File.WriteAllText(briefPath,recovery.ReconstructionBrief);File.WriteAllText(draftPath,SheetMetalManufacturingArtifacts.WriteRecoveredFirmament(recognized.Part,Path.GetRelativePath(outDir,input)));
        var report=new{command="sheetmetal recover",success=true,input,outDir,evidence=evidencePath,brief=briefPath,draft=draftPath,status=recognized.Part.RecognitionStatus,recovery.Evidence.DeterministicId,timingsMilliseconds=new{import=recognized.ImportTime.TotalMilliseconds,recognition=recognized.RecognitionTime.TotalMilliseconds}};
        stdout.WriteLine(json?JsonSerializer.Serialize(report,JsonOptions):$"Recovered {recognized.Part.Regions.Count} regions, {recognized.Part.Bends.Count} bends, and {recognized.Part.Features.Count} cuts.\nEvidence: {evidencePath}\nBrief: {briefPath}\nDraft: {draftPath}");return 0;
    }

    private static int RunSheetMetalCompare(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if(args.Length<2||args.Skip(2).Any(a=>a is not ("--json" or "--semantic"))){stderr.WriteLine(SheetMetalUsage);return 1;}var sourcePath=Path.GetFullPath(args[0]);var intentPath=Path.GetFullPath(args[1]);var json=args.Contains("--json",StringComparer.Ordinal);var semantic=args.Contains("--semantic",StringComparer.Ordinal);
        if(!File.Exists(sourcePath)||!File.Exists(intentPath)){stderr.WriteLine("Sheet Metal compare input was not found.");return 1;}
        SheetMetalPartIr? Load(string path){var text=File.ReadAllText(path);return SheetMetalFirmament.LooksLikeSheetMetal(text)?SheetMetalFirmament.Compile(text,path).Part:SheetMetalRecognizer.RecognizeStep(path).Part;}
        var source=Load(sourcePath);var intent=Load(intentPath);if(source is null||intent is null){stderr.WriteLine("Sheet Metal compare could not compile/recover both inputs.");return 2;}var comparison=SheetMetalIntentComparer.Compare(source,intent);var semanticComparison=semantic?SemanticSheetMetalComparer.CompareFormed(source,intent):null;
        if(json)stdout.WriteLine(JsonSerializer.Serialize(new{command="sheetmetal compare",success=comparison.Status is SheetMetalComparisonStatus.Pass or SheetMetalComparisonStatus.PassWithKnownDifferences or SheetMetalComparisonStatus.NeedsReview,source=sourcePath,intent=intentPath,comparison,semanticComparison},JsonOptions));
        else{stdout.WriteLine($"Sheet Metal intent comparison: {comparison.Status}");stdout.WriteLine($"Thickness residual: {comparison.ThicknessResidual:G6} mm");stdout.WriteLine($"Formed source->intent RMS/p95/max: {comparison.SourceToIntent.Rms:G6}/{comparison.SourceToIntent.P95:G6}/{comparison.SourceToIntent.Maximum:G6} mm");stdout.WriteLine($"Formed intent->source RMS/p95/max: {comparison.IntentToSource.Rms:G6}/{comparison.IntentToSource.P95:G6}/{comparison.IntentToSource.Maximum:G6} mm");foreach(var b in comparison.Bends)stdout.WriteLine($"  {b.SourceBendId} -> {b.IntentBendId}: axis {b.AxisResidual:G6} mm, axis-angle {b.AxisAngleResidualDegrees:G6} deg, bend-angle {b.BendAngleResidualDegrees:G6} deg, radius {b.RadiusResidual:G6} mm, adjacency {b.AdjacencyMatches}, {b.Status}");if(semanticComparison is not null)foreach(var t in semanticComparison.Terminations)stdout.WriteLine($"  {t.SemanticPath}: formed axial endpoint {t.AxialEndpointResidual:G6} mm, {t.Status}");stdout.WriteLine($"Flat: {comparison.FlatPattern.Status}; width Δ {comparison.FlatPattern.WidthResidual:G6}, height Δ {comparison.FlatPattern.HeightResidual:G6}, contour p95 {comparison.FlatPattern.Contour.P95:G6} mm");}
        return comparison.Status==SheetMetalComparisonStatus.Fail?2:0;
    }

    private static int RunModules(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length > 0 && args[0] == "showcase") return RunModuleShowcase(args.Skip(1).ToArray(), stdout, stderr);
        var json = args.Contains("--json", StringComparer.Ordinal);
        if (args.Any(a => a is not "--json" and not "--help" and not "-h")) { stderr.WriteLine("Usage: aetheris modules [--json] | modules showcase --out-dir <directory>"); return 1; }
        var catalog = BuiltInModules.Catalog;
        if (json)
        {
            stdout.WriteLine(JsonSerializer.Serialize(catalog.Modules.Select(m => new { id=m.Id.Value,name=m.Name,version=m.Version.ToString(),m.BuiltIn,dependencies=m.Dependencies.Select(d=>new{id=d.ModuleId.Value,minimumVersion=d.MinimumVersion.ToString()}),capabilities=m.Capabilities.Select(c=>c.Id),m.Concepts,m.Templates,m.Lowerings,m.Documentation }), JsonOptions));
            return 0;
        }
        stdout.WriteLine("Built-in engineering Modules (explicit registration; no dynamic plugins)");
        foreach (var module in catalog.Modules) stdout.WriteLine($"{module.Id.Value} {module.Version}  {(module.Capabilities.Count == 0 ? "(reserved)" : string.Join(", ", module.Capabilities.Select(c=>c.Id)))}");
        return 0;
    }

    private static int RunModuleShowcase(string[] args, TextWriter stdout, TextWriter stderr)
    {
        var index=Array.IndexOf(args,"--out-dir");if(index<0||index+1>=args.Length){stderr.WriteLine("Usage: aetheris modules showcase --out-dir <directory>");return 1;}
        var output=Path.GetFullPath(args[index+1]);Directory.CreateDirectory(output);var started=Stopwatch.GetTimestamp();var catalog=BuiltInModules.Catalog;var registryMs=Stopwatch.GetElapsedTime(started).TotalMilliseconds;started=Stopwatch.GetTimestamp();for(var i=0;i<10_000;i++)_ = BuiltInModules.Catalog.Capabilities.Count;var cachedRegistryLookupMicroseconds=Stopwatch.GetElapsedTime(started).TotalMicroseconds/10_000;
        started=Stopwatch.GetTimestamp();var saddleIr=RuledCanopyTemplate.Create("m0:saddle",80,50,12);var saddlePatch=RuledSurfaceLowering.Lower(saddleIr);var saddlePanel=RuledSurfacePanelMaterializer.Materialize(saddleIr,2);var surfacingMs=Stopwatch.GetElapsedTime(started).TotalMilliseconds;
        if(!saddlePatch.IsSuccess||saddlePanel.Body is null){stderr.WriteLine(string.Join("; ",saddlePanel.Diagnostics.Select(d=>d.Message)));return 1;}
        started=Stopwatch.GetTimestamp();var route=StandardPipeElbowTemplate.Create("m0:pipe-route",20,50,30);var pipe=PipeRouteLowering.Lower(route);var pipingMs=Stopwatch.GetElapsedTime(started).TotalMilliseconds;if(!pipe.IsSuccess){stderr.WriteLine(string.Join("; ",pipe.Diagnostics.Select(d=>d.Message)));return 1;}
        var saddleStep=Step242Exporter.ExportBody(saddlePanel.Body);var pipeStep=Step242Exporter.ExportBody(pipe.Body!);if(!saddleStep.IsSuccess||!pipeStep.IsSuccess){stderr.WriteLine(string.Join("; ",saddleStep.Diagnostics.Concat(pipeStep.Diagnostics).Select(d=>d.Message)));return 1;}
        var saddlePath=Path.Combine(output,"ruled-saddle.step");var pipePath=Path.Combine(output,"pipe-route.step");File.WriteAllText(saddlePath,saddleStep.Value);File.WriteAllText(pipePath,pipeStep.Value);
        string Hash(string text)=>Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(text)));
        var galleryReports=new List<object>();var galleryStarted=Stopwatch.GetTimestamp();
        foreach(var entry in SurfacingGallery.Build())
        {
            var brep=SurfacePatchBrepMaterializer.Materialize(entry.Support,entry.Evaluate);if(brep.Body is null){stderr.WriteLine(string.Join("; ",brep.Diagnostics.Select(d=>d.Message)));return 1;}var step=Step242Exporter.ExportBody(brep.Body);if(!step.IsSuccess){stderr.WriteLine(string.Join("; ",step.Diagnostics.Select(d=>d.Message)));return 1;}
            var fileName=entry.StableId+".step";File.WriteAllText(Path.Combine(output,fileName),step.Value);var reimport=Step242Importer.ImportBody(step.Value);
            var authored=entry.Panel.AuthoredPatch;var centerU=(authored.Domain.U.Minimum+authored.Domain.U.Maximum)/2d;var centerV=(authored.Domain.V.Minimum+authored.Domain.V.Maximum)/2d;var curvature=CurvatureQuery.Patch(authored,centerU,centerV);
            galleryReports.Add(new{entry.StableId,panelId=entry.Panel.StableId,constructionFamily=entry.ConstructionKind.ToString(),supportType=entry.Support.Kind.ToString(),materialization=entry.MaterializationKind.ToString(),parameterDomain=new{u=new[]{entry.Panel.ParameterDomain.U.Minimum,entry.Panel.ParameterDomain.U.Maximum},v=new[]{entry.Panel.ParameterDomain.V.Minimum,entry.Panel.ParameterDomain.V.Maximum}},orientation=entry.Panel.Orientation,secondJetCapability=authored.SupportsSecondJet,centerDifferential=new{status=curvature.Status.ToString(),regular=curvature.Singularity==DifferentialSingularityKind.Regular,curvature.GaussianCurvature,curvature.MeanCurvature,curvature.K1,curvature.K2,evidence=curvature.Evidence.ToString(),curvature.Diagnostic},edges=entry.Panel.BoundaryEdges.Select(edge=>new{edge.Name,edge.StableId,curveFamily=edge.Curve.Kind.ToString(),lengthMm=edge.Length(),direction=edge.SourceDirection.ToString(),edge.SourceCurveStableId}),corners=entry.Panel.Corners.Values.Select(corner=>new{corner.Name,corner.StableId,corner.Point}),entry.SourceDeclarations,entry.AuthoringSummary,developability=entry.Developability,approximation=entry.Approximation,step=fileName,stepSha256=Hash(step.Value),brepFaces=brep.Body.Topology.Faces.Count(),stepReimport=reimport.IsSuccess,surfaceMeshIr=entry.Support.Kind==Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind.BSplineSurfaceWithKnots?"typed-unsupported-non-rational-bspline-support":"supported-when-analytic-family-admitted"});
        }
        var galleryMs=Stopwatch.GetElapsedTime(galleryStarted).TotalMilliseconds;
        var canonicalPanelSource="""
Model CanonicalPanel {
  Units: mm;
  Panel Saddle {
    Surface: ParametricSurface {
      DomainU: [-1, 1]; DomainV: [-1, 1];
      X: 40mm * u; Y: 30mm * v; Z: 12mm * u * v;
    }
    Orientation: Front; Thickness: 1.2mm; Material: "Aluminum";
  }
}
""";
        started=Stopwatch.GetTimestamp();var compilerProof=FirmamentPanelCompiler.Compile(canonicalPanelSource);var parseBindMs=compilerProof.Performance.ParseBindMilliseconds;var panelConstructionMs=compilerProof.Performance.PanelConstructionMilliseconds;
        if(!compilerProof.IsSuccess){stderr.WriteLine(string.Join("; ",compilerProof.Diagnostics));return 1;}var compilerProofAgain=FirmamentPanelCompiler.Compile(canonicalPanelSource);
        started=Stopwatch.GetTimestamp();var edgeInspection=compilerProof.Panels.SelectMany(panel=>panel.BoundaryEdges).Select(edge=>new{edge.StableId,length=edge.Length()}).ToArray();var edgeExtractionMs=Stopwatch.GetElapsedTime(started).TotalMilliseconds;
        started=Stopwatch.GetTimestamp();var canopy=PanelShowcases.DevelopableFoldedCanopy();var mateValidationMs=Stopwatch.GetElapsedTime(started).TotalMilliseconds;if(!canopy.Network.IsSuccess){stderr.WriteLine(string.Join("; ",canopy.Network.Diagnostics.Select(d=>d.Message)));return 1;}
        var canopySteps=new List<object>();var stepStarted=Stopwatch.GetTimestamp();for(var i=0;i<canopy.Panels.Count;i++){var panel=canopy.Panels[i];var exportBody=SurfacePatchBrepMaterializer.Materialize(panel.SurfaceConstruction.Support,panel.SurfaceConstruction.Evaluate,panel.Thickness??1);if(exportBody.Body is null){stderr.WriteLine(string.Join("; ",exportBody.Diagnostics.Select(d=>d.Message)));return 1;}var export=Step242Exporter.ExportBody(exportBody.Body);if(!export.IsSuccess){stderr.WriteLine(string.Join("; ",export.Diagnostics.Select(d=>d.Message)));return 1;}var name=$"developable-folded-canopy-{i}.step";File.WriteAllText(Path.Combine(output,name),export.Value);canopySteps.Add(new{panel=panel.StableId,file=name,sha256=Hash(export.Value)});}var stepGenerationMs=Stopwatch.GetElapsedTime(stepStarted).TotalMilliseconds;
        var networkReport=new{canopy.StableId,panels=canopy.Panels.Select(panel=>new{panel.StableId,construction=panel.SurfaceConstruction.Kind.ToString(),developability=panel.Developability,edges=panel.BoundaryEdges.Select(edge=>new{edge.Name,edge.StableId})}),mates=canopy.Network.Mates,freeEdges=canopy.Network.FreeEdges,steps=canopySteps};
        File.WriteAllText(Path.Combine(output,"canonical-panel.firmament"),canonicalPanelSource);File.WriteAllText(Path.Combine(output,"panel-network.json"),JsonSerializer.Serialize(networkReport,JsonOptions));File.WriteAllText(Path.Combine(output,"compiler-bridge.json"),JsonSerializer.Serialize(new{success=compilerProof.IsSuccess,panels=compilerProof.Panels.Select(panel=>panel.StableId),deterministic=compilerProof.Panels.Select(panel=>panel.StableId).SequenceEqual(compilerProofAgain.Panels.Select(panel=>panel.StableId)),compilerProof.TemplateInstantiations},JsonOptions));
        var evidence=new{milestone="AETHERIS-PANEL-M0",registryMs,cachedRegistryLookupMicroseconds,surfacingMs,galleryMs,pipingMs,performance=new{parseBindMs,panelConstructionMs,edgeExtractionMs,mateValidationMs,stepGenerationMs},determinism=new{panelIds=compilerProof.Panels.Select(panel=>panel.StableId),repeatPanelIds=compilerProofAgain.Panels.Select(panel=>panel.StableId),stable=compilerProof.Panels.Select(panel=>panel.StableId).SequenceEqual(compilerProofAgain.Panels.Select(panel=>panel.StableId))},modules=catalog.Modules.Select(m=>new{module=m.Id.Value,version=m.Version.ToString(),capabilities=m.Capabilities.Select(c=>c.Id)}),surfacing=new{saddleIr.StableId,kind=saddleIr.Kind.ToString(),surface=saddlePatch.Patch!.ExactSurface.Kind.ToString(),boundaries=saddlePatch.Patch.BoundaryProvenance,developability=saddlePatch.Patch.Developability,saddleHash=Hash(saddleStep.Value),faces=saddlePanel.Body.Topology.Faces.Count(),gallery=galleryReports},panels=new{compilerBridge=compilerProof.Panels.Select(panel=>new{panel.StableId,panel.Orientation,panel.Developability,semantics=SemanticValueDescriptor.From(panel.SemanticValue)}),edgeInspection,network=networkReport},piping=new{ir=new{pipe.Ir!.StableId,elements=pipe.Ir.Elements.Select(e=>e switch{PipeRouteElement.Straight s=>new{kind="Straight",start=s.Start,end=s.End,radius=(double?)null,angle=(double?)null},PipeRouteElement.PlanarCircularBend b=>new{kind="PlanarCircularBend",start=b.Center,end=b.Center,radius=(double?)b.Radius,angle=(double?)b.AngleRadians},_=>throw new InvalidOperationException()})},framePolicy=PipeRouteLowering.CircularFramePolicy,pipeHash=Hash(pipeStep.Value),faces=pipe.Body!.Topology.Faces.Count(),semantics=SemanticValueDescriptor.From(pipe.Semantics!)} };
        File.WriteAllText(Path.Combine(output,"module-registry.json"),JsonSerializer.Serialize(catalog.Modules.Select(m=>new{id=m.Id.Value,version=m.Version.ToString(),dependencies=m.Dependencies,capabilities=m.Capabilities,concepts=m.Concepts,templates=m.Templates}),JsonOptions));
        File.WriteAllText(Path.Combine(output,"semantic-inspection.json"),JsonSerializer.Serialize(SemanticValueDescriptor.From(pipe.Semantics!),JsonOptions));
        File.WriteAllText(Path.Combine(output,"validation-report.json"),JsonSerializer.Serialize(evidence,JsonOptions));File.WriteAllText(Path.Combine(output,"surfacing-gallery-inspection.json"),JsonSerializer.Serialize(galleryReports,JsonOptions));
        var hashManifest=Directory.GetFiles(output).Where(path=>Path.GetFileName(path)!="hashes.json").Order(StringComparer.Ordinal).Select(path=>new{file=Path.GetFileName(path),sha256=Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path)))}).ToArray();File.WriteAllText(Path.Combine(output,"hashes.json"),JsonSerializer.Serialize(hashManifest,JsonOptions));
        stdout.WriteLine(JsonSerializer.Serialize(new{output,saddleStep=saddlePath,pipeStep=pipePath,saddleHash=Hash(saddleStep.Value),pipeHash=Hash(pipeStep.Value),surfacingGallery=galleryReports.Count,panels=galleryReports.Count,networkPanels=canopy.Panels.Count,networkMates=canopy.Mates.Count},JsonOptions));return 0;
    }

    private static int RunDrawing(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length > 0 && args[0] is not ("compile" or "generate") && !IsHelpFlag(args[0])) return DrawingNotesCli.Run(args, stdout, stderr);
        if (args.Length == 0 || IsHelpFlag(args[0]))
        {
            CommandHelp.Write(args.Length == 0 ? stderr : stdout, DrawingUsage, "Compile an authored drawing or generate dimensioned drawing artifacts from a model. Rendering existing PDFs requires the optional drawing-notes renderer.", "aetheris drawing generate bracket.firmament --out-dir artifacts/local/drawing");
            return args.Length == 0 ? 1 : 0;
        }
        if (args[0] is not ("compile" or "generate") || args.Length < 2)
        {
            stderr.WriteLine(DrawingUsage);
            return 1;
        }
        var source = args[1];
        string? output = null;
        var json = false;
        var signoffValues = new Dictionary<string, string>(StringComparer.Ordinal);
        var generationOptions = new DrawingGenerationOptions();
        for (var i = 2; i < args.Length; i++)
        {
            if (args[i] == "--out-dir" && i + 1 < args.Length) output = args[++i];
            else if (args[i] == "--json") json = true;
            else if (args[i] == "--reference-only") generationOptions = generationOptions with { ReferenceOnly = true };
            else if (args[i] == "--material" && i + 1 < args.Length) generationOptions = generationOptions with { Material = args[++i] };
            else if (args[i] == "--angular-tolerance" && i + 1 < args.Length)
            {
                var angle = double.TryParse(args[++i], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var parsedAngle) ? parsedAngle : double.NaN;
                generationOptions = generationOptions with { AngularToleranceDegrees = angle };
            }
            else if (args[i] == "--linear-tolerance" && i + 1 < args.Length)
            {
                var tolerance = double.TryParse(args[++i], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var parsedTolerance) ? parsedTolerance : double.NaN;
                generationOptions = generationOptions with { LinearToleranceMillimetres = tolerance };
            }
            else if (args[i] is "--drawn-by" or "--date" or "--checked-by" or "--checked-date" or "--approved-by" or "--approved-date" && i + 1 < args.Length)
                signoffValues[args[i]] = args[++i];
            else { stderr.WriteLine($"Unknown drawing option '{args[i]}'."); stderr.WriteLine(DrawingUsage); return 1; }
        }
        output ??= Path.GetFullPath(Path.Combine("artifacts", "local", "drawing", Path.GetFileNameWithoutExtension(source)));
        DrawingSignoffIr? signoff = signoffValues.Count == 0 ? null : new(
            new(signoffValues.GetValueOrDefault("--drawn-by"), signoffValues.GetValueOrDefault("--date")),
            new(signoffValues.GetValueOrDefault("--checked-by"), signoffValues.GetValueOrDefault("--checked-date")),
            new(signoffValues.GetValueOrDefault("--approved-by"), signoffValues.GetValueOrDefault("--approved-date")));
        if (args[0] == "compile" && generationOptions != new DrawingGenerationOptions())
        { stderr.WriteLine("drawing-authored-options-unsupported: Generation options apply to drawing generate; authored requirements belong in its metadata."); return 1; }
        var result = args[0] == "generate" ? FirmamentDrawingCompiler.Generate(source, output, signoff, generationOptions) : FirmamentDrawingCompiler.Compile(source, output, signoff);
        if (!result.IsSuccess)
        {
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = false, diagnostics = result.KernelDiagnostics().Select(d=>FirmamentBuildAdmissionValidation.Present(d,source,File.Exists(source)?File.ReadAllText(source):null)).ToArray() }, JsonOptions));
            else WriteFrontendDiagnostics(result.KernelDiagnostics().Select(d=>FirmamentBuildAdmissionValidation.Present(d,source,File.Exists(source)?File.ReadAllText(source):null)),stderr);
            return 1;
        }
        var artifacts = result.Artifacts!;
        if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = true, artifacts.DrawingIrPath, artifacts.SvgPath, artifacts.PdfPath, artifacts.PptxPath, artifacts.ReviewPptxPath, artifacts.DfmReviewPptxPath, artifacts.ReviewIrPath, artifacts.ValidationPath, artifacts.PdfSha256, artifacts.DrawingIrSha256, artifacts.PptxSha256, pageCount = artifacts.Drawing.Pages.Count, layout = artifacts.Drawing.LayoutEvidence, definition = artifacts.Drawing.DefinitionEvidence }, JsonOptions));
        else stdout.WriteLine($"Compiled Drawing '{artifacts.Drawing.Identity}' to PDF and native editable PPTX ({artifacts.Drawing.Pages.Count} A4 page(s)).");
        if (!json && artifacts.Drawing.DefinitionEvidence is { } definition)
            stdout.WriteLine($"Nominal geometry complete: {definition.NominalGeometryComplete}; dimensional tolerances complete: {definition.DimensionalTolerancesComplete}; material specified: {definition.MaterialSpecified}; process capability verified: {definition.ProcessCapabilityVerified}.");
        return 0;
    }

    private static int RunFea(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0])) { CommandHelp.Write(stdout, FeaUsage, "Run the bounded engineering analysis declared by a Firmament source and save its reports.", "aetheris fea checked-part.firmament --out-dir artifacts/local/analysis --json"); return args.Length == 0 ? 1 : 0; }
        var input = Path.GetFullPath(args[0]); string? outDir = null; var json = false;Vector3D? rotationDegrees=null;(int X,int Y,int Z)? latticeOverride=null;ExperimentalPreconditionerKind? experimentalPreconditioner=null;bool? experimentalEquilibration=null;
        for (var index = 1; index < args.Length; index++)
        {
            if (args[index] == "--json") json = true;
            else if (args[index] == "--out-dir" && index + 1 < args.Length) outDir = Path.GetFullPath(args[++index]);
            else if(args[index]=="--rotate"&&index+1<args.Length){var values=args[++index].Split(',').Select(value=>double.Parse(value,System.Globalization.CultureInfo.InvariantCulture)).ToArray();if(values.Length!=3){stderr.WriteLine(FeaUsage);return 1;}rotationDegrees=new(values[0],values[1],values[2]);}
            else if(args[index]=="--lattice"&&index+1<args.Length){var values=args[++index].Split(',').Select(value=>int.TryParse(value,out var parsed)?parsed:0).ToArray();if(values.Length!=3||values.Any(value=>value<1)){stderr.WriteLine("Lattice override requires three positive integers.");return 1;}latticeOverride=(values[0],values[1],values[2]);}
            else if(args[index]=="--experimental-preconditioner"&&index+1<args.Length){var value=args[++index];experimentalPreconditioner=value.ToLowerInvariant() switch{"identity"=>ExperimentalPreconditionerKind.Identity,"jacobi"=>ExperimentalPreconditionerKind.Jacobi,"block-jacobi"=>ExperimentalPreconditionerKind.BlockJacobi3,"ic0"=>ExperimentalPreconditionerKind.IncompleteCholeskyZero,_=>(ExperimentalPreconditionerKind?)null};if(experimentalPreconditioner is null){stderr.WriteLine("Experimental preconditioner must be identity, jacobi, block-jacobi, or ic0.");return 1;}}
            else if(args[index]=="--experimental-equilibration"&&index+1<args.Length){if(!bool.TryParse(args[++index],out var value)){stderr.WriteLine("Experimental equilibration must be true or false.");return 1;}experimentalEquilibration=value;}
            else { stderr.WriteLine(FeaUsage); return 1; }
        }
        if (!File.Exists(input))
        {
            var message = $"Analysis source was not found: {input}";
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "fea", success = false, input, diagnostics = new[] { new { code = "firmament-analysis-source-missing", severity = "Error", message } } }, JsonOptions));
            else stderr.WriteLine(message);
            return 1;
        }
        var compiled = FirmamentAnalysisCompiler.Compile(File.ReadAllText(input), input, Path.GetDirectoryName(input));
        if (!compiled.IsSuccess || compiled.Analysis is null)
        {
            if (json)
                stdout.WriteLine(JsonSerializer.Serialize(new
                {
                    command = "fea",
                    success = false,
                    input,
                    diagnostics = FirmamentAnalysisCompiler.KernelDiagnostics(compiled).Select(d=>FirmamentBuildAdmissionValidation.Present(d,input,File.ReadAllText(input))).ToArray()
                }, JsonOptions));
            else
                WriteFrontendDiagnostics(FirmamentAnalysisCompiler.KernelDiagnostics(compiled).Select(d=>FirmamentBuildAdmissionValidation.Present(d,input,File.ReadAllText(input))),stderr);
            return 1;
        }
        if(latticeOverride is { } requestedLattice)compiled=compiled with{Analysis=compiled.Analysis with{Lattice=new Aetheris.Continuum.Lattice.LatticeSpec(compiled.Analysis.Body.ContinuumRegion.Bounds,requestedLattice.X,requestedLattice.Y,requestedLattice.Z)}};
        Transform3D? orientation=null;if(rotationDegrees is { } degrees){var b=compiled.Analysis.Body.ContinuumRegion.Bounds;var center=new Vector3D((b.Min.X+b.Max.X)/2,(b.Min.Y+b.Max.Y)/2,(b.Min.Z+b.Max.Z)/2);orientation=Transform3D.CreateTranslation(-center)*Transform3D.CreateRotationX(degrees.X*double.Pi/180)*Transform3D.CreateRotationY(degrees.Y*double.Pi/180)*Transform3D.CreateRotationZ(degrees.Z*double.Pi/180)*Transform3D.CreateTranslation(center);}
        // Generic imported BReps classify every intersecting site through exact kernel containment;
        // use the production default order while analytic domains retain the higher CLI verification order.
        var quadratureOrder=compiled.Analysis.Body.ContinuumRegion is Aetheris.FEA.Geometry.ImportedBrepAnalysisRegion?4:6;
        var isExperimentalShell=compiled.Analysis.Mode==Aetheris.FEA.Analysis.AnalysisMode.ExperimentalShell;
        var solveOptions=new MechanicsSolveOptions(CutCellQuadraturePerAxis:quadratureOrder,RelativeResidualTolerance:isExperimentalShell?1e-8:1e-9,MaximumIterations:isExperimentalShell?10000:null,DomainTransform:orientation,PreserveNominalCellVolumeUnderTransform:orientation is not null,
            RetryEmptyCutCells:compiled.Analysis.Body.ContinuumRegion is not Aetheris.FEA.Geometry.ImportedBrepAnalysisRegion,ExperimentalPreconditioner:experimentalPreconditioner,ExperimentalSymmetricEquilibration:experimentalEquilibration);var result = LinearElasticSolver.Solve(compiled.Analysis,solveOptions);
        if (!result.IsSuccess)
        {
            var errors = result.Diagnostics.Where(item => item.Severity == Aetheris.FEA.Analysis.AnalysisDiagnosticSeverity.Error).ToArray();
            if (json)
                stdout.WriteLine(JsonSerializer.Serialize(new
                {
                    command = "fea",
                    success = false,
                    input,
                    diagnostics = errors.Select(diagnostic => new { diagnostic.Code, severity = diagnostic.Severity.ToString(), diagnostic.Message }),result.System,result.Solver,experimentalShell=result.ExperimentalShell
                }, JsonOptions));
            else
                foreach (var diagnostic in errors) stderr.WriteLine($"{diagnostic.Code}: {diagnostic.Message}");
            return 1;
        }
        var experimental=compiled.Analysis.Mode==Aetheris.FEA.Analysis.AnalysisMode.ExperimentalShell;
        string? abaqusText=null;string? abaqusHash=null;object? abaqusReport=null;var verificationValid=true;
        if(!experimental)
        {
            var abaqus=AbaqusInpExporter.Export(compiled.Analysis,orientation);var validation=AbaqusInpValidator.Validate(abaqus.Text);
            abaqusText=abaqus.Text;abaqusHash=abaqus.Sha256;verificationValid=validation.IsValid;
            abaqusReport=new{abaqus.Sha256,abaqus.NodeCount,abaqus.ElementCount,validation.IsValid,validation.Diagnostics};
        }
        var report = new
        {
            analysis = new { compiled.Analysis.Id, kind = compiled.Analysis.Kind.ToString(),mode=compiled.Analysis.Mode.ToString(),qualification=experimental?"Experimental - not production-qualified":"Production", body = compiled.Analysis.Body.Id, compiled.Analysis.Body.SourceKind,
                geometryIdentity=compiled.Analysis.Body.ContinuumRegion.Id.Value,geometryHash=compiled.Analysis.Body.ResourceHash,brepBodyId=compiled.Analysis.Body.BrepBodyId,
                material = compiled.Analysis.Materials.Select(item => new { item.Id, item.StableMaterialId, item.ConstitutiveClass, item.YoungsModulusPascal, item.PoissonRatio, item.DensityKilogramsPerCubicMeter, item.YieldStrengthPascal }),
                constraints = compiled.Analysis.Constraints.Select(item => new { item.Id, region = item.Region.Path, components = item.Components }),
                loads = compiled.Analysis.Loads.Select(item => new { item.Id, kind = item.Kind.ToString(), distribution=item.Distribution.ToString(), region = item.Region.Path, item.VectorSi, item.PressurePascal }),
                bodyForces = (compiled.Analysis.BodyForces??[]).Select(item=>new{item.Id,item.AccelerationMetersPerSecondSquared}),
                requestedResults=compiled.Analysis.RequestedFields.Order().Select(Aetheris.FEA.Analysis.AnalysisResultContracts.Describe),
                lattice = new { compiled.Analysis.Lattice.CountX, compiled.Analysis.Lattice.CountY, compiled.Analysis.Lattice.CountZ },experimentalShell=compiled.Analysis.ExperimentalShell,
                midsurfacePatchGraph=compiled.Analysis.MidsurfacePatchGraph is null?null:new{analysisSource=compiled.Analysis.MidsurfacePatchGraph.AnalysisSource.ToString(),compiled.Analysis.MidsurfacePatchGraph.SheetMetalBody,compiled.Analysis.MidsurfacePatchGraph.ThicknessMeters,compiled.Analysis.MidsurfacePatchGraph.Material,patchCount=compiled.Analysis.MidsurfacePatchGraph.Patches.Count,compiled.Analysis.MidsurfacePatchGraph.PanelPatchCount,compiled.Analysis.MidsurfacePatchGraph.BendPatchCount,compiled.Analysis.MidsurfacePatchGraph.OpeningCount,interfaceCount=compiled.Analysis.MidsurfacePatchGraph.Interfaces.Count,patches=compiled.Analysis.MidsurfacePatchGraph.Patches.Select(x=>new{x.Identity,kind=x.Kind.ToString(),bounds=x.ParameterDomain.Bounds,x.OpeningCount,x.SourceAuthority}),interfaces=compiled.Analysis.MidsurfacePatchGraph.Interfaces.Select(x=>new{x.Identity,x.PatchA,edgeA=x.EdgeA.ToString(),x.PatchB,edgeB=x.EdgeB.ToString(),orientation=x.Orientation.ToString(),x.StartMeters,x.EndMeters,x.MaximumMismatchMeters,x.SemanticBendId})} },
            solverSettings=new{solveOptions.CutCellQuadraturePerAxis,solveOptions.RelativeResidualTolerance,solveOptions.MaximumIterations,solveOptions.RetryEmptyCutCells,solveOptions.ExperimentalPreconditioner,solveOptions.ExperimentalSymmetricEquilibration},
            orientationDegrees=rotationDegrees,result.System, result.Solver, result.Equilibrium, result.TinyCells, result.Performance,boundaryLoads=result.BoundaryLoads,bodyLoads=result.BodyLoads,numericalLowering=result.NumericalLowering,strainEnergy=result.StrainEnergy,stressProbes=result.StressProbes,
            experimentalShell=result.ExperimentalShell,
            maximumDisplacementMeters = result.MaximumDisplacementMeters, maximumVonMisesPascal = result.MaximumVonMisesPascal,
            abaqus = abaqusReport
        };
        if (outDir is not null)
        {
            Directory.CreateDirectory(outDir);
            File.WriteAllText(Path.Combine(outDir, "analysis-ir.json"), JsonSerializer.Serialize(report.analysis, JsonOptions));
            File.WriteAllText(Path.Combine(outDir, "native-results.json"), JsonSerializer.Serialize(report, JsonOptions));
            File.WriteAllText(Path.Combine(outDir, "sparse-system-metrics.json"), JsonSerializer.Serialize(result.System, JsonOptions));
            File.WriteAllText(Path.Combine(outDir, "residual-history.json"), JsonSerializer.Serialize(result.Solver.ResidualHistory, JsonOptions));
            File.WriteAllText(Path.Combine(outDir, "displacement-stress-summary.json"), JsonSerializer.Serialize(new { maximumDisplacementMeters = result.MaximumDisplacementMeters, maximumVonMisesPascal = result.MaximumVonMisesPascal, result.Equilibrium }, JsonOptions));
            File.WriteAllText(Path.Combine(outDir,"boundary-quadrature.json"),JsonSerializer.Serialize(result.BoundaryLoads,JsonOptions));
            File.WriteAllText(Path.Combine(outDir,"body-force-quadrature.json"),JsonSerializer.Serialize(result.BodyLoads,JsonOptions));
            File.WriteAllText(Path.Combine(outDir,"numerical-lowering-strategy-map.json"),JsonSerializer.Serialize(result.NumericalLowering,JsonOptions));
            if(experimental)
            {
                File.WriteAllText(Path.Combine(outDir,"experimental-shell-evidence.json"),JsonSerializer.Serialize(result.ExperimentalShell,JsonOptions));
                if(compiled.Analysis.MidsurfacePatchGraph is not null)File.WriteAllText(Path.Combine(outDir,"midsurface-patch-graph.json"),JsonSerializer.Serialize(report.analysis.midsurfacePatchGraph,JsonOptions));
                File.WriteAllText(Path.Combine(outDir,"parameter-domain-grid.svg"),ThinWallDebugArtifacts.ParameterDomainSvg(compiled.Analysis));
                File.WriteAllText(Path.Combine(outDir,"mapped-deformed-cells.svg"),ThinWallDebugArtifacts.MappedAndDeformedSvg(compiled.Analysis,result));
            }
            else File.WriteAllText(Path.Combine(outDir, "verification.inp"), abaqusText!);
        }
        stdout.WriteLine(json ? JsonSerializer.Serialize(report, JsonOptions) : experimental
            ? $"{compiled.Analysis.Id}: ExperimentalShell converged in {result.Solver.Iterations} iterations; max |u|={result.MaximumDisplacementMeters:R} m; max von Mises={result.MaximumVonMisesPascal:R} Pa"
            : $"{compiled.Analysis.Id}: converged in {result.Solver.Iterations} iterations; max |u|={result.MaximumDisplacementMeters:R} m; max von Mises={result.MaximumVonMisesPascal:R} Pa; Abaqus SHA-256={abaqusHash}");
        return verificationValid ? 0 : 1;
    }

    private static int RunMesh(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0])) { CommandHelp.Write(stdout, MeshUsage, "Build or import a part and export a display mesh. The target format must be admitted by the compiled product.", "aetheris mesh bracket.firmament --format stl --output bracket.stl"); return args.Length == 0 ? 1 : 0; }
        var input = args[0]; var format = "stl"; string? output = null; string? debugIr = null; string? stepOutput = null; var json = false;
        for (var i = 1; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--format" when i + 1 < args.Length: format = args[++i]; break;
                case "--output" when i + 1 < args.Length: output = args[++i]; break;
                case "--debug-ir" when i + 1 < args.Length: debugIr = args[++i]; break;
                case "--step-output" when i + 1 < args.Length: stepOutput = args[++i]; break;
                case "--json": json = true; break;
                default: stderr.WriteLine($"Unknown mesh option '{args[i]}'."); stderr.WriteLine(MeshUsage); return 1;
            }
        }
        if (string.Equals(format, "display-json", StringComparison.OrdinalIgnoreCase))
        {
            if (debugIr is not null) { stderr.WriteLine("display-json does not support --debug-ir."); return 1; }
            return PartDisplayMeshCommand.Run(input, output, stepOutput, stdout);
        }
        if (stepOutput is not null) { stderr.WriteLine("--step-output requires --format display-json."); return 1; }
        if (string.Equals(format, "assembly-json", StringComparison.OrdinalIgnoreCase))
        {
            if (debugIr is not null) { stderr.WriteLine("assembly-json does not support --debug-ir."); return 1; }
            var compilation = Path.GetExtension(input).Equals(".firmasm", StringComparison.OrdinalIgnoreCase)
                ? new FirmamentAssemblyDocumentCompiler().CompileFile(input).Compilation
                : new AssemblyM1Pipeline().CompileFile(input);
            if (!compilation.IsSuccess)
                return WriteMeshFailure(compilation.Diagnostics.Select(d => d.Code + ": " + d.Message), json, input, stdout, stderr);
            try
            {
                var assemblyDocument = AssemblyDisplayMeshExporter.Export(compilation);
                var destination = Path.GetFullPath(output ?? Path.Combine("artifacts", "local", "mesh", Path.GetFileNameWithoutExtension(input) + ".mesh.json"));
                Directory.CreateDirectory(Path.GetDirectoryName(destination)!);
                File.WriteAllText(destination, AssemblyDisplayMeshExporter.Serialize(assemblyDocument));
                stdout.WriteLine(JsonSerializer.Serialize(new { status = "success", output = destination, definitions = assemblyDocument.Definitions.Count,
                    occurrences = assemblyDocument.Occurrences.Count, triangles = assemblyDocument.Definitions.Sum(d => d.Indices.Length / 3) }));
                return 0;
            }
            catch (InvalidOperationException error) { return WriteMeshFailure([error.Message], json, input, stdout, stderr); }
        }
        string? sculptStep = null;
        if (File.Exists(input) && Path.GetExtension(input).Equals(".firmament", StringComparison.OrdinalIgnoreCase) && SculptingAuthoring.IsSculptingSource(File.ReadAllText(input)))
        {
            var sculpt = SculptingAuthoring.CompileFile(input);
            if (sculpt.OutputMesh is not null || !sculpt.IsSuccess)
            {
                if (debugIr is not null) sculpt = sculpt with { IsSuccess = false, Diagnostics = [..sculpt.Diagnostics, new("mesh-sculpt-debug-ir-unsupported", "Use inspect --json for cage identities and provenance; SurfaceMeshIR debug output belongs to BRep tessellation.")] };
                return MeshSculptCommand.Write(sculpt, input, output, format.ToLowerInvariant(), "mesh", json, stdout, stderr);
            }
            var exact = SculptStepExporter.Export(sculpt.OutputState!, sculpt.ModelName);
            if (!exact.IsSuccess) return WriteMeshFailure(exact.Diagnostics.Select(d => d.Code + ": " + d.Message), json, input, stdout, stderr);
            sculptStep = exact.Step;
        }
        if (!string.Equals(format, "stl", StringComparison.OrdinalIgnoreCase) && !string.Equals(format, "obj", StringComparison.OrdinalIgnoreCase))
        {
            stderr.WriteLine("Mesh supports binary STL, topology-preserving OBJ, and assembly-json definition/occurrence meshes.");
            return 1;
        }
        var fullInput = Path.GetFullPath(input);
        string stepText;
        if (sculptStep is not null) stepText = sculptStep;
        else if (string.Equals(Path.GetExtension(fullInput), ".firmament", StringComparison.OrdinalIgnoreCase) || string.Equals(Path.GetExtension(fullInput), ".firmfixture", StringComparison.OrdinalIgnoreCase))
        {
            var build = FirmamentBuildAndExport.Run(fullInput);
            if (!build.IsSuccess) return WriteMeshFailure(build.Diagnostics.Select(d => d.Message), json, fullInput, stdout, stderr);
            stepText = build.Value.Export.StepText;
        }
        else if (string.Equals(Path.GetExtension(fullInput), ".step", StringComparison.OrdinalIgnoreCase) || string.Equals(Path.GetExtension(fullInput), ".stp", StringComparison.OrdinalIgnoreCase)) stepText = File.ReadAllText(fullInput);
        else { stderr.WriteLine("Mesh expects Firmament (.firmament, .firmfixture) or STEP (.step, .stp) input."); return 1; }
        var importWatch = System.Diagnostics.Stopwatch.StartNew();
        var imported = Step242Importer.ImportBody(stepText);
        importWatch.Stop();
        if (!imported.IsSuccess || imported.Value is null) return WriteMeshFailure(imported.Diagnostics.Select(d => d.Message), json, fullInput, stdout, stderr);
        string? irFailure = null;
        var meshIrWatch = System.Diagnostics.Stopwatch.StartNew();
        if (!SurfaceMeshIrTessellator.TryBuild(imported.Value, SurfaceMeshPolicy.FromDisplayOptions(DisplayTessellationOptions.Default), out var document, out irFailure)
            || !SurfaceMeshIrValidator.TryValidate(document, out irFailure))
        {
            var diagnostic = irFailure ?? "SurfaceMeshIR does not support this B-rep family or its topology did not validate.";
            var audit = SurfaceMeshIrTessellator.Audit(imported.Value);
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "mesh", success = false, input = fullInput, diagnostics = new[] { diagnostic }, coverage = audit }, JsonOptions));
            else stderr.WriteLine($"Mesh failed: {diagnostic}");
            return 1;
        }
        meshIrWatch.Stop();
        if (!string.IsNullOrWhiteSpace(debugIr))
        {
            var debugPath = Path.GetFullPath(debugIr);
            Directory.CreateDirectory(Path.GetDirectoryName(debugPath)!);
            File.WriteAllText(debugPath, SurfaceMeshIrDebug.ToJson(document));
        }
        var outputPath = Path.GetFullPath(output ?? Path.ChangeExtension(fullInput, string.Equals(format, "obj", StringComparison.OrdinalIgnoreCase) ? ".obj" : ".stl"));
        Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!);
        if (string.Equals(format, "obj", StringComparison.OrdinalIgnoreCase))
        {
            var serializationWatch = System.Diagnostics.Stopwatch.StartNew();
            var obj = SurfaceMeshObjExporter.Export(document, Path.GetFileNameWithoutExtension(outputPath));
            File.WriteAllText(outputPath, obj.Text);
            serializationWatch.Stop();
            var objBytes = new FileInfo(outputPath).Length;
            var watertight = SurfaceMeshIrTessellator.TryLowerToTriangleMesh(document, out _, out var objTopology) && objTopology.IsWatertight;
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new
            {
                command = "mesh", success = true, pipeline = "SurfaceMeshIR", input = fullInput, outputPath, format = "obj",
                coverage = SurfaceMeshIrTessellator.Audit(imported.Value),
                planarAudit = SurfaceMeshIrPlanarAudit.Analyze(document),
                patchCount = document.Metrics.PatchCount, cellCount = document.Metrics.CellCount, polygonCount = obj.PolygonCount,
                quadCount = obj.QuadCount, triangleCount = obj.TriangleCount, boundaryPolygonCount = obj.BoundaryPolygonCount,
                quadPercentage = obj.PolygonCount == 0 ? 0d : (double)obj.QuadCount / obj.PolygonCount * 100d,
                vertexCount = obj.VertexCount, normalCount = obj.NormalCount, textureCoordinateCount = obj.TextureCoordinateCount,
                finalTriangleCount = objTopology.TriangleCount, watertight,
                crackCount = objTopology.CrackCount, nonManifoldEdgeCount = objTopology.NonManifoldEdgeCount,
                orientationConflictEdgeCount = objTopology.OrientationConflictEdgeCount,
                consistentlyOriented = objTopology.IsConsistentlyOriented,
                duplicateTriangleCount = objTopology.DuplicateTriangleCount, zeroAreaTriangleCount = objTopology.ZeroAreaTriangleCount,
                connected = objTopology.IsConnected, outwardOriented = objTopology.IsOutwardOriented,
                foreignTrimResolutionCount = document.ForeignTrimResolutions?.Count ?? 0,
                sampledBSplineTrimCount = document.ForeignTrimResolutions?.Count(item => item.ResolutionKind == ForeignTrimResolutionKind.SampledBSpline) ?? 0,
                trimResolutions = document.ForeignTrimResolutions?.Select(item => new
                {
                    edgeId = item.SourceEdgeId.Value,
                    sourceCurveKind = item.SourceCurveKind.ToString(),
                    resolutionKind = item.ResolutionKind.ToString(),
                    adjacentSupportFamilies = item.AdjacentSupportFamilies,
                    sampleCount = item.SharedSamplePlan.Samples.Count,
                    maxChordalDeviation = item.SharedSamplePlan.MaxChordalDeviation,
                    maxTangentDeviationRadians = item.SharedSamplePlan.MaxTangentDeviationRadians,
                    recognitionCandidate = item.RecognitionCandidate,
                    maxRecognitionDeviation = item.MaxRecognitionDeviation,
                    recognitionTolerance = item.RecognitionTolerance,
                    provenance = item.Provenance
                }),
                timingsMilliseconds = new { brepImport = importWatch.Elapsed.TotalMilliseconds, surfaceMeshIr = meshIrWatch.Elapsed.TotalMilliseconds, objSerialization = serializationWatch.Elapsed.TotalMilliseconds },
                maxChordalDeviation = document.Metrics.MaxChordalDeviation, normalDeviation = document.Metrics.MaxNormalDeviation,
                minEdgeLength = document.Metrics.MinEdgeLength, maxEdgeLength = document.Metrics.MaxEdgeLength,
                worstAspectRatio = document.Metrics.WorstAspectRatio, approximateStructuredBufferBytes = document.Metrics.ApproximateBufferBytes,
                deterministicHash = obj.DeterministicHash, bytes = objBytes
            }, JsonOptions));
            else stdout.WriteLine($"SurfaceMeshIR OBJ: {outputPath}\nPatches: {document.Metrics.PatchCount}; polygons: {obj.PolygonCount}; quads: {obj.QuadCount}; triangles: {obj.TriangleCount}; max chordal error: {document.Metrics.MaxChordalDeviation:R}");
            return 0;
        }
        var loweringWatch = System.Diagnostics.Stopwatch.StartNew();
        if (!SurfaceMeshIrTessellator.TryLowerToTriangleMesh(document, out var mesh, out var topology))
            return WriteMeshFailure([$"SurfaceMeshIR could not lower the validated document to a watertight TriangleMesh for STL: cracks={topology.CrackCount}, nonmanifold={topology.NonManifoldEdgeCount}, orientationConflicts={topology.OrientationConflictEdgeCount}, duplicates={topology.DuplicateTriangleCount}, zeroArea={topology.ZeroAreaTriangleCount}, connected={topology.IsConnected}, outward={topology.IsOutwardOriented}."], json, fullInput, stdout, stderr);
        try { BinaryStlExporter.Export(outputPath, mesh, out topology); }
        catch (InvalidOperationException error) { return WriteMeshFailure([error.Message], json, fullInput, stdout, stderr); }
        loweringWatch.Stop();
        var stlBytes = new FileInfo(outputPath).Length;
        if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "mesh", success = true, pipeline = "SurfaceMeshIR", input = fullInput, outputPath, format = "binary-stl", patchCount = document.Metrics.PatchCount, cellCount = document.Metrics.CellCount, quadCount = document.Metrics.QuadCount, triangleCount = topology.TriangleCount, vertexCount = topology.VertexCount, watertight = topology.IsWatertight, orientationConflictEdgeCount = topology.OrientationConflictEdgeCount, consistentlyOriented = topology.IsConsistentlyOriented, outwardOriented = topology.IsOutwardOriented, meshSignedVolumeMm3 = topology.HasValidSignedVolume ? (double?)topology.SignedVolume : null, maxChordalDeviation = document.Metrics.MaxChordalDeviation, normalDeviation = document.Metrics.MaxNormalDeviation, timingsMilliseconds = new { brepImport = importWatch.Elapsed.TotalMilliseconds, surfaceMeshIr = meshIrWatch.Elapsed.TotalMilliseconds, triangleLoweringAndStlSerialization = loweringWatch.Elapsed.TotalMilliseconds }, deterministicHash = mesh.DeterministicHash, bytes = stlBytes }, JsonOptions));
        else stdout.WriteLine($"SurfaceMeshIR STL: {outputPath}\nTriangles: {topology.TriangleCount}; watertight: {topology.IsWatertight}; max chordal error: {document.Metrics.MaxChordalDeviation:R}");
        return 0;
    }

    private static int WriteMeshFailure(IEnumerable<string> diagnostics, bool json, string input, TextWriter stdout, TextWriter stderr)
    {
        var messages = diagnostics.ToArray();
        if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "mesh", success = false, input, diagnostics = messages }, JsonOptions));
        else foreach (var message in messages) stderr.WriteLine($"Mesh failed: {message}");
        return 1;
    }

    private static int RunInspect(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0]))
        {
            WriteInspectHelp(stdout);
            return args.Length == 0 ? 1 : 0;
        }

        var input = args[0];
        if (File.Exists(input) && Aetheris.Kernel.Firmament.Garment.GarmentAuthoring.HasRoot(File.ReadAllText(input)))
            return GarmentCommand.Run(["inspect", .. args], stdout, stderr);
        if (File.Exists(input) && Aetheris.Kernel.Firmament.Scene.SceneAuthoring.HasRoot(File.ReadAllText(input)))
            return SceneCommand.Run(["inspect", .. args], stdout, stderr);
        if (File.Exists(input) && (Path.GetExtension(input).Equals(".firmasm", StringComparison.OrdinalIgnoreCase) || FirmamentLanguageAnalysisService.HasAssemblyRoot(File.ReadAllText(input), input)))
            return RunAsmInspect(args, stdout, stderr);
        var json = args.Skip(1).SequenceEqual(["--json"]);
        if (!json && args.Length > 1) { stderr.WriteLine($"Unknown inspect option '{args[1]}'."); stderr.WriteLine(InspectUsage); return 1; }
        if (!File.Exists(input)) { stderr.WriteLine($"Inspect input was not found: {input}"); return 1; }

        var fullPath = Path.GetFullPath(input);
        var extension = Path.GetExtension(fullPath);
        if (string.Equals(extension, ".step", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".stp", StringComparison.OrdinalIgnoreCase))
            return RunAnalyze([fullPath, .. args.Skip(1)], stdout, stderr);
        if (!string.Equals(extension, ".firmament", StringComparison.OrdinalIgnoreCase))
        {
            stderr.WriteLine("Inspect expects Firmament (.firmament) or STEP (.step, .stp) input.");
            return 1;
        }

        var source = File.ReadAllText(fullPath);
        if (SectionChainAuthoringParser.IsSectionChainSource(source))
            return RunSectionChain(["inspect", fullPath, .. args.Skip(1)], stdout, stderr);
        var frontend = FirmamentFrontendSchemas.Select(source);
        if (!frontend.IsSuccess)
        {
            return WriteFrontendRejection(frontend, source, fullPath, "inspect", json, stdout, stderr);
        }
        source = frontend.Source;
        if (SheetMetalFirmament.LooksLikeSheetMetal(source))
            return RunSheetMetal(["inspect", fullPath, .. args.Skip(1)], stdout, stderr);
        if (PlasticShellFirmament.LooksLikePlasticShell(source))
        {
            var plastic = PlasticShellFirmament.Compile(source, fullPath);
            var plasticReport = new { command = "inspect", success = plastic.IsSuccess, input = fullPath, domain = "PlasticShell", model = plastic.ModelName,
                plasticShell = plastic.Intent, state = plastic.State?.StateId, geometricDelta = plastic.State?.Delta, manufacturingEvidence = plastic.State?.Evidence, diagnostics = PlasticShellFirmament.KernelDiagnostics(plastic).Select(d=>FirmamentBuildAdmissionValidation.Present(d,fullPath,source)).ToArray() };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(plasticReport, JsonOptions));
            else if (plastic.IsSuccess && plastic.State is { } state)
            {
                stdout.WriteLine($"PlasticShell {state.Intent.PlasticShellId}: wall {state.Evidence.WallThickness.Minimum:G6}..{state.Evidence.WallThickness.Maximum:G6} mm; draft minimum {state.Evidence.Draft.Min(x => x.DraftAngleDegrees):G6} deg; undercuts {state.Evidence.Pullability.Undercuts.Count}; ribs {state.Evidence.RibNetwork?.SelectedCandidate ?? "none"}");
                if (state.Evidence.RibNetwork is { } ribs)
                    foreach (var candidate in ribs.Candidates) stdout.WriteLine($"  {candidate.CandidateId}: eligible={candidate.Eligible}; support={candidate.Metrics.SupportProxy:F6}; flow={candidate.Metrics.FlowCompatibility:F6}; sink={candidate.Metrics.SinkProxy:F6}; length={candidate.Metrics.RibLength:F6}; complexity={candidate.Metrics.Complexity:F6}; utility={candidate.Metrics.Utility:F6}");
            }
            else WriteFrontendDiagnostics(PlasticShellFirmament.KernelDiagnostics(plastic).Select(d=>FirmamentBuildAdmissionValidation.Present(d,fullPath,source)),stderr);
            return plastic.IsSuccess ? 0 : 1;
        }
        if (SculptingAuthoring.IsSculptingSource(source))
        {
            var sculpt = SculptingAuthoring.Compile(source,fullPath);
            var sculptReport = new { command = "inspect", success = sculpt.IsSuccess, input = fullPath, domain = "Sculpting", model = sculpt.ModelName,
                states = sculpt.States.Values.Select(state => new { state = DescribeSculptState(state), geometricDelta = state.Delta, validationEvidence = state.ValidationEvidence }),
                outputState = sculpt.OutputState?.StateId, meshStates = sculpt.MeshStates, outputMesh = sculpt.OutputMesh, timingsMilliseconds = sculpt.Timings, diagnostics = SculptingAuthoring.KernelDiagnostics(sculpt).Select(d=>FirmamentBuildAdmissionValidation.Present(d,fullPath,source)).ToArray() };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(sculptReport, JsonOptions));
            else if (sculpt.IsSuccess) { stdout.WriteLine($"Sculpting model {sculpt.ModelName}: output {sculpt.OutputState?.AuthoredName ?? sculpt.OutputMesh!.Name} ({sculpt.OutputState?.StateId.Value ?? sculpt.OutputMesh!.StateId})"); foreach (var state in sculpt.States.Values) stdout.WriteLine($"State {state.AuthoredName}: {state.StateId} <- {state.PredecessorStateId?.Value ?? "<initial>"}"); }
            else WriteFrontendDiagnostics(SculptingAuthoring.KernelDiagnostics(sculpt).Select(d=>FirmamentBuildAdmissionValidation.Present(d,fullPath,source)),stderr);
            return sculpt.IsSuccess ? 0 : 1;
        }
        if (PipingAuthoring.IsPipingSource(source))
        {
            var piping = PipingAuthoring.Compile(source, fullPath);
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "inspect", success = piping.IsSuccess, input = fullPath, domain = "Piping", piping = piping.Report, diagnostics = piping.KernelDiagnostics().Select(d => FirmamentBuildAdmissionValidation.Present(d, fullPath, source)).ToArray() }, JsonOptions));
            else if (piping.IsSuccess && piping.Report is { } pipingReport) stdout.WriteLine($"Piping system {pipingReport.PipingSystem}: {pipingReport.Connections.Count} connections, {pipingReport.Routes.Count} routes, {pipingReport.PipeSegments.Count} pipe segments, {pipingReport.Fittings.Count} fittings, {pipingReport.Nozzles.Count} equipment nozzles, {pipingReport.Mates.Count} endpoint mates");
            else foreach (var diagnostic in piping.KernelDiagnostics().Select(d => FirmamentBuildAdmissionValidation.Present(d, fullPath, source))) stderr.WriteLine($"{diagnostic.SourceFile}:{diagnostic.Line}:{diagnostic.Column}: {diagnostic.Severity} {diagnostic.Code}: {diagnostic.Message}");
            return piping.IsSuccess ? 0 : 1;
        }
        if (StructuralAuthoring.IsStructuralSource(source))
        {
            var structural = StructuralAuthoring.Compile(source, fullPath);
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "inspect", success = structural.IsSuccess, input = fullPath, domain = "Structural", structural = structural.Report, diagnostics = structural.KernelDiagnostics().Select(d=>FirmamentBuildAdmissionValidation.Present(d,fullPath,source)).ToArray() }, JsonOptions));
            else if (structural.IsSuccess && structural.Report is { } structuralReport) stdout.WriteLine($"Structure {structuralReport.Structure}: {structuralReport.Members.Count} members, {structuralReport.Joints.Count} joints, {structuralReport.Welds.Count} welds, {structuralReport.CutList.Count} cut-list groups");
            else WriteFrontendDiagnostics(structural.KernelDiagnostics().Select(d=>FirmamentBuildAdmissionValidation.Present(d,fullPath,source)),stderr);
            return structural.IsSuccess ? 0 : 1;
        }
        if (frontend.Schema == FirmamentFrontendSchema.SectionChain)
        {
            return RunSectionChain(["inspect", fullPath, .. args.Skip(1)], stdout, stderr);
        }
        if (PlateauAuthoring.IsSource(source) && !System.Text.RegularExpressions.Regex.IsMatch(source, @"\bAssembly\s+"))
        {
            var plateau = FirmamentBuildAndExport.CompileSource(source, Path.GetDirectoryName(fullPath));
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "inspect", success = plateau.IsSuccess, input = fullPath,
                plateau = plateau.IsSuccess ? plateau.Value.Plateau : null, diagnostics = plateau.Diagnostics }, JsonOptions));
            else if (plateau.IsSuccess) stdout.WriteLine($"Plateau: {plateau.Value.Plateau!.FaceCount} faces; G2 contact/trim report available with --json.");
            else foreach (var d in plateau.Diagnostics) stderr.WriteLine(d.Message);
            return plateau.IsSuccess ? 0 : 1;
        }
        if (GearAuthoring.IsGearSource(source))
        {
            var gear = GearAuthoring.Parse(source);
            var payload = new
            {
                command = "inspect", success = gear.IsSuccess, input = fullPath, domain = "GearLibrary", model = gear.ModelName, units = "mm",
                gears = gear.Gears.Select(item => new
                {
                    item.Name, family = item.Family.ToString(), item.Teeth, module = item.ModuleMm,
                    pressureAngle = item.PressureAngleDegrees, pitchDiameter = item.PitchDiameterMm,
                    baseDiameter = item.BaseDiameterMm, outsideDiameter = item.AddendumDiameterMm,
                    rootDiameter = item.RootDiameterMm, faceWidth = item.FaceWidthMm, boreDiameter = item.BoreDiameterMm,
                    axis = item.Axis, phase = item.PhaseDegrees, backlash = item.BacklashMm,
                    pitchConeAngle = item.PitchConeAngleDegrees,
                    stableToothIds = item.Teeth is { } count ? Enumerable.Range(0, count).Select(index => $"{item.Name}.Tooth{index}") : []
                }),
                interfaces = gear.Interfaces.Select(item => new { item.Name, gearA = item.A.Name, gearB = item.B.Name, item.Kind, item.Compatible,
                    expectedCenterDistance = item.ExpectedCenterDistanceMm, item.Ratio, item.RotationSign,
                    item.AxisRelation, shaftAngle = item.ShaftAngleDegrees, engagementPhase = item.EngagementPhaseDegrees,
                    item.AllowedDirection, item.RejectionReasons }),
                diagnostics = gear.Diagnostics
            };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(payload, JsonOptions));
            else if (gear.IsSuccess) foreach (var item in gear.Gears) stdout.WriteLine($"{item.Family} {item.Name}: {item.Teeth?.ToString() ?? "n/a"} teeth, pitch diameter {item.PitchDiameterMm?.ToString("G12") ?? "n/a"} mm");
            else foreach (var diagnostic in gear.Diagnostics) stderr.WriteLine("error: " + diagnostic);
            return gear.IsSuccess ? 0 : 1;
        }
        var library = FirmamentStandardLibraryResolver.Resolve(source, out var libraryDiagnostics);
        var inspectionSource = library?.Source ?? source;
        var sweepSource = ExpandSweepInspectionSource(source, out var sweepExpansionDiagnostics);
        if (RevolveAuthoringParser.IsRevolveSource(inspectionSource))
        {
            var revolve = RevolveAuthoringParser.Parse(inspectionSource, out var revolveDiagnostics);
            var revolveSuccess = revolve is not null && revolveDiagnostics.Count == 0;
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new
            {
                command = "inspect", success = revolveSuccess, input = fullPath, domain = "Revolve",
                revolve = revolve is null ? null : new
                {
                    revolve.Name, profile = revolve.Profile.Name, axis = revolve.AxisName,
                    axisOrigin = new[] { revolve.Axis.Origin.X, revolve.Axis.Origin.Y, revolve.Axis.Origin.Z },
                    axisDirection = new[] { revolve.Axis.Direction.X, revolve.Axis.Direction.Y, revolve.Axis.Direction.Z },
                    sweepRadians = revolve.SweepRadians, sweepDegrees = revolve.SweepRadians * 180d / Math.PI,
                    alias = revolve.AuthoredAlias, direction = revolve.SweepRadians < 0d ? "Negative" : "Positive",
                    classification = Math.Abs(Math.Abs(revolve.SweepRadians) - 2d * Math.PI) <= 1e-9 ? "Full" : "Partial",
                    profileFrame = revolve.Profile.PlaneFrame
                },
                diagnostics = revolveDiagnostics
            }, JsonOptions));
            else if (revolveSuccess) stdout.WriteLine($"Revolve {revolve!.Name}: {revolve.Profile.Name} about {revolve.AxisName}, {revolve.SweepRadians * 180d / Math.PI:R}deg ({(Math.Abs(Math.Abs(revolve.SweepRadians) - 2d * Math.PI) <= 1e-9 ? "Full" : "Partial")})");
            else foreach (var diagnostic in revolveDiagnostics) stderr.WriteLine("error: " + diagnostic);
            return revolveSuccess ? 0 : 1;
        }
        if (WireFormAuthoring.IsWireFormSource(source))
        {
            var authored = sweepSource is null ? null : WireFormAuthoring.Parse(sweepSource);
            var wireDiagnostics = sweepExpansionDiagnostics.Concat(authored is null ? [] : authored.IsSuccess ? WireFormBRepMaterializer.Validate(authored.Value) : authored.Diagnostics.Select(item => item.Message)).ToArray();
            var wireSuccess = authored?.IsSuccess == true && wireDiagnostics.Length == 0;
            var wire = authored?.IsSuccess == true ? authored.Value : null;
            var wireReportPayload = new
            {
                command = "inspect", success = wireSuccess, input = fullPath, domain = "WireForm", model = Path.GetFileNameWithoutExtension(fullPath), units = "mm",
                wireForm = wire is null ? null : new
                {
                    wireFormId = wire.Name, diameter = wire.DiameterMm, material = wire.Material.Identity.FirmamentPath,
                    operationCount = wire.Operations.Count, straightCount = wire.Operations.Count(x => x is WireStraightAir), bendCount = wire.Operations.Count(x => x is WireBendAir), coilCount = wire.Operations.Count(x => x is WireCoilAir), knotCount = wire.Operations.Count(x => x is WireKnotPathAir),
                    totalStraightLength = wire.TotalStraightLengthMm, totalBendLength = wire.TotalBendLengthMm, totalCoilLength = wire.TotalCoilLengthMm, totalWireLength = wire.TotalWireLengthMm,
                    bendRadiusSemantics = "CenterlineRadius", frameTransportPolicy = wire.FrameTransportPolicy,
                    startTerminal = new { position = new[] { wire.StartState.Position.X, wire.StartState.Position.Y, wire.StartState.Position.Z }, tangent = new[] { wire.StartState.Tangent.X, wire.StartState.Tangent.Y, wire.StartState.Tangent.Z }, diameter = wire.DiameterMm },
                    endTerminal = new { position = new[] { wire.EndState.Position.X, wire.EndState.Position.Y, wire.EndState.Position.Z }, tangent = new[] { wire.EndState.Tangent.X, wire.EndState.Tangent.Y, wire.EndState.Tangent.Z }, diameter = wire.DiameterMm },
                    operations = wire.Operations.Select(operation => new { operation.Ordinal, operation.Name, kind = operation switch { WireStraightAir => "Straight", WireBendAir => "Bend", WireAxisCoilAir => "AxisCoil", WireSurfaceCoilAir => "SurfaceCoil", WireKnotPathAir => "KnotPath", _ => "Unknown" }, operation.LengthMm,
                        radius = operation is WireBendAir bend ? bend.RadiusMm : (double?)null, angleDegrees = operation is WireBendAir angle ? angle.AngleRadians * 180d / Math.PI : (double?)null,
                        plane = operation is WireBendAir plane ? plane.Plane : null, coilKind = operation is WireCoilAir coil ? coil.CoilKind : null,
                        turns = operation is WireCoilAir turns ? turns.Turns : (double?)null, handedness = operation is WireCoilAir handed ? handed.Handedness.ToString() : null,
                        pitch = operation switch { WireAxisCoilAir axis => axis.PitchMm, WireSurfaceCoilAir surface => surface.AxialPitchMm, _ => (double?)null },
                        progressionLaw = operation is WireCoilAir progression ? progression.ProgressionLaw : null, selfClearance = operation is WireCoilAir self ? self.MinimumSelfClearanceMm : (double?)null,
                        supportClearance = operation is WireCoilAir support ? support.SupportClearanceMm : null, representation = operation switch { WireKnotPathAir => "ExactEvaluablePeriodicKnotLaw->ClosureCorrectedNonRationalBSplineTube", WireCoilAir => "ExactEvaluableWindingLaw->NonRationalBSplineTube", _ => "Analytic" },
                        approximationTolerance = operation is WireEvaluablePathAir tolerance ? tolerance.ApproximationToleranceMm : (double?)null,
                        approximationSegmentCount = operation is WireEvaluablePathAir segments ? segments.ApproximationSegmentCount : (int?)null,
                        approximationMaxError = operation is WireEvaluablePathAir maxError ? maxError.ApproximationError.MaxMm : (double?)null,
                        approximationRmsError = operation is WireEvaluablePathAir rmsError ? rmsError.ApproximationError.RmsMm : (double?)null,
                        knot = operation is WireKnotPathAir knot ? new { family = knot.Family.ToString(), knot.P, knot.Q, knot.ComponentCount, knot.Closed, knot.ScaleMm, knot.MajorRadiusMm, knot.MinorRadiusMm, handedness = knot.Handedness.ToString(), phaseDegrees = knot.PhaseRadians * 180d / Math.PI, seamParameter = knot.SeamParameter,
                            centerlineLength = knot.LengthMm, lengthIntegrationError = knot.Qualification.LengthIntegrationErrorMm, minimumNonlocalCenterlineDistance = knot.Qualification.MinimumNonlocalDistanceMm, minimumLocalCurvatureRadius = knot.Qualification.MinimumCurvatureRadiusMm, tubeRadiusLimit = knot.Qualification.TubeRadiusLimitMm, maximumAdmittedDiameter = knot.Qualification.MaximumAdmittedDiameterMm, closestParameter1 = knot.Qualification.ClosestParameter1, closestParameter2 = knot.Qualification.ClosestParameter2,
                            rawClosureRotation = knot.FrameClosure.RawClosureRotationRadians, appliedDistributedCorrection = knot.FrameClosure.AppliedCorrectionRadians, finalClosureRotationError = knot.FrameClosure.FinalClosureErrorRadians, qualificationMethod = knot.Qualification.Method } : null,
                        stableId = operation.StableId(wire.Name), input = operation.Input, output = operation.Output })
                }, diagnostics = wireDiagnostics
            };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(wireReportPayload, JsonOptions));
            else if (wireSuccess) stdout.WriteLine($"WireForm {wire!.Name}: {wire.Operations.Count} operations, {wire.TotalWireLengthMm:G12} mm stock length");
            else foreach (var diagnostic in wireDiagnostics) stderr.WriteLine($"error: {diagnostic}");
            return wireSuccess ? 0 : 1;
        }
        if (CircularSweepAuthoring.IsSweepSource(source))
        {
            var authored = sweepSource is null ? null : CircularSweepAuthoring.Parse(sweepSource);
            var sweepDiagnostics = sweepExpansionDiagnostics.Concat(authored is null ? [] : authored.IsSuccess ? CircularSweepBRepMaterializer.Validate(authored.Value) : authored.Diagnostics.Select(item => item.Message)).ToArray();
            var sweepSuccess = authored?.IsSuccess == true && sweepDiagnostics.Length == 0;
            var sweepReport = new
            {
                command = "inspect", success = sweepSuccess, input = fullPath,
                model = Path.GetFileNameWithoutExtension(fullPath), units = "mm",
                sweep = authored?.IsSuccess == true ? new { authored.Value.Name, diameter = authored.Value.Diameter, radius = authored.Value.Radius,
                    material = authored.Value.Material.Identity.FirmamentPath, path = authored.Value.Path.Name,
                    segments = authored.Value.Path.Segments.Select(segment => new { segment.Name, segment.SemanticKind, geometry = segment.Geometry.GetType().Name, segment.StableId }),
                    provenance = authored.Value.Provenance } : null,
                conceptPaths = sweepSource is null ? [] : ProfileAuthoringParser.InspectConceptPaths(sweepSource), diagnostics = sweepDiagnostics
            };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(sweepReport, JsonOptions));
            else if (sweepSuccess) stdout.WriteLine($"Sweep {authored!.Value.Name}: {authored.Value.Path.Segments.Count} segments, {authored.Value.Diameter:G6} mm diameter");
            else foreach (var diagnostic in sweepDiagnostics) stderr.WriteLine($"error: {diagnostic}");
            return sweepSuccess ? 0 : 1;
        }
        var parse = FirmamentV2Parser.Parse(inspectionSource, Path.GetDirectoryName(fullPath));
        var document = parse.Document;
        var success = library is not null && parse.IsSuccess && document is not null;
        var features = (document?.ModifyBlocks?.SelectMany(block =>
            block.SemanticHoles.Select(hole => $"Hole<{hole.Variant}> {hole.Name}")
            .Concat((block.EdgeFinishes ?? []).Select(finish => $"{finish.Kind} {finish.Name}"))) ?? [])
            .Concat((document?.Bosses ?? []).Select(feature => $"Boss {feature.Name}"))
            .Concat((document?.Pockets ?? []).Select(feature => $"Pocket {feature.Name}"))
            .ToList();
        var semanticValues = FirmamentSemanticValues.FromProfilesAndConceptPaths(inspectionSource, fullPath).ToList();
        if (PrismaticProfileCompositionParser.IsCompositionSource(inspectionSource))
        {
            var composition = PrismaticProfileCompositionParser.Parse(inspectionSource);
            if (composition.Feature is { } compositionFeature)
            {
                features.AddRange((compositionFeature.ShaftHoles ?? []).Select(feature => $"Hole<Shaft> {feature.Name}"));
                features.AddRange((compositionFeature.CounterboreHoles ?? []).Select(feature => $"Hole<Counterbore> {feature.Name}"));
            }
            semanticValues.AddRange(composition.Profiles.Values.OrderBy(profile => profile.Name, StringComparer.Ordinal).Select(profile =>
                FirmamentSemanticValues.FromProfile(profile, SemanticSourceSpan.Generated(fullPath),
                    [new("firmament-profile", profile.Name, "named Profile normalized before consumer")])));
        }
        else if (ProfileAuthoringParser.IsProfileSource(inspectionSource) && ProfileAuthoringParser.Parse(inspectionSource).Profile is { } directProfile)
            semanticValues.Add(FirmamentSemanticValues.FromProfile(directProfile, SemanticSourceSpan.Generated(fullPath),
                [new("firmament-profile", directProfile.Name, "named Profile normalized before consumer")]));
        if (document?.ConceptIr is { } conceptIr) semanticValues.AddRange(FirmamentSemanticValues.FromConceptIr(conceptIr, fullPath));
        if (document?.RecognizedRegions?.Count > 0) semanticValues.AddRange(FirmamentSemanticValues.FromRecognizedRegions(document, fullPath, inspectionSource));
        var inspectionDiagnostics = libraryDiagnostics.Concat(parse.Diagnostics).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();
        var report = new
        {
            command = "inspect",
            success,
            input = fullPath,
            model = document?.ModelName,
            units = document?.Units,
            bodies = document?.Solids.Select(solid => new { name = solid.Name, kind = solid.RecordType }).ToArray() ?? [],
            tables = document?.StaticAuthoring?.Tables?.Select(table => new
            {
                table.Name,
                rowType = table.RowType,
                keyField = table.KeyField,
                rowCount = table.RowCount,
                columns = table.Columns,
                table.SourceSpan
            }).ToArray() ?? [],
            sets = document?.StaticAuthoring?.Sets?.Select(set => new
            {
                setId = set.Name,
                elementType = set.ElementType,
                count = set.Entries.Count,
                entries = set.Entries.Select(entry => new
                {
                    entry.Name,
                    entry.Value,
                    entry.SourceOrder,
                    provenance = entry.Provenance
                })
            }).ToArray() ?? [],
            polygons = document?.Polygons?.Select(polygon => new
            {
                polygon.Name,
                polygon.Variant,
                center = new[] { polygon.CenterX, polygon.CenterY },
                diagonals = new[] { polygon.DiagonalX, polygon.DiagonalY },
                polygon.GeneratedPoints,
                polygon.GeneratedEdges,
                polygon.SourceSpan
            }).ToArray() ?? [],
            boundaries = document?.Boundaries?.Select(boundary => new
            {
                shapeId = boundary.Name,
                boundary.ShapeType,
                boundary.Variant,
                boundary.Capability,
                center = new[] { boundary.CenterX, boundary.CenterY },
                rotationDegrees = boundary.RotationDegrees,
                boundary.Dimensions,
                area = boundary.Area,
                perimeter = boundary.Perimeter,
                generatedGuides = boundary.GeneratedPoints.Concat(boundary.GeneratedEdges),
                exactCarrier = boundary.ExactCarrier,
                provenance = boundary.SourceSpan
            }).ToArray() ?? [],
            patterns = document?.StaticAuthoring?.Patterns?.Select(pattern => new
            {
                pattern.Name,
                pattern.Source,
                generator = pattern.Template,
                count = pattern.GeneratedCount,
                generatedInstances = pattern.GeneratedIds,
                associations = pattern.Associations,
                distribution = "AuthoredSourceOrder",
                status = "PreservedThroughFeatureAir;InstancesMaterializedAtBRepPlan"
            }).ToArray() ?? [],
            mirrors = document?.StaticAuthoring?.Mirrors?.Select(mirror => new
            {
                kind = "Mirrored",
                mirror.Destination,
                mirror.Source,
                acrossPlane = mirror.AcrossPlane,
                mirror.HandednessCorrection,
                mirror.Provenance,
                members = mirror.Members
            }).ToArray() ?? [],
            radialPatterns = document?.StaticAuthoring?.RadialPatterns?.Select(pattern => new
            {
                pattern.Name,
                pattern.Source,
                pattern.Axis,
                pattern.Count,
                pattern.AngleRadians,
                pattern.Distribution,
                instanceTransforms = pattern.Instances
            }).ToArray() ?? [],
            linearPatterns = document?.StaticAuthoring?.LinearPatterns ?? [],
            planarAxes = document?.StaticAuthoring?.PlanarAxes ?? [],
            equationCurves = document?.StaticAuthoring?.EquationCurves ?? [],
            templateInstances = (document?.TemplateInstantiations ?? document?.ConceptIr?.TemplateInstantiations)?.Select(instance => new
            {
                instance.Template,
                instance.Instance,
                instance.SpecializationIdentity,
                records = instance.RecordArguments?.OrderBy(pair => pair.Key, StringComparer.Ordinal).ToDictionary(pair => pair.Key, pair => new
                {
                    pair.Value.RecordType,
                    pair.Value.StaticValue,
                    pair.Value.Provenance,
                    members = pair.Value.Members.OrderBy(member => member.Key, StringComparer.Ordinal).ToDictionary(member => member.Key, member => member.Value, StringComparer.Ordinal)
                }, StringComparer.Ordinal)
            }).ToArray() ?? [],
            featureDefinitions = document?.FeatureDefinitions?.Select(definition => new
            {
                definition.Name,
                parameters = definition.Parameters,
                definition.ReturnType,
                definition.Scope,
                definition.Evaluation
            }).ToArray() ?? [],
            featureInvocations = document?.FeatureInvocations?.Select(invocation => new
            {
                invocation.Feature,
                invocation.Ordinal,
                invocation.Arguments,
                invocation.ReturnType,
                invocation.ExpandedSemanticKind,
                invocation.GeneratedByFeature,
                invocation.ResultIdentity,
                invocation.ApplicationIdentity,
                invocation.IdentityKind,
                invocation.Pattern,
                invocation.GeneratedResults,
                invocation.BindingScope,
                invocation.DefinitionOrigin,
                invocation.InvocationOrigin,
                invocation.ExpansionChain,
                invocation.Status
            }).ToArray() ?? [],
            featureExpansion = document?.FeatureExpansion,
            conceptPaths = ProfileAuthoringParser.InspectConceptPaths(inspectionSource),
            semanticValues = semanticValues.OrderBy(value => value.StableIdentity, StringComparer.Ordinal).Select(SemanticValueDescriptor.From).ToArray(),
            recognizedRegions = document?.RecognizedRegions?.Select(region => new
            {
                region.BodyName,
                region.RegionName,
                region.Kind,
                region.FaceRefs,
                region.Confidence,
                region.Evidence,
                region.Proposal
            }).ToArray() ?? [],
            features,
            pmi = document?.Pmi?.Select(item => new { item.Kind, item.Name, item.Target }).ToArray() ?? [],
            assertions = document?.VolumeAssertions?.Select(assertion => new { assertion.Id, assertion.TargetBodyId, assertion.ExpectedMm3, assertion.ToleranceMm3 }).ToArray() ?? [],
            diagnostics = inspectionDiagnostics
        };
        if (json) stdout.WriteLine(JsonSerializer.Serialize(report, JsonOptions));
        else if (!success)
        {
            stderr.WriteLine($"Inspect failed for {fullPath}.");
            foreach (var diagnostic in inspectionDiagnostics) stderr.WriteLine($"error: {diagnostic}");
        }
        else
        {
            stdout.WriteLine($"Model: {document!.ModelName}");
            stdout.WriteLine($"Bodies: {document.Solids.Count}");
            foreach (var feature in features) stdout.WriteLine($"Feature: {feature}");
            foreach (var item in document.Pmi ?? []) stdout.WriteLine($"PMI: {item.Kind} {item.Name}");
            foreach (var assertion in document.VolumeAssertions ?? []) stdout.WriteLine($"Assertion: Volume {assertion.TargetBodyId}");
        }
        return success ? 0 : 1;
    }

    private static int RunView(string[] args, TextWriter stdout, TextWriter stderr, ICadmataProcessLauncher launcher, string cliBaseDirectory)
    {
        if (args.Length == 0 || IsHelpFlag(args[0])) { WriteViewHelp(stdout); return args.Length == 0 ? 1 : 0; }
        var input = args[0];
        string? executable = null;
        var json = false;
        for (var i = 1; i < args.Length; i++)
        {
            if ((args[i] == "--cadmata-path" || args[i] == "--cad-assistant-path") && i + 1 < args.Length) { executable = args[++i]; continue; }
            if (args[i] == "--json") { json = true; continue; }
            stderr.WriteLine($"Unknown view option '{args[i]}'."); stderr.WriteLine(ViewUsage); return 1;
        }
        if (!File.Exists(input)) { stderr.WriteLine($"View input was not found: {input}"); return 1; }
        var fullInput = Path.GetFullPath(input);
        var extension = Path.GetExtension(fullInput);
        string stepPath;
        if (string.Equals(extension, ".firmament", StringComparison.OrdinalIgnoreCase))
        {
            var viewSource = File.ReadAllText(fullInput);
            if (SculptingAuthoring.IsSculptingSource(viewSource))
            {
                var sculpt = SculptingAuthoring.Compile(viewSource); var export = sculpt.OutputState is null ? null : SculptStepExporter.Export(sculpt.OutputState, sculpt.ModelName);
                if (sculpt.OutputMesh is not null) return MeshSculptCommand.Write(sculpt, fullInput, null, "step", "view", json, stdout, stderr);
                if (!sculpt.IsSuccess || export?.IsSuccess != true || export.Step is null)
                {
                    var messages = sculpt.Diagnostics.Select(x => $"{x.Code}: {x.Message}").Concat(export?.Diagnostics.Select(x => $"{x.Code}: {x.Message}") ?? []).ToArray();
                    if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "view", success = false, input = fullInput, diagnostics = messages }, JsonOptions)); else foreach (var message in messages) stderr.WriteLine($"error: {message}"); return 1;
                }
                stepPath = Path.ChangeExtension(fullInput, ".step"); File.WriteAllText(stepPath, export.Step);
            }
            else
            {
                var build = FirmamentBuildAndExport.Run(fullInput);
                if (!build.IsSuccess)
                {
                    if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "view", success = false, input = fullInput, diagnostics = build.Diagnostics.Select(d => new { d.Source, d.Message, severity = d.Severity.ToString() }) }, JsonOptions));
                    else { stderr.WriteLine("View stopped because build failed."); foreach (var diagnostic in build.Diagnostics) stderr.WriteLine($"error: {diagnostic.Message}"); }
                    return 1;
                }
                stepPath = build.Value.OutputPath;
            }
            if (!json)
            {
                stdout.WriteLine($"✓ Built {Path.GetFileName(fullInput)}");
                stdout.WriteLine($"  STEP: {stepPath}");
                stdout.WriteLine();
            }
        }
        else if (string.Equals(extension, ".step", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".stp", StringComparison.OrdinalIgnoreCase)) stepPath = fullInput;
        else { stderr.WriteLine("View expects Firmament (.firmament) or STEP (.step, .stp) input."); return 1; }

        var discovery = CadmataDiscovery.Resolve(executable, cliBaseDirectory);
        if (discovery is null)
        {
            const string message = "Cadmata was not found. Install the packaged Cadmata host beside Aetheris, put it on PATH, or set --cadmata-path (AETHERIS_CADMATA_PATH; legacy AETHERIS_CAD_ASSISTANT_PATH is also supported).";
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "view", success = false, source = string.Equals(extension, ".firmament", StringComparison.OrdinalIgnoreCase) ? fullInput : null, stepPath, cadmataPath = (string?)null, launched = false, diagnostics = new[] { message } }, JsonOptions));
            else stderr.WriteLine(message);
            return 1;
        }
        Process? process;
        try
        {
            process = launcher.Launch(discovery.Path, stepPath);
            if (process is null) throw new InvalidOperationException("Process.Start returned no process.");
        }
        catch (Exception ex)
        {
            var message = $"Could not open '{stepPath}' in Cadmata: {ex.Message}";
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "view", success = false, source = string.Equals(extension, ".firmament", StringComparison.OrdinalIgnoreCase) ? fullInput : null, stepPath, cadmataPath = discovery.Path, launched = false, diagnostics = new[] { message } }, JsonOptions));
            else stderr.WriteLine(message);
            return 1;
        }
        if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "view", success = true, source = string.Equals(extension, ".firmament", StringComparison.OrdinalIgnoreCase) ? fullInput : null, stepPath, cadmataPath = discovery.Path, launched = true, processId = process.Id, diagnostics = Array.Empty<string>() }, JsonOptions));
        else stdout.WriteLine($"✓ Opened {Path.GetFileName(stepPath)} in Cadmata");
        return 0;
    }


    private static int RunInspectProfile(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0])) { stdout.WriteLine(InspectProfileUsage); return args.Length == 0 ? 1 : 0; }
        var json = args.Skip(1).All(x => x == "--json");
        if (!json) { stderr.WriteLine(InspectProfileUsage); return 1; }
        if (!File.Exists(args[0])) { stderr.WriteLine($"Profile source was not found: {args[0]}"); return 1; }
        var source = File.ReadAllText(args[0]);
        if (PrismaticProfileCompositionParser.IsCompositionSource(source))
        {
            var composition = PrismaticProfileCompositionParser.Parse(source);
            if (composition.Profiles.Count == 0) { stderr.WriteLine(string.Join(Environment.NewLine, composition.Diagnostics)); return 1; }
            var profiles = composition.Profiles.Values.OrderBy(x => x.Name, StringComparer.Ordinal).Select(profile =>
            {
                var validation = ResolvedProfile2DValidator.Validate(profile);
                return new
                {
                    profile.Name, profile.PlaneFrame, loops = profile.Loops.Count,
                    lineSegments = profile.Loops.SelectMany(x => x.Segments).Count(x => x.Geometry is LineArcLineSegment2D),
                    arcSegments = profile.Loops.SelectMany(x => x.Segments).Count(x => x.Geometry is LineArcCircularArc2D),
                    validation.IsValid, validation.SignedArea, validation.Diagnostics,
                    junctions = DescribeProfileJunctions(profile, source, profile.Name),
                    provenance = profile.Loops.SelectMany(x => x.Segments).Select(x => new { x.Name, x.Provenance.StableId, x.Provenance.ConceptStableId, x.Provenance.Derivation, x.Provenance.TracedFrom, x.Provenance.Reversed, x.Provenance.PipelineIndex, x.Provenance.InvocationSourceRange })
                };
            }).ToArray();
            stdout.WriteLine(JsonSerializer.Serialize(new { profiles, expansion = composition.Expansion, diagnostics = composition.Diagnostics }, JsonOptions));
            return composition.Diagnostics.Count == 0 && profiles.All(x => x.IsValid) ? 0 : 1;
        }
        var parsed = ProfileAuthoringParser.Parse(source);
        if (parsed.Profile is null) { stderr.WriteLine(string.Join(Environment.NewLine, parsed.Diagnostics)); return 1; }
        var validation = ResolvedProfile2DValidator.Validate(parsed.Profile);
        var plan = validation.IsValid
            ? ProfileExtrusionBRepPlanner.TryPlan(new LineArcProfileExtrudeRequest(parsed.Profile.Loops.Select(l => new LineArcProfileLoop2D(l.Segments.Select(s => s.Geometry).ToArray(), !l.IsOuter)).ToArray(), parsed.Height, parsed.Profile.EffectiveConstructionPlane, parsed.Profile.LocalStartDepth, parsed.Profile.LocalEndDepth), parsed.Profile)
            : new ProfileExtrusionPlanResult(false, null, validation.Diagnostics);
        var report = new
        {
            profile = new
            {
                parsed.Profile.Name, parsed.Profile.PlaneFrame,
                constructionPlane = DescribeConstructionPlane(parsed.Profile.EffectiveConstructionPlane),
                spans = ProfileAuthoringParser.InspectGeometricSpans(source).Spans,
                conceptPaths = ProfileAuthoringParser.InspectConceptPaths(source),
                loops = parsed.Profile.Loops.Count,
                segments = parsed.Profile.Loops.SelectMany(x => x.Segments).Select(x =>
                {
                    var guide = DescribeProfileGuide(x.Provenance.ConceptStableId);
                    return new { x.Name, guide = guide.Name, guideKind = guide.Kind, parentGuide = guide.Parent, stableId = x.Provenance.StableId, derivation = x.Provenance.Derivation, tracedFrom = x.Provenance.TracedFrom, reversed = x.Provenance.Reversed, pipelineIndex = x.Provenance.PipelineIndex, invocationSourceRange = x.Provenance.InvocationSourceRange, geometry = x.Geometry.GetType().Name };
                }),
                validation.IsValid, validation.SignedArea, validation.Diagnostics,
                junctions = DescribeProfileJunctions(parsed.Profile, source, parsed.Profile.Name),
                straightEdgeFillet = DescribeProfileStraightEdgeFillet(parsed.Profile, source, parsed.Profile.Name),
                extrusionHeight = parsed.Height,
                brepPlan = plan.Plan is null ? null : new
                {
                    plan.Plan.StableId, authoritative = plan.Plan.IsAuthoritative,
                    constructionPlane = DescribeConstructionPlane(plan.Plan.Construction.Frame),
                    localDepth = new { start = plan.Plan.Construction.LocalStartDepth, end = plan.Plan.Construction.LocalEndDepth },
                    topology = new { vertices = plan.Plan.Vertices.Count, curves = plan.Plan.Curves.Count, edges = plan.Plan.Edges.Count, loops = plan.Plan.Loops.Count, coedges = plan.Plan.CoedgeCount, surfaces = plan.Plan.Surfaces.Count, faces = plan.Plan.Faces.Count, shells = 1, bodies = 1 },
                    roles = plan.Plan.Faces.Select(x => new { x.StableId, role = x.Role.ToString(), loops = x.LoopIds.Select(id => id.Value), x.SameSense }),
                    correspondence = plan.Plan.Correspondence.Descendants.Select(x => new { x.StableId, role = x.Role.ToString(), x.SourceStableId, edge = x.Edge?.Value, face = x.Face?.Value, loop = x.Loop?.Value }),
                    materializer = "ProfileExtrusionBRepMaterializer",
                    plan.Plan.Provenance,
                    plan.Plan.Diagnostics
                }
            }
        };
        if (json) stdout.WriteLine(JsonSerializer.Serialize(report, JsonOptions)); else stdout.WriteLine($"Profile {parsed.Profile.Name}: {(validation.IsValid ? "valid" : "invalid")}");
        return validation.IsValid ? 0 : 1;
    }

    private static int RunInspectSpans(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0])) { stdout.WriteLine(InspectSpansUsage); return args.Length == 0 ? 1 : 0; }
        if (args.Length != 2 || args[1] != "--json") { stderr.WriteLine(InspectSpansUsage); return 1; }
        if (!File.Exists(args[0])) { stderr.WriteLine($"Span source was not found: {args[0]}"); return 1; }
        var inspection = ProfileAuthoringParser.InspectGeometricSpans(File.ReadAllText(args[0]));
        stdout.WriteLine(JsonSerializer.Serialize(new { command = "inspect-spans", success = inspection.Diagnostics.Count == 0, spans = inspection.Spans, diagnostics = inspection.Diagnostics }, JsonOptions));
        return inspection.Diagnostics.Count == 0 ? 0 : 1;
    }

    private static object DescribeConstructionPlane(ConstructionPlane plane) => new
    {
        plane.StableId, plane.SourceConceptId,
        origin = new[] { plane.Origin.X, plane.Origin.Y, plane.Origin.Z },
        axisX = new[] { plane.AxisX.ToVector().X, plane.AxisX.ToVector().Y, plane.AxisX.ToVector().Z },
        axisY = new[] { plane.AxisY.ToVector().X, plane.AxisY.ToVector().Y, plane.AxisY.ToVector().Z },
        axisZ = new[] { plane.AxisZ.ToVector().X, plane.AxisZ.ToVector().Y, plane.AxisZ.ToVector().Z },
        plane.Handedness, plane.Determinant, plane.SourceSpan, plane.Provenance
    };

    private static (string Name, string Kind, string? Parent) DescribeProfileGuide(string stableId)
    {
        const string prefix = "concept:";
        var path = stableId.StartsWith(prefix, StringComparison.Ordinal) ? stableId[prefix.Length..] : stableId;
        var components = path.Split('.', StringSplitOptions.RemoveEmptyEntries);
        if (components.Length >= 3 && components[^1] is "Top" or "Bottom" or "Left" or "Right")
        {
            return ($"{components[^2]}.{components[^1]}", "Rect2Side", components[^2]);
        }

        return (stableId, "ConceptGuide", null);
    }

    private static int RunInspectSelections(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0])) { stdout.WriteLine(InspectSelectionsUsage); return args.Length == 0 ? 1 : 0; }
        if (args.Length != 2 || args[1] != "--json") { stderr.WriteLine(InspectSelectionsUsage); return 1; }
        if (!File.Exists(args[0])) { stderr.WriteLine($"Selection source was not found: {args[0]}"); return 1; }
        var totalClock = Stopwatch.StartNew();
        var source = File.ReadAllText(args[0]);
        if (PrismaticProfileCompositionParser.IsCompositionSource(source))
        {
            var parsedCompose = PrismaticProfileCompositionParser.Parse(source);
            var stack = PrismaticSectionStackCompiler.Normalize(parsedCompose, out var composeDiagnostics);
            var emittedCompose = stack is null ? null : PrismaticSectionStackEmitter.Emit(stack);
            if (stack is null || emittedCompose is null || emittedCompose.Body is null || emittedCompose.Correspondence is null)
            {
                stderr.WriteLine(string.Join(Environment.NewLine, composeDiagnostics));
                return 1;
            }
            BlindDrillToolCorridorEvidence? corridor = null;
            var bridgeDiagnostics = Array.Empty<string>();
            if ((stack.Feature.ConstructionPlaneBlindDrills?.Count ?? 0) > 0)
            {
                var finalPlan = SectionStackBlindDrillComposeBridge.TryApply(stack, emittedCompose.Plan!, out var bridge, out corridor);
                bridgeDiagnostics = bridge.ToArray();
                if (finalPlan?.TopologyPlan is null) { stderr.WriteLine(string.Join(Environment.NewLine, bridgeDiagnostics)); return 1; }
                var materialized = PrismaticSectionStackBrepMaterializer.TryMaterialize(finalPlan.TopologyPlan);
                if (materialized.Body is null) { stderr.WriteLine(string.Join(Environment.NewLine, materialized.Diagnostics)); return 1; }
                emittedCompose = new PrismaticSectionStackEmissionResult(materialized.Body, finalPlan, emittedCompose.Diagnostics.Concat(bridgeDiagnostics).ToArray(), finalPlan.Correspondence);
            }
            var composeRequests = SemanticSelectionSourceParser.Parse(source, parsedCompose.Profiles.Values.First(), stack.Feature.Name, out var composeParseDiagnostics).ToList();
            if (corridor is not null)
            {
                composeRequests.AddRange([
                    new("inspect:mouth-loop", "MouthLoop", stack.Feature.Name, [corridor.HoleId], SemanticTopologyRole.HoleEntryLoop, SemanticSelectionRequirement.ClosedLoop, "inspect-selections"),
                    new("inspect:shaft-wall-faces", "ShaftWallFaces", stack.Feature.Name, [corridor.HoleId], SemanticTopologyRole.HoleWallFace, SemanticSelectionRequirement.NonEmptyFaceSet, "inspect-selections"),
                    new("inspect:shaft-to-drill-point-loop", "ShaftToDrillPointLoop", stack.Feature.Name, [corridor.HoleId], SemanticTopologyRole.HoleShaftToDrillPointLoop, SemanticSelectionRequirement.ClosedLoop, "inspect-selections"),
                    new("inspect:drill-point-faces", "DrillPointFaces", stack.Feature.Name, [corridor.HoleId], SemanticTopologyRole.HoleDrillPointFace, SemanticSelectionRequirement.NonEmptyFaceSet, "inspect-selections"),
                    new("inspect:tip-vertex", "TipVertex", stack.Feature.Name, [corridor.HoleId], SemanticTopologyRole.HoleTipVertex, SemanticSelectionRequirement.ExactlyOne, "inspect-selections")
                ]);
            }
            if (emittedCompose.Body is not { } composeBody || emittedCompose.Correspondence is not { } composeCorrespondence)
            {
                stderr.WriteLine("Composition materialization did not provide body/correspondence evidence.");
                return 1;
            }
            var composeResults = composeRequests.Select(request => SemanticTopologySelectionResolver.Resolve(composeBody, composeCorrespondence, request)).ToArray();
            var mouthEdges = corridor is null ? [] : composeCorrespondence.Descendants
                .Where(x => x.SourceStableId == corridor.HoleId && x.Role == SemanticTopologyRole.TopBoundary && x.Edge is not null)
                .Select(x => x.Edge!.Value).OrderBy(x => x.Value).ToArray();
            var mouthTopology = corridor is null ? null : new
            {
                MouthOwnership = composeCorrespondence.ProvenanceChain.Contains("MultiFaceCoplanarMouth", StringComparer.Ordinal) ? "MultiFaceCoplanar" : "SingleFace",
                affectedHostFaceIds = emittedCompose.Plan?.TopologyPlan?.FaceMappings.Where(x => x.Kind == "HostFaceReplacement").Select(x => x.FaceId.Value).OrderBy(x => x).ToArray(),
                planningSeam = composeCorrespondence.ProvenanceChain.Contains("ExactLineCircleSplit", StringComparer.Ordinal) ? "section-stack-internal" : null,
                mouthArcDescendants = mouthEdges.Select(x => x.Value),
                intersectionVertices = emittedCompose.Plan?.TopologyPlan?.Topology.Edges.Where(x => mouthEdges.Contains(x.Id)).SelectMany(x => new[] { x.StartVertexId.Value, x.EndVertexId.Value }).Distinct().OrderBy(x => x).ToArray(),
                semanticMouthLoopOrder = composeResults.Where(x => x.Request.Role == SemanticTopologyRole.HoleEntryLoop).SelectMany(x => x.OrderedChain).Select(x => x.StableId),
                noCap = composeCorrespondence.ProvenanceChain.Contains("NoInternalCaps", StringComparer.Ordinal)
            };
            stdout.WriteLine(JsonSerializer.Serialize(new
            {
                body = composeCorrespondence.BodyStableId,
                selections = composeResults.Select(result => new { name = result.Request.Label, stableId = result.Request.StableId, sourceIdentities = result.Request.SourceStableIds, body = result.Request.BodyStableId, expectedShape = result.Request.Require.ToString(), topologyRole = result.Request.Role?.ToString(), succeeded = result.Succeeded, failure = result.Failure.ToString(), connectivity = new { result.IsConnected, result.IsClosed }, traversalOrder = result.OrderedChain.Select(x => x.StableId), materializedDescendants = result.Descendants.Select(x => new { x.StableId, x.Kind, role = x.Role.ToString(), x.SourceStableId, x.ParentStableId }), provenance = composeCorrespondence.ProvenanceChain, consumer = result.Request.Consumer, diagnostics = result.Diagnostics }),
                holeContract = corridor is null ? null : new
                {
                    ValidationPolicy = corridor.ValidationPolicy.ToString(), corridor.HoleId, corridor.HostId, corridor.ConstructionPlaneId,
                    corridor.Radius, corridor.ShaftDepth, corridor.TipLength, corridor.TotalDepth,
                    ClearanceCylinderLength = corridor.TotalDepth,
                    HostTraversalClassification = corridor.Classification.ToString(),
                    RelevantHostSlabs = corridor.ShaftSliceProofs.Select(x => new { z = new[] { x.ZFrom, x.ZTo }, x.Provenance }),
                    ChordProofs = corridor.ShaftSliceProofs.Select(x => new { z = new[] { x.ZFrom, x.ZTo }, axial = new[] { x.AxisFrom, x.AxisTo }, cross = new[] { x.CrossFrom, x.CrossTo }, x.ToolPart, classification = x.Classification.ToString(), x.Detail, x.Provenance }),
                    corridor.RemainingWall,
                    ContractSatisfied = corridor.Classification == BlindDrillToolCorridorClassification.CorridorProven,
                    ConservativeRejection = corridor.Classification == BlindDrillToolCorridorClassification.FullRadiusTipClearanceFailed,
                    diagnostics = corridor.Diagnostics
                },
                mouthTopology,
                arrangement = stack.Slabs.Select(s => new { slab = new[] { s.From, s.To }, fragments = s.Arrangement?.AtomicFragments.Select(f => new { f.StableId, source = f.Source.Provenance.StableId, f.FromParameter, f.ToParameter, f.MaterialOnLeft, f.Retained }) }),
                diagnostics = composeDiagnostics.Concat(composeParseDiagnostics).Concat(bridgeDiagnostics).Distinct()
            }, JsonOptions));
            return composeDiagnostics.Count == 0 && composeParseDiagnostics.Count == 0 && composeResults.All(x => x.Succeeded) ? 0 : 1;
        }
        var parseClock = Stopwatch.StartNew();
        var v2 = FirmamentV2Parser.Parse(source, Path.GetDirectoryName(Path.GetFullPath(args[0])));
        parseClock.Stop();
        if (v2.IsSuccess && v2.Document is not null && v2.Document.ModifyBlocks?.SelectMany(x => x.SemanticHoles).Any() == true)
        {
            var inspectClock = Stopwatch.StartNew();
            var hole = SemanticHoleInspection.Inspect(v2.Document);
            inspectClock.Stop();
            if (!hole.Succeeded || hole.Correspondence is null) { stderr.WriteLine(string.Join(Environment.NewLine, hole.Diagnostics)); return 1; }
            var selectionRequests = new List<SemanticSelectionRequest>
            {
                new("inspect:mouth-loop", "MouthLoop", hole.Correspondence.BodyStableId, [hole.HoleId!], SemanticTopologyRole.HoleEntryLoop, SemanticSelectionRequirement.ClosedLoop, "inspect-selections"),
                new("inspect:shaft-wall-faces", "ShaftWallFaces", hole.Correspondence.BodyStableId, [hole.HoleId!], SemanticTopologyRole.HoleWallFace, SemanticSelectionRequirement.NonEmptyFaceSet, "inspect-selections")
            };
            if (hole.Evidence?.PointAngle is { })
            {
                selectionRequests.Add(new("inspect:shaft-to-drill-point-loop", "ShaftToDrillPointLoop", hole.Correspondence.BodyStableId, [hole.HoleId!], SemanticTopologyRole.HoleShaftToDrillPointLoop, SemanticSelectionRequirement.ClosedLoop, "inspect-selections"));
                selectionRequests.Add(new("inspect:drill-point-faces", "DrillPointFaces", hole.Correspondence.BodyStableId, [hole.HoleId!], SemanticTopologyRole.HoleDrillPointFace, SemanticSelectionRequirement.NonEmptyFaceSet, "inspect-selections"));
                selectionRequests.Add(new("inspect:tip-vertex", "TipVertex", hole.Correspondence.BodyStableId, [hole.HoleId!], SemanticTopologyRole.HoleTipVertex, SemanticSelectionRequirement.ExactlyOne, "inspect-selections"));
            }
            else selectionRequests.Add(new("inspect:exit-loop", "ExitLoop", hole.Correspondence.BodyStableId, [hole.HoleId!], SemanticTopologyRole.HoleExitLoop, SemanticSelectionRequirement.ClosedLoop, "inspect-selections"));
            var selectionResults = selectionRequests.Select(request => SemanticTopologySelectionResolver.Resolve(hole.Body!, hole.Correspondence, request)).ToArray();
            totalClock.Stop();
            stdout.WriteLine(JsonSerializer.Serialize(new
            {
                body = hole.Correspondence.BodyStableId,
                hole = hole.HoleId,
                sourceDeclaration = new { kind = "Hole<Shaft>", featureId = hole.HoleId, sourceSpan = hole.Evidence?.SourceSpan },
                boundPlacement = hole.Evidence is null ? null : new { kind = hole.Evidence.PlacementKind, hole.Evidence.ConstructionPlaneId, hole.Evidence.SourceConceptPlaneId, hole.Evidence.LocalCenter },
                airPlacement = hole.Evidence is null ? null : new { kind = hole.Evidence.PlacementKind == "ConstructionPlane" ? "AirConstructionPlaneHolePlacement" : "AirFaceLocalHolePlacement", featureId = hole.Evidence.FeatureId, hole.Evidence.ConstructionPlaneId, hole.Evidence.LocalCenter },
                stockFrame = hole.Evidence?.StockFrame,
                plan = hole.Evidence?.PlanId is null ? null : new { kind = "LocalFrameHoleBRepPlan", stableId = hole.Evidence.PlanId, hostInterval = hole.Evidence.HostInterval },
                holeContract = hole.Evidence?.Contract is null ? null : new
                {
                    FeatureId = hole.Evidence.FeatureId,
                    DeclaredEndCondition = hole.Evidence.Contract.DeclaredEndCondition,
                    DeclaredTermination = hole.Evidence.Contract.DeclaredTermination,
                    hole.Evidence.ConstructionPlaneId,
                    LocalCenter = hole.Evidence.LocalCenter,
                    WorldMouthCenter = hole.Evidence.WorldMouthCenter,
                    Axis = hole.Evidence.HostTraversal?.Axis,
                    hole.Evidence.Diameter,
                    hole.Evidence.Radius,
                    hole.Evidence.Contract.ShaftDepth,
                    hole.Evidence.Contract.TipLength,
                    hole.Evidence.Contract.TotalDepth,
                    PointAngle = hole.Evidence.PointAngle,
                    HostTraversalClassification = hole.Evidence.HostTraversal?.Classification.ToString(),
                    HostIntervals = hole.Evidence.HostTraversal?.OrderedIntervals,
                    PhysicalMaterialSpan = hole.Evidence.HostTraversal?.PhysicalMaterialSpan,
                    hole.Evidence.Contract.RemainingWall,
                    hole.Evidence.Contract.IsThroughAll,
                    hole.Evidence.Contract.IsBlind,
                    HasExit = hole.Evidence.Contract.HasExit,
                    hole.Evidence.Contract.HasDrillPoint,
                    hole.Evidence.Contract.MouthInsideMaterial,
                    hole.Evidence.Contract.TipInsideMaterial,
                    hole.Evidence.Contract.ContractSatisfied,
                    diagnostics = hole.Evidence.Contract.Diagnostics
                },
                summary = hole.Evidence is null ? null : new
                {
                    hole.Evidence.FeatureId, hole.Evidence.PlacementKind, hole.Evidence.ConstructionPlaneId, hole.Evidence.SourceConceptPlaneId,
                    frameOrigin = hole.Evidence.FrameOrigin, axisX = hole.Evidence.AxisX, axisY = hole.Evidence.AxisY, axisZ = hole.Evidence.AxisZ,
                    localCenter = hole.Evidence.LocalCenter, worldMouthCenter = hole.Evidence.WorldMouthCenter,
                    hole.Evidence.Diameter, hole.Evidence.Radius, extent = hole.Evidence.Extent, endKind = hole.Evidence.Extent, hole.Evidence.DeclaredDepth, hole.Evidence.ShaftDepth, hole.Evidence.TipLength, hole.Evidence.TotalDepth, pointAngle = hole.Evidence.PointAngle,
                    hostInterval = hole.Evidence.HostInterval,
                    hole.Evidence.PlanId, hole.Evidence.SourceSpan
                },
                descendants = hole.Correspondence.Descendants.Select(x => new { x.StableId, x.Kind, role = x.Role.ToString(), x.SourceStableId, x.ParentStableId, edge = x.Edge?.Value, face = x.Face?.Value, loop = x.Loop?.Value }),
                selectionResults = selectionResults.Select(result => new { name = result.Request.Label, stableId = result.Request.StableId, topologyRole = result.Request.Role?.ToString(), expectedShape = result.Request.Require.ToString(), succeeded = result.Succeeded, failure = result.Failure.ToString(), materializedDescendants = result.Descendants.Select(x => x.StableId), diagnostics = result.Diagnostics }),
                provenance = hole.Correspondence.ProvenanceChain,
                diagnostics = hole.Diagnostics,
                timings = new { parseMs = parseClock.Elapsed.TotalMilliseconds, inspectMs = inspectClock.Elapsed.TotalMilliseconds, totalMs = totalClock.Elapsed.TotalMilliseconds }
            }, JsonOptions));
            return 0;
        }
        var parsed = ProfileAuthoringParser.Parse(source);
        if (parsed.Profile is null) { stderr.WriteLine(string.Join(Environment.NewLine, parsed.Diagnostics)); return 1; }
        var emitted = ResolvedProfile2DValidator.Extrude(parsed.Profile, parsed.Height);
        if (emitted.Body is null || emitted.Correspondence is null) { stderr.WriteLine(string.Join(Environment.NewLine, emitted.Diagnostics)); return 1; }
        var requests = SemanticSelectionSourceParser.Parse(source, parsed.Profile, parsed.Profile.Name, out var parseDiagnostics);
        var results = requests.Select(request => SemanticTopologySelectionResolver.Resolve(emitted.Body, emitted.Correspondence, request)).ToArray();
        stdout.WriteLine(JsonSerializer.Serialize(new
        {
            body = emitted.Correspondence.BodyStableId,
            selections = results.Select(result => new
            {
                name = result.Request.Label, stableId = result.Request.StableId, sourceIdentities = result.Request.SourceStableIds,
                body = result.Request.BodyStableId, expectedShape = result.Request.Require.ToString(), topologyRole = result.Request.Role?.ToString(),
                succeeded = result.Succeeded, failure = result.Failure.ToString(), connectivity = new { result.IsConnected, result.IsClosed },
                traversalOrder = result.OrderedChain.Select(x => x.StableId),
                materializedDescendants = result.Descendants.Select(x => new { x.StableId, x.Kind, role = x.Role.ToString(), x.SourceStableId, x.ParentStableId, sourceSpan = result.Request.SourceSpan }),
                provenance = emitted.Correspondence.ProvenanceChain, consumer = result.Request.Consumer,
                diagnostics = result.Diagnostics
            }),
            diagnostics = parseDiagnostics
        }, JsonOptions));
        return parseDiagnostics.Count == 0 && results.All(x => x.Succeeded) ? 0 : 1;
    }

    private static int RunInspectCompose(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0])) { stdout.WriteLine(InspectComposeUsage); return args.Length == 0 ? 1 : 0; }
        var json = args.Skip(1).Any(x => x == "--json");
        var materialize = args.Skip(1).Any(x => x == "--materialize");
        if (!json || args.Skip(1).Any(x => x is not "--json" and not "--materialize")) { stderr.WriteLine(InspectComposeUsage); return 1; }
        if (!File.Exists(args[0])) { stderr.WriteLine($"Composition source was not found: {args[0]}"); return 1; }
        var total = Stopwatch.StartNew();
        var parseClock = Stopwatch.StartNew();
        var source = File.ReadAllText(args[0]);
        if (!FirmamentV2Parser.TryExpandCanonicalStaticAuthoring(source, out var materializerSource, out var staticDiagnostics))
        {
            stderr.WriteLine(string.Join(Environment.NewLine, staticDiagnostics));
            return 1;
        }
        var parsed = PrismaticProfileCompositionParser.Parse(materializerSource);
        parseClock.Stop(); var normalizeClock = Stopwatch.StartNew();
        var stack = PrismaticSectionStackCompiler.Normalize(parsed, out var diagnostics);
        normalizeClock.Stop();
        if (stack is null) { stderr.WriteLine(string.Join(Environment.NewLine, diagnostics)); return 1; }
        PrismaticSectionStackEmissionResult? emitted = null; BrepMassPropertiesResult? mass = null;
        var materializeClock = TimeSpan.Zero;
        if (materialize) { var clock = Stopwatch.StartNew(); emitted = PrismaticSectionStackEmitter.Emit(stack); mass = emitted.Body is null ? null : BrepMassProperties.Evaluate(emitted.Body); clock.Stop(); materializeClock = clock.Elapsed; }
        total.Stop();
        var report = new
        {
            composition = new
            {
                name = stack.Feature.Name, frame = stack.Feature.Frame, axis = stack.Feature.Axis,
                placement = new { stack.Feature.Placement.Name, anchor = new[] { stack.Feature.Placement.AnchorX, stack.Feature.Placement.AnchorY, stack.Feature.Placement.AnchorZ }, profilePlane = stack.Feature.Placement.ProfilePlane, stack.Feature.Placement.Axis, stack.Feature.Placement.ReferenceDirection, stack.Feature.Placement.IsExplicit },
                signatures = new { composition = CompositionSignature(stack), profiles = parsed.Profiles.OrderBy(x => x.Key, StringComparer.Ordinal).ToDictionary(x => x.Key, x => ProfileSignature(x.Value), StringComparer.Ordinal) },
                operations = stack.Feature.Operations.Select(x => new { x.Name, intent = x.Intent.ToString(), profile = x.ProfileReference, x.From, x.To, x.SemanticRole, x.SourceSpan, x.SemanticFeatureId, x.SemanticFeatureKind, x.Diameter, signature = Hash($"{x.Intent}|{x.ProfileReference}|{x.From:R}|{x.To:R}|{x.SemanticRole}|{x.SemanticFeatureId}|{x.Diameter:R}") }),
                shaftHoles = (stack.Feature.ShaftHoles ?? []).Select(x => new { x.Name, x.StableId, profile = x.ProfileReference, center = new[] { x.CenterX, x.CenterY }, x.Diameter, x.From, x.To, endCondition = "ThroughAll", x.SemanticRole, x.SourceSpan, support = x.SupportSpan is null ? null : new { kind = "Span<Plane>", id = x.SupportSpan, parent = x.ParentSupport, boundaryMargin = x.SupportBoundaryMargin } }),
                counterboreHoles = (stack.Feature.CounterboreHoles ?? []).Select(x => new { x.Name, x.StableId, shaftProfile = x.ShaftProfileReference, counterboreProfile = x.CounterboreProfileReference, center = new[] { x.CenterX, x.CenterY }, x.Diameter, x.CounterboreDiameter, x.CounterboreDepth, x.From, x.To, endCondition = "ThroughAll", x.SemanticRole, x.SourceSpan, support = x.SupportSpan is null ? null : new { kind = "Span<Plane>", id = x.SupportSpan, parent = x.ParentSupport, boundaryMargin = x.SupportBoundaryMargin } }),
                bosses = (stack.Feature.Bosses ?? []).Select(x => new { x.Name, x.StableId, host = x.Host, on = x.SupportFace, profile = x.ProfileReference, x.Height, x.From, x.To, support = x.SupportSpan is null ? null : new { kind = "Span<Plane>", id = x.SupportSpan, parent = x.ParentSupport }, materialEffect = "Add", lowering = "PrismaticSectionStack/Add" }),
                pockets = (stack.Feature.Pockets ?? []).Select(x => new { x.Name, x.StableId, host = x.Host, on = x.SupportFace, profile = x.ProfileReference, x.Depth, x.HostThickness, x.RemainingFloor, x.MinimumFloorThickness, x.MinimumFloorPolicySource, x.From, x.To, support = x.SupportSpan is null ? null : new { kind = "Span<Plane>", id = x.SupportSpan, parent = x.ParentSupport }, materialEffect = "Remove", lowering = "PrismaticSectionStack/Remove" }),
                capsuleSlots = (stack.Feature.CapsuleSlots ?? []).Select(x => new { x.Name, x.StableId, kind = "Slot<Capsule>", profile = x.ProfileReference, center = new[] { x.CenterX, x.CenterY }, direction = new[] { x.DirectionX, x.DirectionY }, x.Length, x.Width, radius = x.Radius, straightSpan = x.StraightSpan, endCenters = new[] { new[] { x.CenterX - x.DirectionX * x.StraightSpan / 2d, x.CenterY - x.DirectionY * x.StraightSpan / 2d }, new[] { x.CenterX + x.DirectionX * x.StraightSpan / 2d, x.CenterY + x.DirectionY * x.StraightSpan / 2d } }, x.From, x.To, x.Extent, x.SemanticRole, x.SourceSpan, segments = parsed.Profiles[x.ProfileReference].Loops.Single().Segments.Select(s => s.Name) }),
                roundedRectangleSlots = (stack.Feature.RoundedRectangleSlots ?? []).Select(x => new { x.Name, x.StableId, kind = "Slot<RoundedRectangle>", profile = x.ProfileReference, center = new[] { x.CenterX, x.CenterY }, direction = new[] { x.DirectionX, x.DirectionY }, x.Length, x.Width, x.CornerRadius, x.From, x.To, x.Extent, x.SemanticRole, x.SourceSpan, segments = parsed.Profiles[x.ProfileReference].Loops.Single().Segments.Select(s => s.Name) }),
                criticalLevels = stack.Feature.CriticalLevels,
                slabs = stack.Slabs.Select(x => new
                {
                    x.From,
                    x.To,
                    x.ActiveOperations,
                    area = x.MaterialRegions.Sum(PrismaticSectionStackCompiler.Area), signature = ProfileSignature(x.Region.Outer),
                    outerLoops = x.MaterialRegions.Count,
                    innerLoops = x.MaterialRegions.Sum(r => r.Holes.Count),
                    regions = x.MaterialRegions.Select((region, index) => new { index, area = PrismaticSectionStackCompiler.Area(region), signature = ProfileSignature(region.Outer), innerLoops = region.Holes.Count, region.Provenance }),
                    loops = x.MaterialRegions.SelectMany(region => new[]
                    {
                        new { role = "Outer", signedAreaInProfileFrame = PrismaticSectionStackCompiler.ProfileArea(region.Outer), sourceWinding = PrismaticSectionStackCompiler.ProfileArea(region.Outer) >= 0d ? "CounterClockwise" : "Clockwise", materialFacingWinding = "CounterClockwise" }
                    }.Concat(region.Holes.Select(h => new { role = "Inner", signedAreaInProfileFrame = PrismaticSectionStackCompiler.ProfileArea(h), sourceWinding = PrismaticSectionStackCompiler.ProfileArea(h) >= 0d ? "CounterClockwise" : "Clockwise", materialFacingWinding = "Clockwise" }))),
                    lineSegments = x.MaterialRegions.Sum(r => r.Outer.Loops[0].Segments.Count(s => s.Geometry is LineArcLineSegment2D)),
                    arcSegments = x.MaterialRegions.Sum(r => r.Outer.Loops[0].Segments.Count(s => s.Geometry is LineArcCircularArc2D))
                    , arrangement = x.Arrangement is null ? null : new
                    {
                        sourceSegmentCount = x.Arrangement.SourceCurves.Count,
                        intersectionVertexCount = x.Arrangement.IntersectionVertices.Count,
                        atomicFragmentCount = x.Arrangement.AtomicFragments.Count,
                        coincidentFragmentCount = x.Arrangement.CoincidentFragmentCount,
                        retainedBoundaryFragmentCount = x.Arrangement.RetainedBoundaryFragmentCount,
                        resultLoopCount = x.Arrangement.ResultLoops.Count,
                        perimeter = x.Arrangement.ResultLoops.Sum(loop => loop.Perimeter),
                        timingsMilliseconds = new { intersections = x.Arrangement.IntersectionTime.TotalMilliseconds, splitting = x.Arrangement.SplitTime.TotalMilliseconds, classification = x.Arrangement.ClassificationTime.TotalMilliseconds, reconstruction = x.Arrangement.ReconstructionTime.TotalMilliseconds },
                        provenance = x.MaterialRegions.SelectMany(r => r.Provenance).Distinct().Order(StringComparer.Ordinal),
                        diagnostics = x.Arrangement.Diagnostics
                    }
                }),
                transitions = stack.Transitions.Select(x => new { x.Level, upwardRegionCount = x.UpwardRegions.Count, downwardRegionCount = x.DownwardRegions.Count, upwardArea = x.UpwardRegions.Sum(PrismaticSectionStackCompiler.Area), downwardArea = x.DownwardRegions.Sum(PrismaticSectionStackCompiler.Area) }),
                analyticVolume = stack.AnalyticVolume,
                materialization = materialize ? new
                {
                    bRepStatus = mass?.Status.ToString(),
                    bRepVolume = mass?.AbsoluteVolume,
                    volumeDelta = mass is null ? (double?)null : mass.AbsoluteVolume - stack.AnalyticVolume,
                    bRepErrorBound = mass?.ErrorBound,
                    bRepEnclosed = mass?.IsEnclosed,
                    bRepDiagnostics = mass?.Diagnostics,
                    // The construction topology plan contains dictionaries keyed by
                    // internal ID value objects.  Expose its public contract rather
                    // than leaking an unserializable implementation graph.
                    bRepPlan = emitted?.Plan is { } plan ? new
                    {
                        plan.Signature,
                        plan.Vertices,
                        plan.Edges,
                        plan.Faces,
                        plan.Policy,
                        plan.Authoritative,
                        correspondence = plan.Correspondence is { } correspondence ? new
                        {
                            correspondence.BodyStableId,
                            descendantCount = correspondence.Descendants.Count,
                            correspondence.ProvenanceChain
                        } : null
                    } : null
                } : null,
                expansion = parsed.Expansion,
                timingsMilliseconds = new { parse = parseClock.Elapsed.TotalMilliseconds, normalize = normalizeClock.Elapsed.TotalMilliseconds, materialize = materializeClock.TotalMilliseconds, total = total.Elapsed.TotalMilliseconds },
                executionBoundary = new { inspectionOnly = !materialize, bRepMaterialized = materialize, stepExported = false, m8Executed = false, cirExecuted = false },
                diagnostics = staticDiagnostics.Concat(emitted?.Diagnostics ?? stack.Diagnostics).Distinct()
            }
        };
        stdout.WriteLine(JsonSerializer.Serialize(report, JsonOptions));
        return 0;
    }

    private static string? ExpandSweepInspectionSource(string source, out IReadOnlyList<string> diagnostics)
    {
        var expansion = FirmamentTemplateSourceCompiler.Expand(source, out var templateDiagnostics);
        if (expansion is null)
        {
            diagnostics = templateDiagnostics;
            return null;
        }

        if (!FirmamentV2Parser.TryExpandCanonicalStaticAuthoring(expansion.ExpandedSource, out var expandedSource, out var staticDiagnostics))
        {
            diagnostics = templateDiagnostics.Concat(staticDiagnostics).Distinct(StringComparer.Ordinal).ToArray();
            return null;
        }

        diagnostics = templateDiagnostics.Concat(staticDiagnostics).Distinct(StringComparer.Ordinal).ToArray();
        return FirmamentV2Parser.TryGetCanonicalAdvancedBody(expandedSource, out var canonicalBody)
            ? canonicalBody
            : expandedSource;
    }

    private static int RunValidate(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0)
        {
            stderr.WriteLine(ValidateUsage);
            return 1;
        }

        if (IsHelpFlag(args[0]))
        {
            WriteValidateHelp(stdout);
            return 0;
        }

        var sourcePath = args[0];
        var json = false;
        var explain = false;
        var parseOnly = false;
        var locked = false;
        var shadow = false;
        var shadowAst = false;
        var forgePackPaths = new List<string>();
        for (var i = 1; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--forge-pack" when i + 1 < args.Length:
                    forgePackPaths.Add(args[++i]);
                    break;
                case "--forge-pack":
                    stderr.WriteLine("Validate option --forge-pack requires a local assembly path.");
                    stderr.WriteLine(ValidateUsage);
                    return 1;
                case "--explain":
                    explain = true;
                    break;
                case "--shadow":
                    shadow = true;
                    break;
                case "--ast":
                    shadowAst = true;
                    break;
                case "--parse-only":
                    parseOnly = true;
                    break;
                case "--locked":
                    locked = true;
                    break;
                case "--json":
                    json = true;
                    break;
                case "-h":
                case "--help":
                    WriteValidateHelp(stdout);
                    return 0;
                default:
                    stderr.WriteLine($"Unknown validate option '{args[i]}'.");
                    stderr.WriteLine(ValidateUsage);
                    return 1;
            }
        }

        if (!File.Exists(sourcePath))
        {
            stderr.WriteLine($"Validation input was not found: {sourcePath}");
            return 1;
        }

        if (shadowAst && !shadow) { stderr.WriteLine("--ast requires --shadow."); return 1; }
        if (!DependencyLockCommand.Verify(sourcePath, locked, json, stdout, stderr, JsonOptions, "validate")) return 1;
        if (shadow)
        {
            if (forgePackPaths.Count > 0 || parseOnly) { stderr.WriteLine("--shadow uses normal production validation; --forge-pack/--parse-only are not supported together with it."); return 1; }
            return FrontendShadowCommand.Run([sourcePath, "--validate", .. (json ? new[] { "--json" } : []), .. (shadowAst ? new[] { "--ast" } : [])], stdout, stderr);
        }
        int RejectParseOnly(string domain)
        {
            var diagnostic = new FirmamentV2ValidationDiagnostic("firmament-validation-option-unsupported", "error",
                $"{domain} has no static-only admission path. Omit --parse-only to run its actual validator; no engineering validation was performed.")
                { SourceFile = Path.GetFullPath(sourcePath), Stage = "Validation options" };
            var payload = new { source = sourcePath, status = "not-validated", domain, validationLevel = "NotValidated", diagnostics = new[] { diagnostic } };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));
            else stderr.WriteLine($"{diagnostic.SourceFile}: {diagnostic.Severity} {diagnostic.Code}: {diagnostic.Message}");
            return 1;
        }
        var validationSource=File.ReadAllText(sourcePath);
        var authoredValidationSource = validationSource;
        var frontend = FirmamentFrontendSchemas.Select(validationSource);
        if (!frontend.IsSuccess) return WriteFrontendRejection(frontend, validationSource, sourcePath, "validate", json, stdout, stderr);
        validationSource = frontend.Source;
        var domain = FirmamentCommandRouting.Select(validationSource, sourcePath, frontend.Schema);
        if(domain == FirmamentCommandDomain.Drawing)
        {
            if (parseOnly) return RejectParseOnly("Drawing");
            var output=Path.GetFullPath(Path.Combine("artifacts","local","drawing-validation",Guid.NewGuid().ToString("N")));
            try
            {
                var drawing=FirmamentDrawingCompiler.Compile(sourcePath,output);
                var diagnostics=drawing.KernelDiagnostics().Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,validationSource)).ToArray();
                var payload=new {source=sourcePath,status=drawing.IsSuccess?"valid":"invalid",domain="Drawing",validationLevel=drawing.IsSuccess?"Built":"BuildRejected",parserRoute="UnifiedDrawing",diagnostics};
                if(json)stdout.WriteLine(JsonSerializer.Serialize(new {firmamentV2Validation=payload},JsonOptions));
                else {stdout.WriteLine(drawing.IsSuccess?"Drawing admitted.":"Drawing rejected.");foreach(var d in diagnostics)stderr.WriteLine($"{d.SourceFile}:{d.Line}:{d.Column}: {d.Severity} {d.Code}: {d.Message}");}
                return drawing.IsSuccess?0:1;
            }
            finally {if(Directory.Exists(output))Directory.Delete(output,true);}
        }
        if (domain == FirmamentCommandDomain.Analysis)
        {
            if (parseOnly) return RejectParseOnly("Analysis");
            var analysis=FirmamentAnalysisCompiler.Compile(frontend.Source,Path.GetFullPath(sourcePath),Path.GetDirectoryName(Path.GetFullPath(sourcePath)));
            var diagnostics=FirmamentAnalysisCompiler.KernelDiagnostics(analysis).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,validationSource)).ToArray();
            var payload=new {source=sourcePath,status=analysis.IsSuccess?"bound-not-solved":"invalid",domain="Analysis",validationLevel=analysis.IsSuccess?"BoundNotSolved":"BindingRejected",parserRoute="UnifiedAnalysis",diagnostics};
            if(json)stdout.WriteLine(JsonSerializer.Serialize(new {firmamentV2Validation=payload},JsonOptions));
            else {stdout.WriteLine(analysis.IsSuccess?"Analysis bound; solver execution has not been validated.":"Analysis rejected.");foreach(var d in diagnostics)stderr.WriteLine($"{d.SourceFile}:{d.Line}:{d.Column}: {d.Severity} {d.Code}: {d.Message}");}
            return analysis.IsSuccess?0:1;
        }
        if (domain == FirmamentCommandDomain.Garment
            || frontend.Schema == FirmamentFrontendSchema.Garment)
        {
            if (parseOnly)
            {
                var garment = Aetheris.Kernel.Firmament.Garment.GarmentAuthoring.Parse(authoredValidationSource, Path.GetFullPath(sourcePath));
                var diagnostics = garment.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(new KernelDiagnostic(
                    KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, d.Code + ": " + d.Message, "Firmament.Garment"), sourcePath, validationSource)).ToArray();
                var payload = new { source = sourcePath, status = garment.IsSuccess ? "parsed-not-built" : "invalid", domain = "Garment",
                    validationLevel = garment.IsSuccess ? "ParsedNotBuilt" : "BindingRejected", parserRoute = "UnifiedGarment", diagnostics };
                if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));
                else { stdout.WriteLine("Garment static analysis: " + payload.status); WriteFrontendDiagnostics(diagnostics, stderr); }
                return garment.IsSuccess ? 0 : 1;
            }
            return GarmentCommand.Run(["inspect", sourcePath, .. (json ? new[] { "--json" } : Array.Empty<string>())], stdout, stderr);
        }
        if (domain == FirmamentCommandDomain.Assembly)
        {
            var sheetMetalAssembly = validationSource.Contains("Use SheetMetal.ProductFamilies", StringComparison.Ordinal);
            var parsedAssembly = parseOnly ? sheetMetalAssembly
                ? new AssemblyM0Parser().Parse(SheetMetalFirmament.ResolveImports(validationSource),Path.GetFullPath(sourcePath))
                : new AssemblyM0Parser().ParseFile(sourcePath) : null;
            var builtAssembly = parseOnly ? null : sheetMetalAssembly
                ? EnclosureProductFamilies.CompileAssemblyFile(sourcePath) : new AssemblyM1Pipeline().CompileFile(sourcePath);
            var validAssembly = parsedAssembly?.IsSuccess ?? builtAssembly!.IsSuccess;
            var payload = new { success=validAssembly, domain="Assembly", validationLevel=!validAssembly ? "BuildRejected" : parseOnly ? "ParsedNotBuilt" : "Built",
                diagnostics=parsedAssembly?.Diagnostics ?? builtAssembly!.Diagnostics };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(payload,JsonOptions));
            else { stdout.WriteLine(validAssembly ? "Assembly admitted." : "Assembly rejected."); foreach(var d in payload.diagnostics) stderr.WriteLine(d.Code+": "+d.Message); }
            return validAssembly ? 0 : 1;
        }
        if (domain == FirmamentCommandDomain.Scene)
        {
            using var sceneSession = new Aetheris.Kernel.Firmament.Scene.FirmamentSceneSession();
            var parsedScene = parseOnly ? Aetheris.Kernel.Firmament.Scene.SceneAuthoring.Parse(validationSource,Path.GetFullPath(sourcePath)) : null;
            var scene = parseOnly ? null : sceneSession.CompileFile(sourcePath);
            var sceneValid=parsedScene?.IsSuccess ?? scene!.IsSuccess;
            var payload = new { success=sceneValid, domain="Scene", validationLevel=!sceneValid ? "BuildRejected" : parseOnly ? "ParsedNotBuilt" : "Built", diagnostics=parsedScene?.Diagnostics ?? scene!.Diagnostics };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(payload,JsonOptions));
            else { stdout.WriteLine(sceneValid ? "Scene admitted." : "Scene rejected."); foreach(var d in payload.diagnostics) stderr.WriteLine(d.Code+": "+d.Message); }
            return sceneValid ? 0 : 1;
        }
        validationSource = frontend.Source;
        if (domain == FirmamentCommandDomain.Mold)
        {
            if (parseOnly) return RejectParseOnly("Mold");
            var mold = MoldFirmament.Compile(validationSource, Path.GetFullPath(sourcePath));
            var payload = new { source = sourcePath, status = mold.IsSuccess ? "valid" : "invalid", domain = "Mold", validationLevel = mold.IsSuccess ? "Built" : "BuildRejected",
                summary = new { fatalDiagnosticCount = mold.Diagnostics.Count(x => x.Severity == PlasticDiagnosticSeverity.Error), warningDiagnosticCount = mold.Diagnostics.Count(x => x.Severity == PlasticDiagnosticSeverity.Warning), mold.Report?.Summary },
                diagnostics = mold.Diagnostics };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { moldValidation = payload }, JsonOptions));
            else { stdout.WriteLine($"Mold validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, {payload.summary.warningDiagnosticCount} warning)"); foreach (var d in mold.Diagnostics) stderr.WriteLine($"{d.Severity.ToString().ToLowerInvariant()} {d.Code}: {d.Message}"); }
            return mold.IsSuccess ? 0 : 1;
        }
        if (domain == FirmamentCommandDomain.PlasticShell)
        {
            if (parseOnly) return RejectParseOnly("PlasticShell");
            var plastic = PlasticShellFirmament.Compile(validationSource, Path.GetFullPath(sourcePath));
            var payload = new { source = sourcePath, status = plastic.IsSuccess ? "valid" : "invalid", domain = "PlasticShell", validationLevel = plastic.IsSuccess ? "Built" : "BuildRejected", parserRoute = "UnifiedPlasticShell", summary = new { fatalDiagnosticCount = plastic.Diagnostics.Count(x => x.Severity == PlasticDiagnosticSeverity.Error), warningDiagnosticCount = plastic.Diagnostics.Count(x => x.Severity == PlasticDiagnosticSeverity.Warning), gates = plastic.Intent?.Gates.Count ?? 0, standoffs = plastic.Intent?.Standoffs.Count ?? 0, ejectors = plastic.Intent?.Ejectors.Count ?? 0, ribCandidates = plastic.State?.Evidence.RibNetwork?.Candidates.Count ?? 0 }, diagnostics = PlasticShellFirmament.KernelDiagnostics(plastic).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,authoredValidationSource)).ToArray() };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { plasticShellValidation = payload }, JsonOptions));
            else {stdout.WriteLine($"PlasticShell validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, {payload.summary.warningDiagnosticCount} warning)");WriteFrontendDiagnostics(payload.diagnostics,stderr);}
            return plastic.IsSuccess ? 0 : 1;
        }
        if (domain == FirmamentCommandDomain.Sculpting)
        {
            if (parseOnly) return RejectParseOnly("Sculpting");
            var sculpt = SculptingAuthoring.Compile(validationSource,Path.GetFullPath(sourcePath));
            var payload = new { source = sourcePath, status = sculpt.IsSuccess ? "valid" : "invalid", domain = "Sculpting", validationLevel=sculpt.IsSuccess?(sculpt.OutputMesh is null?"Built":"MeshBuilt"):"BuildRejected", artifactKind=sculpt.OutputMesh?.ArtifactKind ?? "BRep", stepExportAvailable=sculpt.OutputMesh is null, parserRoute="UnifiedSculpting", summary = new { fatalDiagnosticCount = sculpt.Diagnostics.Count, warningDiagnosticCount = 0, states = sculpt.States.Count + sculpt.MeshStates.Count }, diagnostics = SculptingAuthoring.KernelDiagnostics(sculpt).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,authoredValidationSource)).ToArray() };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));
            else {stdout.WriteLine($"Firmament V2 Sculpting validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");WriteFrontendDiagnostics(payload.diagnostics,stderr);}
            return sculpt.IsSuccess ? 0 : 1;
        }
        if (domain == FirmamentCommandDomain.Plateau)
        {
            if (parseOnly) return RejectParseOnly("Plateau");
            var plateau = FirmamentBuildAndExport.CompileSource(validationSource, Path.GetDirectoryName(Path.GetFullPath(sourcePath)));
            var payload = new { source = sourcePath, status = plateau.IsSuccess ? "valid" : "invalid", domain = "Plateau", diagnostics = plateau.Diagnostics };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));
            else stdout.WriteLine($"Plateau validation: {payload.status}");
            return plateau.IsSuccess ? 0 : 1;
        }
        if (domain == FirmamentCommandDomain.Piping)
        {
            if (parseOnly) return RejectParseOnly("Piping");
            var piping = PipingAuthoring.Compile(validationSource, Path.GetFullPath(sourcePath));
            var payload = new { source = sourcePath, status = piping.IsSuccess ? "valid" : "invalid", domain = "Piping", validationLevel = piping.IsSuccess ? "Built" : "BuildRejected", parserRoute = "UnifiedPiping", summary = new { fatalDiagnosticCount = piping.Diagnostics.Count, warningDiagnosticCount = 0, connections = piping.Report?.Connections.Count ?? 0, routes = piping.Report?.Routes.Count ?? 0 }, diagnostics = piping.KernelDiagnostics().Select(d => FirmamentBuildAdmissionValidation.Present(d, Path.GetFullPath(sourcePath), validationSource)).ToArray() };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));
            else
            {
                stdout.WriteLine($"Firmament V2 Piping validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");
                foreach (var d in payload.diagnostics) stderr.WriteLine($"{d.SourceFile}:{d.Line}:{d.Column}: {d.Severity} {d.Code}: {d.Message}");
            }
            return piping.IsSuccess ? 0 : 1;
        }
        if (domain == FirmamentCommandDomain.Structural)
        {
            if (parseOnly)
            {
                var diagnostics = StructuralAuthoring.Analyze(validationSource, Path.GetFullPath(sourcePath))
                    .Select(d => FirmamentBuildAdmissionValidation.Present(d, sourcePath, validationSource)).ToArray();
                var accepted = diagnostics.All(d => d.Severity is not ("error" or "fatal"));
                var staticReport = new { source = sourcePath, status = accepted ? "parsed-not-built" : "invalid", domain = "Structural",
                    validationLevel = accepted ? "ParsedNotBuilt" : "BindingRejected", parserRoute = "UnifiedStructural", diagnostics };
                if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = staticReport }, JsonOptions));
                else { stdout.WriteLine("Structural static analysis: " + staticReport.status); WriteFrontendDiagnostics(diagnostics, stderr); }
                return accepted ? 0 : 1;
            }
            var structural = StructuralAuthoring.Compile(validationSource, Path.GetFullPath(sourcePath));
            var payload = new { source = sourcePath, status = structural.IsSuccess ? "valid" : "invalid", domain = "Structural", validationLevel=structural.IsSuccess?"Built":"BuildRejected", parserRoute="UnifiedStructural", summary = new { fatalDiagnosticCount = structural.Diagnostics.Count, warningDiagnosticCount = 0, members = structural.Report?.Members.Count ?? 0, joints = structural.Report?.Joints.Count ?? 0 }, diagnostics = structural.KernelDiagnostics().Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,authoredValidationSource)).ToArray() };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));
            else {stdout.WriteLine($"Firmament V2 Structural validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");WriteFrontendDiagnostics(payload.diagnostics,stderr);}
            return structural.IsSuccess ? 0 : 1;
        }
        if (domain == FirmamentCommandDomain.SectionChain)
        {
            var section = SectionChainAuthoringParser.CompileFile(sourcePath, materialize: !parseOnly);
            var diagnostics = section.Diagnostics.Select(message => FirmamentBuildAdmissionValidation.Present(new KernelDiagnostic(
                KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, "Firmament.SectionChain"), sourcePath, validationSource)).ToArray();
            var payload = new { source = sourcePath, status = section.IsSuccess ? (parseOnly ? "parsed-not-built" : "valid") : "invalid", domain = "SectionChain",
                validationLevel = section.IsSuccess ? (parseOnly ? "ParsedNotBuilt" : "Built") : "BuildRejected", parserRoute = "UnifiedSectionChain",
                summary = new { fatalDiagnosticCount = diagnostics.Length, warningDiagnosticCount = 0, sections = section.Chain?.Sections.Count ?? 0 }, diagnostics };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));
            else stdout.WriteLine($"Firmament V2 SectionChain validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");
            return section.IsSuccess ? 0 : 1;
        }
        if (domain == FirmamentCommandDomain.WireForm)
        {
            var wireSource = ExpandSweepInspectionSource(validationSource, out var expansionDiagnostics);
            var authored = wireSource is null ? null : WireFormAuthoring.Parse(wireSource);
            var wireFailures = expansionDiagnostics.Concat(authored is null ? [] : authored.IsSuccess ? WireFormBRepMaterializer.Validate(authored.Value) : authored.Diagnostics.Select(item => item.Message)).ToList();
            var valid = authored?.IsSuccess == true && wireFailures.Count == 0;
            if (valid && !parseOnly)
            {
                var compilation = FirmamentBuildAndExport.CompileSource(validationSource, Path.GetDirectoryName(Path.GetFullPath(sourcePath)));
                valid = compilation.IsSuccess;
                if (!valid) wireFailures.AddRange(compilation.Diagnostics.Select(d => d.Message));
            }
            var diagnostics = wireFailures.Select(message => FirmamentBuildAdmissionValidation.Present(new KernelDiagnostic(
                KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, "Firmament.WireForm"), sourcePath, validationSource)).ToArray();
            var payload = new { source = sourcePath, status = valid ? (parseOnly ? "parsed-not-built" : "valid") : "invalid", domain = "WireForm",
                validationLevel = valid ? (parseOnly ? "ParsedNotBuilt" : "Built") : "BuildRejected",
                summary = new { fatalDiagnosticCount = diagnostics.Length, warningDiagnosticCount = 0, operationCount = authored?.IsSuccess == true ? authored.Value.Operations.Count : 0 }, diagnostics };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));
            else
            {
                stdout.WriteLine($"Firmament V2 WireForm validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");
                foreach (var diagnostic in diagnostics)
                    stdout.WriteLine($"{diagnostic.SourceFile}:{diagnostic.Line}:{diagnostic.Column} {diagnostic.Severity} {diagnostic.Code}: {diagnostic.Message}");
            }
            return valid ? 0 : 1;
        }
        if (domain == FirmamentCommandDomain.Sweep)
        {
            var sweepSource = ExpandSweepInspectionSource(validationSource, out var sweepExpansionDiagnostics);
            var authored = sweepSource is null ? null : CircularSweepAuthoring.Parse(sweepSource);
            var sweepFailures = sweepExpansionDiagnostics.Concat(authored is null ? [] : authored.IsSuccess ? CircularSweepBRepMaterializer.Validate(authored.Value) : authored.Diagnostics.Select(item => item.Message)).ToList();
            var valid = authored?.IsSuccess == true && sweepFailures.Count == 0;
            if (valid && !parseOnly)
            {
                var compilation = FirmamentBuildAndExport.CompileSource(validationSource, Path.GetDirectoryName(Path.GetFullPath(sourcePath)));
                valid = compilation.IsSuccess;
                if (!valid) sweepFailures.AddRange(compilation.Diagnostics.Select(d => d.Message));
            }
            var sweepDiagnostics = sweepFailures.Select(message => FirmamentBuildAdmissionValidation.Present(new KernelDiagnostic(
                KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, "Firmament.Sweep"), sourcePath, validationSource)).ToArray();
            var payload = new { source = sourcePath, status = valid ? (parseOnly ? "parsed-not-built" : "valid") : "invalid", domain = "CircularSweep",
                validationLevel = valid ? (parseOnly ? "ParsedNotBuilt" : "Built") : "BuildRejected", parserRoute = "UnifiedSweep",
                summary = new { fatalDiagnosticCount = sweepDiagnostics.Length, warningDiagnosticCount = 0,
                    segmentCount = authored?.IsSuccess == true ? authored.Value.Path.Segments.Count : 0 }, diagnostics = sweepDiagnostics };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));
            else
            {
                stdout.WriteLine($"Firmament V2 Circular Sweep validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");
                foreach (var diagnostic in sweepDiagnostics)
                    stdout.WriteLine($"{diagnostic.SourceFile}:{diagnostic.Line}:{diagnostic.Column} {diagnostic.Severity} {diagnostic.Code}: {diagnostic.Message}");
            }
            return valid ? 0 : 1;
        }
        if(domain == FirmamentCommandDomain.SheetMetal)
        {
            var sheet=SheetMetalFirmament.Compile(validationSource,Path.GetFullPath(sourcePath));
            var status=sheet.IsSuccess?"valid":"invalid";
            var payload=new
            {
                source=sourcePath,status,domain="SheetMetal",
                summary=new{fatalDiagnosticCount=sheet.Diagnostics.Count(x=>x.Severity==SheetMetalDiagnosticSeverity.Error),warningDiagnosticCount=sheet.Diagnostics.Count(x=>x.Severity==SheetMetalDiagnosticSeverity.Warning),regions=sheet.Part?.Regions.Count??0,bends=sheet.Part?.Bends.Count??0,features=sheet.Part?.Features.Count??0,exactBlank=sheet.FlatPattern?.ExactBlankContour is not null},
                diagnostics=sheet.Diagnostics
            };
            if(json)stdout.WriteLine(JsonSerializer.Serialize(new{sheetMetalValidation=payload},JsonOptions));
            else
            {
                stdout.WriteLine($"Sheet Metal validation: {status} ({payload.summary.fatalDiagnosticCount} fatal, {payload.summary.warningDiagnosticCount} warning)");
                WriteSheetMetalDiagnostics(sheet.Diagnostics,stderr);
            }
            return sheet.IsSuccess?0:1;
        }

        var library = FirmamentStandardLibraryResolver.Resolve(validationSource, out var libraryDiagnostics);
        if (library is null)
        {
            var payload = new
            {
                Source = sourcePath,
                Status = "invalid",
                Summary = new { FatalDiagnosticCount = libraryDiagnostics.Count, WarningDiagnosticCount = 0 },
                Diagnostics = libraryDiagnostics
            };
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));
            else stdout.WriteLine($"Firmament V2 validation: invalid ({libraryDiagnostics.Count} fatal, 0 warning)");
            return 1;
        }

        var runtimeConfiguration = CreateValidateForgeRuntimeConfiguration(forgePackPaths);
        var parse = FirmamentV2Parser.Parse(
            library.Source,
            Path.GetDirectoryName(Path.GetFullPath(sourcePath)),
            runtimeConfiguration.Catalog, frontend.Schema);
        var runtimeValidation = FirmamentV2RuntimeConceptValidation.Validate(parse.Document, runtimeConfiguration);
        var report = FirmamentV2ValidationReportBuilder.Build(parse, sourcePath, runtimeValidation, runtimeConfiguration.Catalog, validationSource);
        if (parseOnly || forgePackPaths.Count > 0)
        {
            if (report.Status != "invalid") report = report with { Status = "parsed-not-built" };
        }
        else report = FirmamentBuildAdmissionValidation.Admit(report, authoredValidationSource, Path.GetDirectoryName(Path.GetFullPath(sourcePath)));
        if (json && explain) stdout.WriteLine(JsonSerializer.Serialize(new
        {
            firmamentV2Validation = report,
            frontendSemantics = new
            {
                featureOwner = "UnifiedAstFeature",
                featureExpansion = parse.Document?.FeatureExpansion,
                featureDefinitions = parse.Document?.FeatureDefinitions,
                featureInvocations = parse.Document?.FeatureInvocations,
                patternOwner = "CanonicalStaticAuthoring (AST mapping; source catalog adapter)",
                patterns = parse.Document?.StaticAuthoring?.Patterns,
                templateOwner = "UnifiedAstTemplate (lexical binding; Record/Match/body source adapters)",
                templateInstantiations = parse.Document?.TemplateInstantiations,
                dataOwner = "UnifiedAstData (lexical identities; shared typed catalog)",
                dataBindings = parse.Document?.DataBindings,
                sourceProvenance = "Original Feature definition/use anchors where retained; complete include/Template maps pending",
                rejectionStage = report.Diagnostics.FirstOrDefault(d => d.Severity is "error" or "fatal")?.Stage
            }
        }, JsonOptions));
        else if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = report }, JsonOptions));
        else stdout.WriteLine($"Firmament V2 validation: {report.Status} ({report.Summary.FatalDiagnosticCount} fatal, {report.Summary.WarningDiagnosticCount} warning)");
        if (!json)
        {
            if (explain) stdout.WriteLine($"Language: {report.LanguageVersion}; parser route: {report.ParserRoute ?? "Expansion/Unselected"}; admission: {report.ValidationLevel}; templates: {parse.Document?.TemplateInstantiations?.Count ?? 0}; solids: {parse.Document?.Solids.Count ?? 0}");
            if (explain && parse.Document?.FeatureExpansion is { } expansion)
                stdout.WriteLine($"Feature owner: UnifiedAstFeature; definitions: {expansion.DefinitionCount}; invocations: {expansion.InvocationCount}; expanded declarations: {expansion.ExpandedSemanticNodeCount}");
            foreach (var diagnostic in report.Diagnostics)
                stderr.WriteLine($"{sourcePath}({diagnostic.Line},{diagnostic.Column}): {diagnostic.Severity} {diagnostic.Code}: {diagnostic.Message}");
        }
        return report.Status == "invalid" ? 1 : 0;
    }

    private static int WriteFrontendRejection(FirmamentFrontendSelection selection, string source, string path,
        string command, bool json, TextWriter stdout, TextWriter stderr)
    {
        var report = FirmamentV2ValidationReportBuilder.Build(selection.Failure(source), path);
        if (json)
        {
            if (command == "validate") stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = report }, JsonOptions));
            else stdout.WriteLine(JsonSerializer.Serialize(new { command, success = false, input = path, diagnostics = report.Diagnostics }, JsonOptions));
        }
        else foreach (var d in report.Diagnostics) stderr.WriteLine($"{path}({d.Line},{d.Column}): {d.Severity} {d.Code}: {d.Message}");
        return 1;
    }

    private static FirmamentV2ForgeRuntimeConfiguration CreateValidateForgeRuntimeConfiguration(IReadOnlyList<string> forgePackPaths)
    {
        if (forgePackPaths.Count == 0)
        {
            return FirmamentV2ForgeRuntimeConfiguration.CreateDefault();
        }

        var loader = new ForgeConceptPackAssemblyLoader();
        var packs = new List<(IForgeConceptPack Pack, string AssemblyPath)>();
        foreach (var forgePackPath in forgePackPaths)
        {
            foreach (var pack in loader.LoadFromAssemblyPath(forgePackPath))
            {
                packs.Add((pack, Path.GetFullPath(forgePackPath)));
            }
        }

        return FirmamentV2ForgeRuntimeConfiguration.Create(packs);
    }

    private static int RunTrace(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length > 0 && IsHelpFlag(args[0]))
        {
            WriteTraceHelp(stdout);
            return 0;
        }

        string? caseName = null;
        string? fixturePath = null;
        string? outDir = null;
        var json = false;
        for (var i = 0; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--case" when i + 1 < args.Length:
                    caseName = args[++i];
                    break;
                case "--fixture" when i + 1 < args.Length:
                    fixturePath = args[++i];
                    break;
                case "--fixture":
                    stderr.WriteLine("Trace option --fixture requires a fixture path.");
                    stderr.WriteLine(TraceUsage);
                    return 1;
                case "--case":
                    stderr.WriteLine("Trace option --case requires a case name.");
                    stderr.WriteLine(TraceUsage);
                    return 1;
                case "--out-dir" when i + 1 < args.Length:
                    outDir = args[++i];
                    break;
                case "--out-dir":
                    stderr.WriteLine("Trace option --out-dir requires a directory path.");
                    stderr.WriteLine("air-x6-output-directory-invalid");
                    stderr.WriteLine(TraceUsage);
                    return 1;
                case "--json":
                    json = true;
                    break;
                case "-h":
                case "--help":
                    WriteTraceHelp(stdout);
                    return 0;
                default:
                    if (!args[i].StartsWith("-", StringComparison.Ordinal))
                    {
                        stderr.WriteLine("trace does not analyze STEP files; use `aetheris analyze ...`.");
                        stderr.WriteLine("air-x6-step-input-rejected-use-analyze");
                        stderr.WriteLine(TraceUsage);
                        return 1;
                    }
                    stderr.WriteLine($"Unknown trace option '{args[i]}'.");
                    stderr.WriteLine(TraceUsage);
                    return 1;
            }
        }

        if (!string.IsNullOrWhiteSpace(caseName) && !string.IsNullOrWhiteSpace(fixturePath))
        {
            stderr.WriteLine("Trace options --case and --fixture are mutually exclusive.");
            stderr.WriteLine("air-x7-case-and-fixture-mutually-exclusive");
            stderr.WriteLine(TraceUsage);
            return 1;
        }

        AirTraceReport report;
        string fileStem;
        if (!string.IsNullOrWhiteSpace(fixturePath))
        {
            FirmFixture fixture;
            try { fixture = FirmFixtureLoader.Load(fixturePath); }
            catch (FirmFixtureException ex) { stderr.WriteLine(ex.Message); stderr.WriteLine(ex.Code); stderr.WriteLine(TraceUsage); return 1; }
            if (!AirTraceReportBuilder.SupportedFixtureCases.Contains(fixture.CaseName, StringComparer.Ordinal) && !fixture.Metadata.ContainsKey("implementation"))
            {
                stderr.WriteLine($"Unknown Firmament fixture case '{fixture.CaseName}'.");
                stderr.WriteLine("air-x7-unknown-firmfixture-case");
                stderr.WriteLine($"Supported fixture cases: {string.Join(", ", AirTraceReportBuilder.SupportedFixtureCases)}");
                return 1;
            }
            report = AirTraceReportBuilder.BuildFixture(fixture);
            fileStem = AirTraceReportBuilder.FixtureFileStem(fixture);
        }
        else
        {
            if (string.IsNullOrWhiteSpace(caseName))
            {
                stderr.WriteLine("Trace requires one of --case <name> or --fixture <path>.");
                stderr.WriteLine("air-x7-missing-case-or-fixture");
                stderr.WriteLine($"Supported cases: {string.Join(", ", AirTraceReportBuilder.SupportedCases)}");
                stderr.WriteLine(TraceUsage);
                return 1;
            }

            caseName = AirTraceReportBuilder.Normalize(caseName);
            if (!AirTraceReportBuilder.SupportedCases.Contains(caseName, StringComparer.Ordinal))
            {
                stderr.WriteLine($"Unknown trace case '{caseName}'.");
                stderr.WriteLine("air-x6-unknown-case-rejected");
                stderr.WriteLine($"Supported cases: {string.Join(", ", AirTraceReportBuilder.SupportedCases)}");
                return 1;
            }
            report = AirTraceReportBuilder.Build(caseName);
            fileStem = AirTraceReportBuilder.FileStem(caseName);
        }

        report = report with { Diagnostics = (json ? report.Diagnostics.Append("air-x7-json-output-requested").Append("air-x7-json-fixture-report-created") : report.Diagnostics.Append("air-x7-default-text-output").Append("air-x7-text-fixture-report-created")).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray() };
        if (!string.IsNullOrWhiteSpace(outDir) && (string.Equals(report.CaseName, "side-hole-face-attached-region", StringComparison.Ordinal) || report.FirmamentV2?.SemanticIntent is not null))
        {
            var artifacts = SideHoleGoldenPathArtifacts.Write(outDir, report);
            report = report with
            {
                Milestone = report.FirmamentV2?.SemanticIntent is not null ? "AIR-FIRMAMENT-X5" : "AIR-REGION-X13",
                Artifacts = artifacts,
                Diagnostics = report.Diagnostics.Append(report.FirmamentV2?.SemanticIntent is not null ? "air-firmament-x5-v2-side-hole-artifacts-written" : "air-region-x13-golden-path-artifacts-written").Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray()
            };
            var jsonText = JsonSerializer.Serialize(report, JsonOptions);
            var textText = AirTraceTextRenderer.Render(report);
            File.WriteAllText(artifacts.TraceJson, jsonText);
            File.WriteAllText(artifacts.TraceText, textText);
            File.WriteAllText(artifacts.Manifest, SideHoleGoldenPathArtifacts.Manifest(report, artifacts));
            if (json) stdout.WriteLine(jsonText);
            else stdout.WriteLine($"Trace artifacts written: {outDir}");
            return 0;
        }

        var text = json ? JsonSerializer.Serialize(report, JsonOptions) : AirTraceTextRenderer.Render(report);
        if (!string.IsNullOrWhiteSpace(outDir))
        {
            Directory.CreateDirectory(outDir);
            var path = Path.Combine(outDir, fileStem + (json ? ".json" : ".txt"));
            File.WriteAllText(path, text);
            if (json)
            {
                stdout.WriteLine(text);
            }
            else
            {
                stdout.WriteLine($"Trace report written: {path}");
            }
            return 0;
        }

        stdout.WriteLine(text);
        if (report.ExpectationSatisfied == false)
        {
            stderr.WriteLine("Firmament fixture expectation was not satisfied.");
            stderr.WriteLine("air-x7-fixture-expectation-not-satisfied");
            return 1;
        }
        return 0;
    }

    private static int RunCanon(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0)
        {
            stderr.WriteLine(CanonUsage);
            stderr.WriteLine("Run 'aetheris canon --help' for examples.");
            return 1;
        }

        if (IsHelpFlag(args[0]))
        {
            WriteCanonHelp(stdout);
            return 0;
        }

        if (args[0].StartsWith("-", StringComparison.Ordinal))
        {
            stderr.WriteLine("Canon requires <file.step> as the first argument.");
            stderr.WriteLine(CanonUsage);
            return 1;
        }

        var inputPath = args[0];
        string? outputPath = null;
        var json = false;
        var canonMode = Aetheris.Kernel.Core.Step242.Step242CanonMode.Deterministic;

        for (var i = 1; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--out" when i + 1 < args.Length:
                    outputPath = args[++i];
                    break;
                case "--out":
                    stderr.WriteLine("Canon option --out requires a path value.");
                    stderr.WriteLine(CanonUsage);
                    return 1;
                case "--json":
                    json = true;
                    break;
                case "--mode" when i + 1 < args.Length:
                    var modeValue = args[++i];
                    if (string.Equals(modeValue, "deterministic", StringComparison.OrdinalIgnoreCase))
                    {
                        canonMode = Aetheris.Kernel.Core.Step242.Step242CanonMode.Deterministic;
                    }
                    else if (string.Equals(modeValue, "production", StringComparison.OrdinalIgnoreCase) || string.Equals(modeValue, "production-preserve-metadata", StringComparison.OrdinalIgnoreCase))
                    {
                        canonMode = Aetheris.Kernel.Core.Step242.Step242CanonMode.ProductionPreserveMetadata;
                    }
                    else
                    {
                        stderr.WriteLine($"Unknown canon mode '{modeValue}'. Expected deterministic or production.");
                        stderr.WriteLine(CanonUsage);
                        return 1;
                    }
                    break;
                case "--mode":
                    stderr.WriteLine("Canon option --mode requires deterministic or production.");
                    stderr.WriteLine(CanonUsage);
                    return 1;
                case "-h":
                case "--help":
                    WriteCanonHelp(stdout);
                    return 0;
                default:
                    stderr.WriteLine($"Unknown canon option '{args[i]}'.");
                    stderr.WriteLine(CanonUsage);
                    return 1;
            }
        }

        if (string.IsNullOrWhiteSpace(outputPath))
        {
            stderr.WriteLine("Canon requires --out <canonical.step>.");
            stderr.WriteLine(CanonUsage);
            return 1;
        }

        var inputFullPath = Path.GetFullPath(inputPath);
        var outputFullPath = Path.GetFullPath(outputPath);

        if (!File.Exists(inputPath))
        {
            return WriteCanonFailure(
                json,
                stdout,
                stderr,
                inputFullPath,
                outputFullPath,
                errorKind: "missing-input",
                error: $"Input STEP file was not found: {inputFullPath}");
        }

        string stepText;
        try
        {
            stepText = File.ReadAllText(inputPath);
        }
        catch (Exception ex)
        {
            return WriteCanonFailure(json, stdout, stderr, inputFullPath, outputFullPath, "io-read-failure", ex.Message);
        }

        var importResult = Aetheris.Kernel.Core.Step242.Step242Importer.ImportBody(stepText,
            new Aetheris.Kernel.Core.Import.ImportPolicy(PreferredLane: Aetheris.Kernel.Core.Import.ImportLaneKind.ExactBRep));
        if (!importResult.IsSuccess)
        {
            return WriteCanonFailure(
                json,
                stdout,
                stderr,
                inputFullPath,
                outputFullPath,
                "import-failure",
                FormatKernelDiagnostics(importResult.Diagnostics));
        }

        var sourcePmi = Aetheris.Kernel.Core.Step242.Step242PmiTransfer.Read(stepText, importResult.Value);
        if (!sourcePmi.IsSuccess)
            return WriteCanonFailure(json, stdout, stderr, inputFullPath, outputFullPath, "pmi-transfer-failure", FormatKernelDiagnostics(sourcePmi.Diagnostics));
        var importedPmi = sourcePmi.Value.SemanticRecordCount > 0 ? sourcePmi.Value : null;
        var exportOptions = canonMode == Aetheris.Kernel.Core.Step242.Step242CanonMode.ProductionPreserveMetadata
            ? Aetheris.Kernel.Core.Step242.Step242ExportOptions.FromSourceMetadata(Aetheris.Kernel.Core.Step242.Step242SourceMetadataReader.Read(stepText),
                Aetheris.Kernel.Core.Step242.BrepExportPreflightPolicy.TrustedProductionRoute, importedPmi)
            : new Aetheris.Kernel.Core.Step242.Step242ExportOptions {
                ImportedPmi = importedPmi,
                BrepExportPreflightPolicy = Aetheris.Kernel.Core.Step242.BrepExportPreflightPolicy.TrustedProductionRoute,
                ImportedRecoveryToleranceMillimetres = .1 };

        var exportResult = Aetheris.Kernel.Core.Step242.Step242Exporter.ExportBody(importResult.Value, exportOptions);
        if (!exportResult.IsSuccess)
        {
            return WriteCanonFailure(
                json,
                stdout,
                stderr,
                inputFullPath,
                outputFullPath,
                "export-failure",
                FormatKernelDiagnostics(exportResult.Diagnostics));
        }

        try
        {
            File.WriteAllText(outputPath, exportResult.Value);
        }
        catch (Exception ex)
        {
            return WriteCanonFailure(json, stdout, stderr, inputFullPath, outputFullPath, "io-write-failure", ex.Message);
        }

        if (json)
        {
            var topology = importResult.Value.Topology;
            stdout.WriteLine(JsonSerializer.Serialize(new
            {
                success = true,
                inputPath = inputFullPath,
                outputPath = outputFullPath,
                bodyCount = topology.Bodies.Count(),
                shellCount = topology.Shells.Count(),
                diagnostics = exportResult.Diagnostics.Select(d => new {
                    code = d.Code.ToString(), severity = d.Severity.ToString(), message = d.Message, source = d.Source }),
                mode = canonMode == Aetheris.Kernel.Core.Step242.Step242CanonMode.ProductionPreserveMetadata ? "production" : "deterministic"
            }, JsonOptions));
        }
        else
        {
            stdout.WriteLine($"Canonical STEP written: {outputFullPath}");
            stdout.WriteLine($"Canon mode: {(canonMode == Aetheris.Kernel.Core.Step242.Step242CanonMode.ProductionPreserveMetadata ? "production" : "deterministic")}");
            foreach (var diagnostic in exportResult.Diagnostics.Where(d => d.Severity == Aetheris.Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Warning)
                .DistinctBy(d => d.Message)) stderr.WriteLine($"warning {diagnostic.Source}: {diagnostic.Message}");
        }

        return 0;
    }

    private static int WriteCanonFailure(
        bool json,
        TextWriter stdout,
        TextWriter stderr,
        string inputPath,
        string outputPath,
        string errorKind,
        string error)
    {
        if (json)
        {
            stdout.WriteLine(JsonSerializer.Serialize(new
            {
                success = false,
                inputPath,
                outputPath,
                errorKind,
                error
            }, JsonOptions));
        }
        else
        {
            stderr.WriteLine($"Canon failed ({errorKind}): {error}");
        }

        return 1;
    }

    private static string FormatKernelDiagnostics(IReadOnlyList<Aetheris.Kernel.Core.Diagnostics.KernelDiagnostic> diagnostics) =>
        string.Join(Environment.NewLine, diagnostics.Select(d => $"[{d.Severity}] {d.Source}: {d.Message}"));

    private static void WriteAnalyzeFailureJson(TextWriter stdout, string stepPath, Exception exception)
    {
        var fullPath = Path.GetFullPath(stepPath);
        if (exception is not StepAnalysisImportException importFailure)
        {
            stdout.WriteLine(JsonSerializer.Serialize(new
            {
                success = false,
                stepPath = fullPath,
                errorKind = "analysis-failure",
                error = exception.Message
            }, JsonOptions));
            return;
        }

        var multiRootDiagnostic = importFailure.Diagnostics.FirstOrDefault(d => string.Equals(d.Source, "Importer.AssemblyLike.StepMultiRoot", StringComparison.Ordinal));
        if (multiRootDiagnostic is null)
        {
            stdout.WriteLine(JsonSerializer.Serialize(new
            {
                success = false,
                stepPath = fullPath,
                errorKind = "import-failure",
                error = importFailure.Message,
                diagnostics = importFailure.Diagnostics.Select(d => new
                {
                    code = d.Code.ToString(),
                    severity = d.Severity.ToString(),
                    source = d.Source,
                    message = d.Message
                })
            }, JsonOptions));
            return;
        }

        var rigidRootCount = CountExactBrepRigidRoots(multiRootDiagnostic.Message);
        stdout.WriteLine(JsonSerializer.Serialize(new
        {
            success = false,
            stepPath = fullPath,
            errorKind = "assembly-like-step",
            classification = "assembly-like",
            rigidRootCount,
            routeHint = "Use the assembly extraction/import path for this STEP input.",
            error = importFailure.Message,
            diagnostics = importFailure.Diagnostics.Select(d => new
            {
                code = d.Code.ToString(),
                severity = d.Severity.ToString(),
                source = d.Source,
                message = d.Message
            })
        }, JsonOptions));
    }

    private static int? CountExactBrepRigidRoots(string message)
    {
        const string token = "detected ";
        var detectedIndex = message.IndexOf(token, StringComparison.OrdinalIgnoreCase);
        if (detectedIndex < 0)
        {
            return null;
        }

        var start = detectedIndex + token.Length;
        var countSlice = message[start..];
        var digits = new string(countSlice.TakeWhile(char.IsDigit).ToArray());
        if (digits.Length == 0)
        {
            return null;
        }

        return int.TryParse(digits, out var value) ? value : null;
    }

    private static int RunAnalyze(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0)
        {
            stderr.WriteLine(AnalyzeUsage);
            stderr.WriteLine($"   or: {AnalyzeMapUsage[7..]}");
            stderr.WriteLine($"   or: {AnalyzeSectionUsage[7..]}");
            stderr.WriteLine($"   or: {AnalyzeVolumeUsage[7..]}");
            stderr.WriteLine($"   or: {AnalyzeCompareUsage[7..]}");
            stderr.WriteLine($"   or: {AnalyzeCompoundUsage[7..]}");
            stderr.WriteLine($"   or: {AnalyzeAssemblyUsage[7..]}");
            stderr.WriteLine("Run 'aetheris analyze --help' for examples.");
            return 1;
        }

        if (IsHelpFlag(args[0]))
        {
            WriteAnalyzeHelp(stdout);
            return 0;
        }

        if (string.Equals(args[0], "map", StringComparison.Ordinal))
        {
            return RunAnalyzeMap(args.Skip(1).ToArray(), stdout, stderr);
        }

        if (string.Equals(args[0], "section", StringComparison.Ordinal))
        {
            return RunAnalyzeSection(args.Skip(1).ToArray(), stdout, stderr);
        }

        if (string.Equals(args[0], "volume", StringComparison.Ordinal))
        {
            return RunAnalyzeVolume(args.Skip(1).ToArray(), stdout, stderr);
        }
        if (string.Equals(args[0], "compound", StringComparison.Ordinal))
        {
            return RunAnalyzeCompound(args.Skip(1).ToArray(), stdout, stderr);
        }
        if (string.Equals(args[0], "assembly", StringComparison.Ordinal))
        {
            return RunAnalyzeAssembly(args.Skip(1).ToArray(), stdout, stderr);
        }
        if (string.Equals(args[0], "compare", StringComparison.Ordinal))
        {
            return RunAnalyzeCompare(args.Skip(1).ToArray(), stdout, stderr);
        }

        if (args[0].StartsWith("-", StringComparison.Ordinal))
        {
            stderr.WriteLine("Analyze requires <file.step> as the first argument, or a subcommand ('map', 'section', 'volume', 'compound', or 'compare').");
            stderr.WriteLine(AnalyzeUsage);
            return 1;
        }

        var stepPath = args[0];
        int? faceId = null;
        int? edgeId = null;
        int? vertexId = null;
        var json = false;

        for (var i = 1; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--face" when i + 1 < args.Length && int.TryParse(args[++i], out var face):
                    faceId = face;
                    break;
                case "--face":
                    stderr.WriteLine("Analyze option --face requires an integer face id.");
                    stderr.WriteLine(AnalyzeUsage);
                    return 1;
                case "--edge" when i + 1 < args.Length && int.TryParse(args[++i], out var edge):
                    edgeId = edge;
                    break;
                case "--edge":
                    stderr.WriteLine("Analyze option --edge requires an integer edge id.");
                    stderr.WriteLine(AnalyzeUsage);
                    return 1;
                case "--vertex" when i + 1 < args.Length && int.TryParse(args[++i], out var vertex):
                    vertexId = vertex;
                    break;
                case "--vertex":
                    stderr.WriteLine("Analyze option --vertex requires an integer vertex id.");
                    stderr.WriteLine(AnalyzeUsage);
                    return 1;
                case "--json":
                    json = true;
                    break;
                case "-h":
                case "--help":
                    WriteAnalyzeHelp(stdout);
                    return 0;
                default:
                    stderr.WriteLine($"Unknown analyze option '{args[i]}'.");
                    stderr.WriteLine(AnalyzeUsage);
                    return 1;
            }
        }

        var detailCount = (faceId.HasValue ? 1 : 0) + (edgeId.HasValue ? 1 : 0) + (vertexId.HasValue ? 1 : 0);
        if (detailCount > 1)
        {
            stderr.WriteLine("Specify at most one detail selector: --face, --edge, or --vertex.");
            return 1;
        }

        if (string.Equals(Path.GetExtension(stepPath), ".firmament", StringComparison.OrdinalIgnoreCase))
        {
            stderr.WriteLine("Analyze expects STEP; use `aetheris build <file.firmament>` first.");
            return 1;
        }
        if (!string.Equals(Path.GetExtension(stepPath), ".step", StringComparison.OrdinalIgnoreCase) && !string.Equals(Path.GetExtension(stepPath), ".stp", StringComparison.OrdinalIgnoreCase))
        {
            stderr.WriteLine("Analyze expects STEP (.step or .stp) input.");
            return 1;
        }

        AnalyzeResult analysis;
        try
        {
            analysis = StepAnalyzer.Analyze(stepPath, faceId, edgeId, vertexId);
        }
        catch (Exception ex)
        {
            if (!json)
            {
                WriteAnalyzeFailureText(stderr, stepPath, ex);
                return 1;
            }

            WriteAnalyzeFailureJson(stdout, stepPath, ex);
            return 1;
        }

        if (json)
        {
            stdout.WriteLine(JsonSerializer.Serialize(analysis, JsonOptions));
            return 0;
        }

        WriteSummaryText(analysis, stdout);
        return 0;
    }

    private static int RunAnalyzeCompare(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0]))
        {
            stdout.WriteLine(AnalyzeCompareUsage);
            return args.Length == 0 ? 1 : 0;
        }

        if (args.Length < 2)
        {
            stderr.WriteLine("Analyze compare requires <reference.step> and <candidate.step>.");
            stderr.WriteLine(AnalyzeCompareUsage);
            return 1;
        }

        var referencePath = args[0];
        var candidatePath = args[1];
        var json = false;
        var approximateVolume = false;
        int? resolution = null;
        var shape = false;
        var shapeResolution = 400;
        for (var i = 2; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--json":
                    json = true;
                    break;
                case "--shape":
                    shape = true;
                    break;
                case "--shape-resolution" when i + 1 < args.Length && int.TryParse(args[++i], out var parsedShape) && parsedShape > 0:
                    shape = true;
                    shapeResolution = parsedShape;
                    break;
                case "--shape-resolution":
                    stderr.WriteLine("Analyze compare option --shape-resolution requires a positive integer value.");
                    return 1;
                case "--approximate-volume":
                    approximateVolume = true;
                    break;
                case "--resolution" when i + 1 < args.Length && int.TryParse(args[++i], out var parsed):
                    resolution = parsed;
                    break;
                case "--resolution":
                    stderr.WriteLine("Analyze compare option --resolution requires an integer value.");
                    return 1;
                default:
                    stderr.WriteLine($"Unknown analyze compare option '{args[i]}'.");
                    stderr.WriteLine(AnalyzeCompareUsage);
                    return 1;
            }
        }

        if (approximateVolume && !resolution.HasValue)
        {
            stderr.WriteLine("Analyze compare approximate volume mode requires --resolution <N>.");
            return 1;
        }

        var reference = AnalyzeCompareSide(referencePath, approximateVolume, resolution);
        var candidate = AnalyzeCompareSide(candidatePath, approximateVolume, resolution);

        var bboxComparison = CompareBoundingBoxes(reference.Analysis?.Summary.BoundingBox, candidate.Analysis?.Summary.BoundingBox);
        var topologyComparison = CompareCounts(reference.Analysis, candidate.Analysis, s => s.FaceCount, s => s.EdgeCount, s => s.VertexCount, s => s.ShellCount, s => s.BodyCount);
        var surfaceComparison = CompareSurfaceFamilies(reference.Analysis?.Summary.SurfaceFamilies, candidate.Analysis?.Summary.SurfaceFamilies);
        var volumeComparison = CompareVolumes(reference.Volume, candidate.Volume, approximateVolume, resolution);
        var success = reference.Success && candidate.Success;
        StepShapeComparison.ShapeComparisonResult? shapeComparison = null;
        string? shapeError = null;
        if (shape && success)
        {
            try
            {
                shapeComparison = StepShapeComparison.Compare(referencePath, candidatePath, shapeResolution);
            }
            catch (Exception ex) when (ex is StepAnalysisImportException or InvalidOperationException)
            {
                shapeError = ex.Message;
                success = false;
            }
        }

        if (json)
        {
            stdout.WriteLine(JsonSerializer.Serialize(new
            {
                success,
                reference,
                candidate,
                bboxComparison,
                topologyComparison,
                surfaceFamilyComparison = surfaceComparison,
                volumeComparison,
                shapeComparison,
                shapeError,
                notes = new[] { approximateVolume ? "Volume comparison uses explicit voxel approximation when exact fails per-side." : "Volume comparison uses exact path only." }
            }, JsonOptions));
            return success ? 0 : 1;
        }

        stdout.WriteLine("Files:");
        stdout.WriteLine($"  Reference: {reference.StepPath}");
        stdout.WriteLine($"  Candidate: {candidate.StepPath}");
        stdout.WriteLine("Status:");
        stdout.WriteLine($"  Reference success: {reference.Success}");
        stdout.WriteLine($"  Candidate success: {candidate.Success}");
        if (!string.IsNullOrWhiteSpace(reference.ErrorKind)) stdout.WriteLine($"  Reference error: {reference.ErrorKind}: {reference.Error}");
        if (!string.IsNullOrWhiteSpace(candidate.ErrorKind)) stdout.WriteLine($"  Candidate error: {candidate.ErrorKind}: {candidate.Error}");
        stdout.WriteLine("Bounding box:");
        stdout.WriteLine($"  Comparison: {JsonSerializer.Serialize(bboxComparison, JsonOptions)}");
        stdout.WriteLine("Counts:");
        stdout.WriteLine($"  Comparison: {JsonSerializer.Serialize(topologyComparison, JsonOptions)}");
        stdout.WriteLine("Surface families:");
        stdout.WriteLine($"  Comparison: {JsonSerializer.Serialize(surfaceComparison, JsonOptions)}");
        stdout.WriteLine("Volume:");
        stdout.WriteLine($"  Comparison: {JsonSerializer.Serialize(volumeComparison, JsonOptions)}");
        if (shapeError is not null) stdout.WriteLine($"Shape comparison failed: {shapeError}");
        if (shapeComparison is { } sc)
        {
            var o = sc.Overlap;
            stdout.WriteLine("Shape overlap (approximate, tessellated rays):");
            stdout.WriteLine(FormattableString.Invariant($"  Reference {o.ReferenceVolume:0.###}  Candidate {o.CandidateVolume:0.###}  IoU {o.IntersectionOverUnion:0.######}"));
            stdout.WriteLine(FormattableString.Invariant($"  Reference only {o.ReferenceOnlyVolume:0.###}  Candidate only {o.CandidateOnlyVolume:0.###}  (grid {o.ColumnsX}x{o.ColumnsY}, cell {o.CellSize:0.####})"));
            foreach (var r in o.Regions)
            {
                stdout.WriteLine(FormattableString.Invariant($"    {r.Side,-15} {r.Volume,12:0.###}  x {r.BoundsMin[0]:0.##}..{r.BoundsMax[0]:0.##}  y {r.BoundsMin[1]:0.##}..{r.BoundsMax[1]:0.##}  z {r.BoundsMin[2]:0.##}..{r.BoundsMax[2]:0.##}"));
            }

            var c = sc.Carriers;
            stdout.WriteLine($"Carriers: reference {c.ReferenceCarrierCount}, candidate {c.CandidateCarrierCount}, matched {c.MatchedCarrierCount}");
            foreach (var (label, groups) in new[] { ("missing", c.MissingFromCandidate), ("extra", c.ExtraInCandidate) })
            {
                foreach (var g in groups)
                {
                    var where = g.BoundsMin is { } lo && g.BoundsMax is { } hi
                        ? FormattableString.Invariant($"  [{lo[0]:0.##},{lo[1]:0.##},{lo[2]:0.##}]..[{hi[0]:0.##},{hi[1]:0.##},{hi[2]:0.##}]")
                        : string.Empty;
                    stdout.WriteLine($"  {label,-7} {g.Description}  faces {string.Join(',', g.FaceIds)}{where}");
                }
            }
        }

        return success ? 0 : 1;
    }

    private static int RunAnalyzeVolume(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0)
        {
            stderr.WriteLine(AnalyzeVolumeUsage);
            return 1;
        }

        if (IsHelpFlag(args[0]))
        {
            WriteAnalyzeVolumeHelp(stdout);
            return 0;
        }

        var stepPath = args[0];
        var json = false;
        var approximate = false;
        int? resolution = null;
        if (stepPath.StartsWith("-", StringComparison.Ordinal))
        {
            stderr.WriteLine("Analyze volume requires <file.step> as the first argument.");
            stderr.WriteLine(AnalyzeVolumeUsage);
            return 1;
        }

        for (var i = 1; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--json":
                    json = true;
                    break;
                case "--approximate":
                    approximate = true;
                    break;
                case "--resolution" when i + 1 < args.Length && int.TryParse(args[++i], out var parsed):
                    resolution = parsed;
                    break;
                case "--resolution":
                    stderr.WriteLine("Analyze volume option --resolution requires an integer value.");
                    return 1;
                case var _ when args[i].StartsWith("--box", StringComparison.Ordinal):
                    stderr.WriteLine("Analyze volume sub-box probing is deferred: exact bounded clipping against an axis-aligned sub-box is not available yet.");
                    return 1;
                default:
                    stderr.WriteLine($"Unknown analyze volume option '{args[i]}'.");
                    stderr.WriteLine(AnalyzeVolumeUsage);
                    return 1;
            }
        }

        if (approximate && !resolution.HasValue)
        {
            stderr.WriteLine("Analyze volume approximate mode requires --resolution <N>.");
            return 1;
        }

        try
        {
            var result = StepAnalyzer.AnalyzeVolume(stepPath, approximate, resolution);
            if (json)
            {
                stdout.WriteLine(JsonSerializer.Serialize(result, JsonOptions));
            }
            else
            {
                stdout.WriteLine($"Input: {result.InputPath}");
                stdout.WriteLine("Success: true");
                stdout.WriteLine($"Volume: {result.Volume:G17}");
                stdout.WriteLine($"Length unit: {result.LengthUnit}");
                stdout.WriteLine($"Volume unit: {result.VolumeUnit}");
                stdout.WriteLine($"Bounding box: min=({result.BoundingBox.Min.X:G17},{result.BoundingBox.Min.Y:G17},{result.BoundingBox.Min.Z:G17}), max=({result.BoundingBox.Max.X:G17},{result.BoundingBox.Max.Y:G17},{result.BoundingBox.Max.Z:G17})");
                stdout.WriteLine($"Method: {result.Method}");
                stdout.WriteLine($"Exact: {result.Exact}");
                stdout.WriteLine($"Approximate: {result.Approximate}");
                if (result.Resolution.HasValue)
                {
                    stdout.WriteLine($"Resolution: {result.Resolution.Value}");
                }
                if (result.VoxelSize is { } voxelSize)
                {
                    stdout.WriteLine($"Voxel size: ({voxelSize.X:G17},{voxelSize.Y:G17},{voxelSize.Z:G17})");
                }
                if (result.OccupiedCount.HasValue && result.TotalCount.HasValue)
                {
                    stdout.WriteLine($"Occupied voxels: {result.OccupiedCount.Value}/{result.TotalCount.Value}");
                }
                if (result.UnknownCount.HasValue && result.TotalCount.HasValue)
                {
                    stdout.WriteLine($"Unknown samples: {result.UnknownCount.Value}/{result.TotalCount.Value}");
                }
                if (!string.IsNullOrWhiteSpace(result.UnknownPolicy))
                {
                    stdout.WriteLine($"Unknown policy: {result.UnknownPolicy}");
                }
                if (result.UnknownCount.GetValueOrDefault() > 0)
                {
                    stdout.WriteLine("Warning: unknown containment samples were conservatively excluded from occupied volume (outside policy), so the estimate may be an under-estimate.");
                }
                foreach (var n in result.Notes) stdout.WriteLine($"Note: {n}");
            }
            return 0;
        }
        catch (Exception ex)
        {
            if (json) WriteAnalyzeFailureJson(stdout, stepPath, ex);
            else WriteAnalyzeFailureText(stderr, stepPath, ex);
            return 1;
        }
    }

    private static CompareSideResult AnalyzeCompareSide(string stepPath, bool approximateVolume, int? resolution)
    {
        var fullPath = Path.GetFullPath(stepPath);
        try
        {
            var analysis = StepAnalyzer.Analyze(stepPath);
            StepAnalyzer.VolumeAnalysisResult? volume = null;
            try
            {
                volume = StepAnalyzer.AnalyzeVolume(stepPath, false, null);
            }
            catch
            {
                if (approximateVolume && resolution.HasValue)
                {
                    volume = StepAnalyzer.AnalyzeVolume(stepPath, true, resolution.Value);
                }
            }

            return new CompareSideResult(true, fullPath, analysis, volume, null, null);
        }
        catch (Exception ex)
        {
            var errorKind = "analysis-failure";
            string? classification = null;
            int? rigidRootCount = null;
            if (ex is StepAnalysisImportException importFailure)
            {
                var multiRootDiagnostic = importFailure.Diagnostics.FirstOrDefault(d => string.Equals(d.Source, "Importer.AssemblyLike.StepMultiRoot", StringComparison.Ordinal));
                if (multiRootDiagnostic is not null)
                {
                    errorKind = "assembly-like-step";
                    classification = "assembly-like";
                    rigidRootCount = CountExactBrepRigidRoots(multiRootDiagnostic.Message);
                }
                else
                {
                    errorKind = "import-failure";
                }
            }

            return new CompareSideResult(false, fullPath, null, null, errorKind, ex.Message, classification, rigidRootCount);
        }
    }

    private static object CompareBoundingBoxes(Aetheris.Kernel.Core.Math.BoundingBox3D? reference, Aetheris.Kernel.Core.Math.BoundingBox3D? candidate)
    {
        if (reference is null || candidate is null) return new { available = false };
        var minDx = candidate.Value.Min.X - reference.Value.Min.X;
        var minDy = candidate.Value.Min.Y - reference.Value.Min.Y;
        var minDz = candidate.Value.Min.Z - reference.Value.Min.Z;
        var maxDx = candidate.Value.Max.X - reference.Value.Max.X;
        var maxDy = candidate.Value.Max.Y - reference.Value.Max.Y;
        var maxDz = candidate.Value.Max.Z - reference.Value.Max.Z;
        return new { available = true, minDelta = new { x = minDx, y = minDy, z = minDz }, maxDelta = new { x = maxDx, y = maxDy, z = maxDz } };
    }

    private static object CompareCounts(AnalyzeResult? reference, AnalyzeResult? candidate, params Func<AnalyzeSummary, int>[] selectors)
    {
        if (reference is null || candidate is null) return new { available = false };
        var names = new[] { "faceCount", "edgeCount", "vertexCount", "shellCount", "bodyCount" };
        var map = new Dictionary<string, object>(StringComparer.Ordinal);
        for (var i = 0; i < selectors.Length; i++)
        {
            var r = selectors[i](reference.Summary);
            var c = selectors[i](candidate.Summary);
            map[names[i]] = new { reference = r, candidate = c, delta = c - r, absDelta = Math.Abs(c - r) };
        }
        return map;
    }

    private static object CompareSurfaceFamilies(IReadOnlyDictionary<string, int>? reference, IReadOnlyDictionary<string, int>? candidate)
    {
        if (reference is null || candidate is null) return new { available = false };
        var keys = reference.Keys.Concat(candidate.Keys).Distinct(StringComparer.Ordinal).OrderBy(k => k, StringComparer.Ordinal);
        return keys.ToDictionary(k => k, k => new { reference = reference.GetValueOrDefault(k), candidate = candidate.GetValueOrDefault(k), delta = candidate.GetValueOrDefault(k) - reference.GetValueOrDefault(k), absDelta = Math.Abs(candidate.GetValueOrDefault(k) - reference.GetValueOrDefault(k)) });
    }

    private static object CompareVolumes(StepAnalyzer.VolumeAnalysisResult? reference, StepAnalyzer.VolumeAnalysisResult? candidate, bool approximateVolume, int? resolution)
    {
        if (reference is null || candidate is null) return new { available = false, approximateVolumeRequested = approximateVolume, resolution };
        var delta = candidate.Volume - reference.Volume;
        var relativeDelta = Math.Abs(reference.Volume) > 1e-12 ? delta / reference.Volume : (double?)null;
        return new
        {
            available = true,
            method = $"{reference.Method} vs {candidate.Method}",
            approximateVolumeRequested = approximateVolume,
            resolution,
            reference = new { reference.Volume, reference.Method, reference.UnknownCount, reference.TotalCount },
            candidate = new { candidate.Volume, candidate.Method, candidate.UnknownCount, candidate.TotalCount },
            delta,
            absDelta = Math.Abs(delta),
            relativeDelta
        };
    }


    private static int RunExperimental(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0]))
        {
            WriteExperimentalHelp(stdout);
            return args.Length == 0 ? 1 : 0;
        }

        if (string.Equals(args[0], "airchamfer-cube", StringComparison.Ordinal))
        {
            return RunExperimentalAirChamferCube(args.Skip(1).ToArray(), stdout, stderr);
        }

        if (string.Equals(args[0], "airchamfer-corpus", StringComparison.Ordinal))
        {
            return RunExperimentalAirChamferCorpus(args.Skip(1).ToArray(), stdout, stderr);
        }

        if (string.Equals(args[0], "prismatic-corpus", StringComparison.Ordinal))
        {
            return RunExperimentalPrismaticCorpus(args.Skip(1).ToArray(), stdout, stderr);
        }

        if (string.Equals(args[0], "prismatic-map", StringComparison.Ordinal))
        {
            return RunExperimentalPrismaticMap(args.Skip(1).ToArray(), stdout, stderr);
        }

        if (string.Equals(args[0], "loop-chamfer-corpus", StringComparison.Ordinal))
        {
            return RunExperimentalLoopChamferCorpus(args.Skip(1).ToArray(), stdout, stderr);
        }

        if (string.Equals(args[0], "heightfield-art", StringComparison.Ordinal))
        {
            return RunExperimentalHeightFieldArt(args.Skip(1).ToArray(), stdout, stderr);
        }

        stderr.WriteLine($"Unknown experimental subcommand '{args[0]}'.");
        stderr.WriteLine(ExperimentalUsage);
        return 1;
    }

    private static int RunExperimentalAirChamferCube(string[] args, TextWriter stdout, TextWriter stderr)
    {
        string? outPath = null;
        var json = false;

        for (var i = 0; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--out" when i + 1 < args.Length:
                    outPath = args[++i];
                    break;
                case "--out":
                    stderr.WriteLine("Experimental airchamfer-cube option --out requires a path value.");
                    stderr.WriteLine(ExperimentalAirChamferCubeUsage);
                    return 1;
                case "--json":
                    json = true;
                    break;
                case "-h":
                case "--help":
                    WriteExperimentalAirChamferCubeHelp(stdout);
                    return 0;
                default:
                    stderr.WriteLine($"Unknown experimental airchamfer-cube option '{args[i]}'.");
                    stderr.WriteLine(ExperimentalAirChamferCubeUsage);
                    return 1;
            }
        }

        if (string.IsNullOrWhiteSpace(outPath))
        {
            stderr.WriteLine("Experimental airchamfer-cube requires --out <path>.");
            stderr.WriteLine(ExperimentalAirChamferCubeUsage);
            return 1;
        }

        var artifact = AirChamferStepArtifactLab.WriteControlledCubeOneEdgeStep(outPath);
        if (json)
        {
            stdout.WriteLine(JsonSerializer.Serialize(new
            {
                success = artifact.Succeeded,
                outputPath = artifact.OutputPath,
                artifactFileName = artifact.ArtifactFileName,
                route = artifact.Route,
                candidatePath = artifact.CandidatePath,
                shadowCandidateStatus = artifact.ShadowCandidateStatus.ToString(),
                markers = artifact.MarkerSummary,
                topologySummary = artifact.TopologySummary,
                diagnostics = artifact.Diagnostics,
                error = artifact.Error
            }, JsonOptions));
            return artifact.Succeeded ? 0 : 1;
        }

        foreach (var diagnostic in artifact.Diagnostics)
        {
            stdout.WriteLine(diagnostic);
        }

        if (!artifact.Succeeded)
        {
            stderr.WriteLine(artifact.Error ?? "Experimental AirChamfer STEP artifact export failed.");
            return 1;
        }

        stdout.WriteLine($"Experimental AirChamfer cube STEP artifact written: {artifact.OutputPath}");
        stdout.WriteLine("Route: experimental/lab AirChamfer shadow candidate export; production chamfer remains legacy-authoritative.");
        return 0;
    }


    private static int RunExperimentalAirChamferCorpus(string[] args, TextWriter stdout, TextWriter stderr)
    {
        string? outDir = null;
        var json = false;

        for (var i = 0; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--out-dir" when i + 1 < args.Length:
                    outDir = args[++i];
                    break;
                case "--out-dir":
                    stderr.WriteLine("Experimental airchamfer-corpus option --out-dir requires a directory value.");
                    stderr.WriteLine(ExperimentalAirChamferCorpusUsage);
                    return 1;
                case "--json":
                    json = true;
                    break;
                case "-h":
                case "--help":
                    WriteExperimentalAirChamferCorpusHelp(stdout);
                    return 0;
                default:
                    stderr.WriteLine($"Unknown experimental airchamfer-corpus option '{args[i]}'.");
                    stderr.WriteLine(ExperimentalAirChamferCorpusUsage);
                    return 1;
            }
        }

        if (string.IsNullOrWhiteSpace(outDir))
        {
            stderr.WriteLine("Experimental airchamfer-corpus requires --out-dir <dir>.");
            stderr.WriteLine(ExperimentalAirChamferCorpusUsage);
            return 1;
        }

        var corpus = AirChamferStepArtifactLab.WriteEdgeX11Corpus(outDir);
        if (json)
        {
            stdout.WriteLine(JsonSerializer.Serialize(corpus, JsonOptions));
            return corpus.Errors.Count == 0 ? 0 : 1;
        }

        foreach (var diagnostic in corpus.Diagnostics)
        {
            stdout.WriteLine(diagnostic);
        }

        stdout.WriteLine($"Experimental AirChamfer EDGE-X11 corpus summary written: {corpus.SummaryPath}");
        stdout.WriteLine("Route: experimental/lab AirChamfer shadow candidate corpus; production chamfer remains legacy-authoritative.");
        return corpus.Errors.Count == 0 ? 0 : 1;
    }


    private static int RunExperimentalPrismaticCorpus(string[] args, TextWriter stdout, TextWriter stderr)
    {
        string? outDir = null;
        var json = false;

        for (var i = 0; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--out-dir" when i + 1 < args.Length:
                    outDir = args[++i];
                    break;
                case "--out-dir":
                    stderr.WriteLine("Experimental prismatic-corpus option --out-dir requires a directory value.");
                    stderr.WriteLine(ExperimentalPrismaticCorpusUsage);
                    return 1;
                case "--json":
                    json = true;
                    break;
                case "-h":
                case "--help":
                    WriteExperimentalPrismaticCorpusHelp(stdout);
                    return 0;
                default:
                    stderr.WriteLine($"Unknown experimental prismatic-corpus option '{args[i]}'.");
                    stderr.WriteLine(ExperimentalPrismaticCorpusUsage);
                    return 1;
            }
        }

        if (string.IsNullOrWhiteSpace(outDir))
        {
            stderr.WriteLine("Experimental prismatic-corpus requires --out-dir <dir>.");
            stderr.WriteLine(ExperimentalPrismaticCorpusUsage);
            return 1;
        }

        var corpus = PrismaticSectionTransitionCorpusLab.WriteEdgePrismaticX5Corpus(outDir);
        if (json)
        {
            stdout.WriteLine(JsonSerializer.Serialize(corpus, JsonOptions));
            return corpus.Errors.Count == 0 ? 0 : 1;
        }

        foreach (var diagnostic in corpus.Diagnostics)
        {
            stdout.WriteLine(diagnostic);
        }

        stdout.WriteLine($"Experimental prismatic EDGE-PRISMATIC-X5 corpus summary written: {corpus.SummaryPath}");
        stdout.WriteLine("Route: experimental/lab prismatic section-transition corpus; production routes remain unchanged.");
        return corpus.Errors.Count == 0 ? 0 : 1;
    }


    private static int RunExperimentalLoopChamferCorpus(string[] args, TextWriter stdout, TextWriter stderr)
    {
        string? outDir = null;
        var json = false;

        for (var i = 0; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--out-dir" when i + 1 < args.Length:
                    outDir = args[++i];
                    break;
                case "--out-dir":
                    stderr.WriteLine("Experimental loop-chamfer-corpus option --out-dir requires a directory value.");
                    stderr.WriteLine(ExperimentalLoopChamferCorpusUsage);
                    return 1;
                case "--json":
                    json = true;
                    break;
                case "-h":
                case "--help":
                    WriteExperimentalLoopChamferCorpusHelp(stdout);
                    return 0;
                default:
                    stderr.WriteLine($"Unknown experimental loop-chamfer-corpus option '{args[i]}'.");
                    stderr.WriteLine(ExperimentalLoopChamferCorpusUsage);
                    return 1;
            }
        }

        if (string.IsNullOrWhiteSpace(outDir))
        {
            stderr.WriteLine("Experimental loop-chamfer-corpus requires --out-dir <dir>.");
            stderr.WriteLine(ExperimentalLoopChamferCorpusUsage);
            return 1;
        }

        var corpus = EdgeLoopX2TopFaceLoopChamferCorpusLab.WriteEdgeLoopX2Corpus(outDir);
        if (json)
        {
            stdout.WriteLine(JsonSerializer.Serialize(corpus, JsonOptions));
            return corpus.Errors.Count == 0 ? 0 : 1;
        }

        foreach (var diagnostic in corpus.Diagnostics)
        {
            stdout.WriteLine(diagnostic);
        }

        stdout.WriteLine($"Experimental EDGE-LOOP-X2 loop chamfer corpus summary written: {corpus.SummaryPath}");
        stdout.WriteLine("Route: experimental/lab top-face outer-loop chamfer corpus; production chamfer and fillet routes remain unchanged.");
        return corpus.Errors.Count == 0 ? 0 : 1;
    }


    private static int RunExperimentalPrismaticMap(string[] args, TextWriter stdout, TextWriter stderr)
    {
        string? caseName = null;
        int? rows = null;
        int? cols = null;
        var json = false;
        string? request = null;

        for (var i = 0; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--case" when i + 1 < args.Length:
                    caseName = args[++i];
                    break;
                case "--case":
                    stderr.WriteLine("edge-prismatic-x9-missing-case");
                    stderr.WriteLine("Experimental prismatic-map option --case requires a generated case value.");
                    stderr.WriteLine(ExperimentalPrismaticMapUsage);
                    return 1;
                case "--rows" when i + 1 < args.Length && int.TryParse(args[++i], out var parsedRows):
                    rows = parsedRows;
                    break;
                case "--rows":
                    stderr.WriteLine("edge-prismatic-x9-invalid-grid");
                    stderr.WriteLine("Experimental prismatic-map option --rows requires an integer value.");
                    stderr.WriteLine(ExperimentalPrismaticMapUsage);
                    return 1;
                case "--cols" when i + 1 < args.Length && int.TryParse(args[++i], out var parsedCols):
                    cols = parsedCols;
                    break;
                case "--cols":
                    stderr.WriteLine("edge-prismatic-x9-invalid-grid");
                    stderr.WriteLine("Experimental prismatic-map option --cols requires an integer value.");
                    stderr.WriteLine(ExperimentalPrismaticMapUsage);
                    return 1;
                case "--request" when i + 1 < args.Length:
                    request = args[++i];
                    break;
                case "--request":
                    stderr.WriteLine("edge-prismatic-x9-lossy-request-rejected:unknown");
                    stderr.WriteLine("Experimental prismatic-map option --request requires a value; only map occupancy is supported.");
                    stderr.WriteLine(ExperimentalPrismaticMapUsage);
                    return 1;
                case "--json":
                    json = true;
                    break;
                case "-h":
                case "--help":
                    WriteExperimentalPrismaticMapHelp(stdout);
                    return 0;
                default:
                    if (!args[i].StartsWith("-", StringComparison.Ordinal))
                    {
                        stderr.WriteLine("edge-prismatic-x9-step-input-rejected");
                        stderr.WriteLine("experimental prismatic-map does not accept STEP input; use generated --case values only");
                        stderr.WriteLine(ExperimentalPrismaticMapUsage);
                        return 1;
                    }

                    stderr.WriteLine($"Unknown experimental prismatic-map option '{args[i]}'.");
                    stderr.WriteLine(ExperimentalPrismaticMapUsage);
                    return 1;
            }
        }

        if (!json)
        {
            stderr.WriteLine("edge-prismatic-x9-json-required");
            stderr.WriteLine("Experimental prismatic-map requires --json to avoid implying a stable human-facing API.");
            stderr.WriteLine(ExperimentalPrismaticMapUsage);
            return 1;
        }

        if (string.IsNullOrWhiteSpace(caseName))
        {
            stderr.WriteLine("edge-prismatic-x9-missing-case");
            stderr.WriteLine("Experimental prismatic-map requires --case <case>.");
            stderr.WriteLine(ExperimentalPrismaticMapUsage);
            return 1;
        }

        if (!rows.HasValue || !cols.HasValue || rows <= 0 || cols <= 0)
        {
            stderr.WriteLine("edge-prismatic-x9-invalid-grid");
            stderr.WriteLine("Experimental prismatic-map requires positive --rows <N> and --cols <N> values.");
            stderr.WriteLine(ExperimentalPrismaticMapUsage);
            return 1;
        }

        if (request is not null && !string.Equals(request, "map-occupancy", StringComparison.OrdinalIgnoreCase))
        {
            var failure = ExperimentalPrismaticMapLab.LossyRequestRejected(caseName, request, rows.Value, cols.Value);
            stdout.WriteLine(JsonSerializer.Serialize(failure, JsonOptions));
            stderr.WriteLine($"edge-prismatic-x9-lossy-request-rejected:{request.Trim().ToLowerInvariant().Replace(' ', '-')}");
            stderr.WriteLine("Experimental prismatic-map only supports map occupancy; face identity and topology parity are lossy.");
            return 1;
        }

        if (!ExperimentalPrismaticMapLab.SupportedCases.Contains(caseName, StringComparer.Ordinal))
        {
            var token = caseName.Trim().ToLowerInvariant().Replace(' ', '-');
            stderr.WriteLine($"edge-prismatic-x9-unknown-case:{token}");
            stderr.WriteLine($"Unknown experimental prismatic-map generated case '{caseName}'. Supported cases: {string.Join(", ", ExperimentalPrismaticMapLab.SupportedCases)}.");
            stderr.WriteLine(ExperimentalPrismaticMapUsage);
            return 1;
        }

        var result = ExperimentalPrismaticMapLab.Run(caseName, rows.Value, cols.Value);
        stdout.WriteLine(JsonSerializer.Serialize(result, JsonOptions));
        return result.Success ? 0 : 1;
    }

    private static int RunAsm(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0]))
        {
            WriteAsmHelp(stdout);
            return args.Length == 0 ? 1 : 0;
        }

        if (string.Equals(args[0], "exec", StringComparison.Ordinal))
        {
            return RunAsmExec(args.Skip(1).ToArray(), stdout, stderr);
        }

        if (string.Equals(args[0], "inspect", StringComparison.Ordinal))
        {
            return RunAsmInspect(args.Skip(1).ToArray(), stdout, stderr);
        }

        if (string.Equals(args[0], "export", StringComparison.Ordinal))
        {
            return RunAsmExport(args.Skip(1).ToArray(), stdout, stderr);
        }

        if (string.Equals(args[0], "import-step", StringComparison.Ordinal))
            return RunAsmImportStep(args.Skip(1).ToArray(), stdout, stderr);
        if (string.Equals(args[0], "export-ap242", StringComparison.Ordinal))
            return RunAsmExportAp242(args.Skip(1).ToArray(), stdout, stderr);
        if (string.Equals(args[0], "export-usd", StringComparison.Ordinal))
            return AssemblyUsdCommand.Run(args.Skip(1).ToArray(), stdout, stderr);
        if (string.Equals(args[0], "motion", StringComparison.Ordinal))
            return AssemblyMotionCommand.Run(args.Skip(1).ToArray(), stdout, stderr);
        if (string.Equals(args[0], "export-glb", StringComparison.Ordinal))
            return AssemblyGlbCommand.Run(args.Skip(1).ToArray(), stdout, stderr);

        stderr.WriteLine($"Unknown asm subcommand '{args[0]}'.");
        stderr.WriteLine(AsmExecUsage);
        stderr.WriteLine(AsmExportUsage);
        stderr.WriteLine(AsmInspectUsage);
        return 1;
    }

    private static int RunSculpture(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0]))
        {
            WriteSculptureHelp(stdout);
            return args.Length == 0 ? 1 : 0;
        }
        if (!string.Equals(args[0], "build", StringComparison.Ordinal) || args.Length < 2 || args[1].StartsWith("-", StringComparison.Ordinal))
        {
            stderr.WriteLine(SculptureUsage);
            return 1;
        }

        var sourcePath = Path.GetFullPath(args[1]);
        string? output = null, evidencePath = null, previewPath = null;
        var json = false;
        for (var i = 2; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--out" when i + 1 < args.Length: output = Path.GetFullPath(args[++i]); break;
                case "--evidence" when i + 1 < args.Length: evidencePath = Path.GetFullPath(args[++i]); break;
                case "--preview" when i + 1 < args.Length: previewPath = Path.GetFullPath(args[++i]); break;
                case "--json": json = true; break;
                case "-h":
                case "--help": WriteSculptureHelp(stdout); return 0;
                default: stderr.WriteLine($"Unknown sculpture option '{args[i]}'."); stderr.WriteLine(SculptureUsage); return 1;
            }
        }
        if (!File.Exists(sourcePath)) { stderr.WriteLine($"Sol 1 source was not found: {sourcePath}"); return 1; }

        output ??= Path.GetFullPath(Path.Combine("artifacts", "local", "virtual-sculpture", "sol-1.step"));
        evidencePath ??= Path.ChangeExtension(output, ".evidence.json");
        previewPath ??= Path.ChangeExtension(output, ".preview.svg");
        var loaded = Sol1Source.Load(sourcePath);
        if (!loaded.IsSuccess)
        {
            foreach (var diagnostic in loaded.Diagnostics) stderr.WriteLine($"- [Error] {diagnostic.Source}: {diagnostic.Message}");
            return 1;
        }
        var built = Sol1Materializer.Build(loaded.Value);
        if (!built.IsSuccess)
        {
            foreach (var diagnostic in built.Diagnostics) stderr.WriteLine($"- [Error] {diagnostic.Source}: {diagnostic.Message}");
            return 1;
        }

        Directory.CreateDirectory(Path.GetDirectoryName(output)!);
        Directory.CreateDirectory(Path.GetDirectoryName(evidencePath)!);
        Directory.CreateDirectory(Path.GetDirectoryName(previewPath)!);
        File.WriteAllText(output, built.Value.Step);
        File.WriteAllText(evidencePath, JsonSerializer.Serialize(built.Value.Evidence, JsonOptions));
        File.WriteAllText(previewPath, built.Value.PreviewSvg);
        if (json)
        {
            stdout.WriteLine(JsonSerializer.Serialize(new
            {
                command = "sculpture build",
                success = true,
                domain = "VirtualSculpture",
                mode = "Virtual",
                source = sourcePath,
                step = output,
                evidencePath,
                preview = previewPath,
                report = built.Value.Evidence
            }, JsonOptions));
        }
        else
        {
            stdout.WriteLine("Built Sol 1 — ART-X0 virtual mathematical sculpture");
            stdout.WriteLine($"STEP: {output}");
            stdout.WriteLine($"Evidence: {evidencePath}");
            stdout.WriteLine($"Preview: {previewPath}");
            stdout.WriteLine($"SHA-256: {built.Value.Evidence.StepSha256}");
            stdout.WriteLine($"Geometry: {built.Value.Evidence.PhyllotaxisNodes} phyllotaxis nodes, {built.Value.Evidence.LatticeConnections} Fibonacci connections, {built.Value.Evidence.ExactClosedBodyOccurrences} exact closed-body occurrences");
        }
        return 0;
    }

    private static int RunExperimentalHeightFieldArt(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0]))
        {
            stdout.WriteLine("Generate the retired polar PlasticShell height field as mathematical computer art.");
            stdout.WriteLine("This path is explicitly non-manufacturing and never participates in normal build.");
            stdout.WriteLine(ExperimentalHeightFieldArtUsage);
            return args.Length == 0 ? 1 : 0;
        }
        var source = args[0]; string? output = null; var json = false;
        for (var i = 1; i < args.Length; i++)
        {
            if (args[i] == "--out" && i + 1 < args.Length) output = args[++i];
            else if (args[i] == "--json") json = true;
            else { stderr.WriteLine(ExperimentalHeightFieldArtUsage); return 1; }
        }
        if (!File.Exists(source) || string.IsNullOrWhiteSpace(output)) { stderr.WriteLine(ExperimentalHeightFieldArtUsage); return 1; }
        var compiled = PlasticShellFirmament.CompileFile(source);
        if (!compiled.IsSuccess || compiled.State is null)
        {
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "experimental heightfield-art", success = false, diagnostics = compiled.Diagnostics }, JsonOptions));
            else foreach (var diagnostic in compiled.Diagnostics) stderr.WriteLine($"- [{diagnostic.Severity}] {diagnostic.Code}: {diagnostic.Message}");
            return 1;
        }
        var art = PlasticShellHeightFieldArt.Export(compiled.State, compiled.ModelName);
        if (!art.IsSuccess || art.Step is null)
        {
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "experimental heightfield-art", success = false, diagnostics = art.Diagnostics }, JsonOptions));
            else foreach (var diagnostic in art.Diagnostics) stderr.WriteLine($"- [{diagnostic.Severity}] {diagnostic.Code}: {diagnostic.Message}");
            return 1;
        }
        var fullOutput = Path.GetFullPath(output); Directory.CreateDirectory(Path.GetDirectoryName(fullOutput)!); File.WriteAllText(fullOutput, art.Step);
        var report = new { command = "experimental heightfield-art", success = true, input = Path.GetFullPath(source), output = fullOutput, classification = "non-manufacturing mathematical computer art", productBuildUnaffected = true, art.BoundaryFaces, surfaceInventory = art.Inventory };
        if (json) stdout.WriteLine(JsonSerializer.Serialize(report, JsonOptions));
        else { stdout.WriteLine($"Happy little accident: {fullOutput}"); stdout.WriteLine("Classification: non-manufacturing mathematical computer art; normal PlasticShell build is unaffected."); }
        return 0;
    }

    private static int RunAsmInspect(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0]))
        {
            (args.Length == 0 ? stderr : stdout).WriteLine(AsmInspectUsage);
            return args.Length == 0 ? 1 : 0;
        }

        var path = args[0];
        var json = false;
        var profile = false;
        var repeat = 1;
        var repeatRequested = false;
        string? outputPath = null;
        for (var i = 1; i < args.Length; i++)
        {
            if (args[i] == "--json") json = true;
            else if (args[i] == "--profile") profile = true;
            else if (args[i] == "--repeat" && i + 1 < args.Length && int.TryParse(args[++i], out var count) && count is >= 1 and <= 16) { repeat = count; repeatRequested = true; }
            else if (args[i] == "--out" && i + 1 < args.Length) outputPath = args[++i];
            else { stderr.WriteLine(AsmInspectUsage); return 1; }
        }
        if (!File.Exists(path)) { stderr.WriteLine($"Assembly source '{path}' was not found."); return 1; }
        var sourceText = File.ReadAllText(path);
        var usesTemplateInstances = Regex.IsMatch(sourceText, @"<Part\s+[A-Za-z_]\w*\s*=\s*[A-Za-z_]\w*\s*<", RegexOptions.CultureInvariant);
        if (!usesTemplateInstances && !Path.GetExtension(path).Equals(".firmasm", StringComparison.OrdinalIgnoreCase) && (FirmamentSourceSpelling.Normalize(sourceText).Contains("Include", StringComparison.Ordinal) || sourceText.Contains("Inventory", StringComparison.Ordinal)))
            usesTemplateInstances = new AssemblyM0Parser().ParseFile(path).Source is { } imported && (imported.HasModuleBindings || NeedsMaterialization(imported.Root));
        static bool NeedsMaterialization(AssemblyMemberSource member) => member.Kind == AssemblyInstanceKind.Part && member.DefinitionIdentity.Contains('<')
            || member.Children.Any(NeedsMaterialization);
        var usesGearParts = GearAuthoring.ParseDefinitions(sourceText).Gears.Count > 0;
        var usesSheetMetalParts = sourceText.Contains("Use SheetMetal.ProductFamilies", StringComparison.Ordinal);
        AssemblyIr? assemblyIr;
        AssemblyGeometryArtifactIr? geometryArtifact;
        IReadOnlyList<AssemblyDiagnostic> assemblyDiagnostics;
        AssemblyPerformanceIr? assemblyPerformance;
        bool success;
        var builds = new List<object>();
        if (repeatRequested)
        {
            if (!FirmamentLanguageAnalysisService.HasAssemblyRoot(sourceText, path) || usesSheetMetalParts)
            { stderr.WriteLine("--repeat requires a canonical authored assembly using the ordinary M1 materializer."); return 1; }
            using var session = new FirmamentCompilationSession();
            AssemblyM1CompilationResult? last = null;
            for (var index = 0; index < repeat; index++)
            {
                var watch = System.Diagnostics.Stopwatch.StartNew();
                last = session.CompileFile(path);
                builds.Add(new { index, elapsedMilliseconds = watch.Elapsed.TotalMilliseconds, success = last.IsSuccess, reuse = last.Reuse, performance = profile ? last.Performance : null });
                if (!last.IsSuccess) break;
            }
            assemblyIr = last!.Ir; geometryArtifact = last.Geometry?.Artifact; assemblyDiagnostics = last.Diagnostics;
            assemblyPerformance = last.Performance; success = last.IsSuccess;
        }
        else if (string.Equals(Path.GetExtension(path), ".firmasm", StringComparison.OrdinalIgnoreCase) && !usesSheetMetalParts)
        {
            var document = new FirmamentAssemblyDocumentCompiler().CompileFile(path);
            assemblyIr = document.Compilation.Ir;
            geometryArtifact = document.Compilation.Geometry?.Artifact;
            assemblyDiagnostics = document.Compilation.Diagnostics;
            assemblyPerformance = document.Compilation.Performance;
            success = document.IsSuccess;
        }
        else if (usesTemplateInstances || usesGearParts || usesSheetMetalParts)
        {
            var m1 = usesSheetMetalParts ? EnclosureProductFamilies.CompileAssemblyFile(path) : new AssemblyM1Pipeline().CompileFile(path);
            assemblyIr = m1.Ir;
            geometryArtifact = m1.Geometry?.Artifact;
            assemblyDiagnostics = m1.Diagnostics;
            assemblyPerformance = m1.Performance;
            success = m1.IsSuccess;
        }
        else
        {
            var m0 = new AssemblyM0Pipeline().CompileFile(path);
            assemblyIr = m0.Ir;
            geometryArtifact = null;
            assemblyDiagnostics = m0.Diagnostics;
            assemblyPerformance = m0.Performance;
            success = m0.IsSuccess;
        }
        var reportJson = JsonSerializer.Serialize(new { success, assemblyIr, geometryArtifact, diagnostics = assemblyDiagnostics, performance = profile ? assemblyPerformance : null, builds }, JsonOptions);
        if (outputPath is not null)
        {
            var fullOutputPath = Path.GetFullPath(outputPath);
            Directory.CreateDirectory(Path.GetDirectoryName(fullOutputPath)!);
            File.WriteAllText(fullOutputPath, reportJson + Environment.NewLine);
        }
        if (json)
        {
            stdout.WriteLine(reportJson);
        }
        else if (assemblyIr is { } ir)
        {
            stdout.WriteLine($"Assembly: {ir.Name} ({ir.Schema})");
            stdout.WriteLine("Product tree:");
            foreach (var instance in ir.Instances.OrderBy(x => x.Path.Segments.Count).ThenBy(x => x.Path.ToString(), StringComparer.Ordinal))
                stdout.WriteLine($"{new string(' ', (instance.Path.Segments.Count - 1) * 2)}- {instance.Path.Segments[^1]} [{instance.Kind}] = {instance.DefinitionIdentity}; placement={instance.PlacementAuthority}");
            stdout.WriteLine("Mates:");
            foreach (var mate in ir.Mates.Concat((ir.AssemblyDefinitions ?? []).SelectMany(definition => definition.LocalMates)).DistinctBy(mate => mate.StableId))
            {
                var definition = ir.Interfaces.Single(item => item.StableId == mate.InterfaceStableId);
                stdout.WriteLine($"- {mate.Name}: Interface<{definition.Family}> {mate.InterfaceStableId} ({string.Join(", ", mate.Roles.Select(x => x.Role + "=" + x.ParticipantPath))}); status={mate.ValidationStatus}");
                foreach (var constraint in ir.PlacementConstraints.Concat((ir.AssemblyDefinitions ?? [])
                             .SelectMany(item => item.LocalPlacementConstraints ?? []))
                             .Where(constraint => constraint.MateStableId == mate.StableId))
                    stdout.WriteLine($"    Expanded Mate {constraint.Kind}: {constraint.FirstSemanticValueId} -> {constraint.SecondSemanticValueId}");
                foreach (var requirement in mate.RequirementResults ?? [])
                    stdout.WriteLine($"    Require {requirement.Name}: {requirement.Expression} ({requirement.Status})");
                if (mate.GearResult is { } gear)
                {
                    WriteGearEndpoint("A", gear.A);
                    WriteGearEndpoint("B", gear.B);
                    stdout.WriteLine($"    Derived: ratio={gear.Ratio:G6}; rotation-sign={gear.RotationSign}; center expected={gear.ExpectedCenterDistanceMm:G6}mm actual={gear.ActualCenterDistanceMm:G6}mm; {gear.CompatibilityStatus}");
                }
            }
            foreach (var joint in ir.Joints ?? [])
                stdout.WriteLine($"    Joint {joint.Name}: {joint.Family}; parent={joint.ParentOccurrenceId}; child={joint.ChildOccurrenceId}; DOF={joint.DegreesOfFreedom}; default={joint.DefaultState:G6}{(joint.Family == MechanicalInterfaceFamily.Revolute ? "deg" : joint.Family == MechanicalInterfaceFamily.Prismatic ? "mm" : "")}");
            var definitions = ir.AssemblyDefinitions ?? [];
            if (definitions.Count > 0)
            {
                stdout.WriteLine("Shared definitions:");
                foreach (var definition in definitions.OrderBy(item => item.DefinitionIdentity, StringComparer.Ordinal))
                {
                    var uses = ir.Instances.Count(item => item.DefinitionIdentity == definition.DefinitionIdentity);
                    stdout.WriteLine($"- {definition.DefinitionIdentity}: occurrences={uses}; local-instances={definition.LocalInstances.Count}; public=[{string.Join(",", definition.PublicSemantics.Select(item => item.ExposedName))}]");
                }
            }
            if (ir.SourceDependencies is { Count: > 0 })
            {
                stdout.WriteLine("Source dependencies:");
                foreach (var dependency in ir.SourceDependencies)
                    stdout.WriteLine($"- {(dependency.IsRoot ? "root" : "include")}: {dependency.Path}; sha256={dependency.Sha256}");
            }
            var datums = (ir.Datums ?? []).Concat((ir.AssemblyDefinitions ?? []).SelectMany(definition => definition.LocalDatums ?? []))
                .DistinctBy(datum => datum.SemanticPath).OrderBy(datum => datum.SemanticPath, StringComparer.Ordinal).ToArray();
            var rootDatums = datums.Where(datum => datum.SemanticPath.StartsWith(ir.Name + ".", StringComparison.Ordinal)).ToArray();
            if (rootDatums.Any(datum => datum.SemanticPath.Contains(".Datums.", StringComparison.Ordinal)))
                datums = rootDatums.Where(datum => datum.SemanticPath.Contains(".Datums.", StringComparison.Ordinal)).ToArray();
            else if (rootDatums.Length > 0)
                datums = rootDatums;
            if (datums.Length > 0)
            {
                stdout.WriteLine("Semantic datums:");
                foreach (var datum in datums) stdout.WriteLine($"- {datum.SemanticPath} [{datum.Kind}] id={datum.StableBindingId}");
            }
            var datumMates = (ir.DatumMateSolutions ?? []).Concat((ir.AssemblyDefinitions ?? []).SelectMany(definition => definition.LocalDatumMateSolutions ?? []))
                .DistinctBy(solution => (solution.MateStableId, solution.FirstDatumSemanticValueId, solution.SecondDatumSemanticValueId)).OrderBy(solution => solution.MateStableId, StringComparer.Ordinal).ToArray();
            if (datumMates.Length > 0)
            {
                stdout.WriteLine("Datum Mate solutions:");
                foreach (var solution in datumMates)
                {
                    var translation = solution.DerivedTransform is { Matrix.Length: >= 15 } transform
                        ? $"; translation=[{transform.Matrix[12]:G6},{transform.Matrix[13]:G6},{transform.Matrix[14]:G6}]mm"
                        : string.Empty;
                    stdout.WriteLine($"- {solution.MateStableId}: {solution.Orientation}; DOF={solution.ConstrainedDegreesOfFreedom}/6; {solution.Status}{translation}");
                }
            }
            if (geometryArtifact is not null)
            {
                stdout.WriteLine($"Executable geometry: {geometryArtifact.Instances.Count} instances, {geometryArtifact.Definitions.Count} definitions, sha256={geometryArtifact.DeterministicSha256}");
                foreach (var residual in geometryArtifact.MateResiduals)
                    stdout.WriteLine($"- residual {residual.ConstraintStableId}: position={residual.PositionResidualMm:G6}mm angle={residual.AngularResidualRadians:G6}rad {(residual.Passed ? "passed" : "failed")}");
                stdout.WriteLine("BOM:");
                foreach (var group in ir.Instances.Where(x => x.Kind == AssemblyInstanceKind.Part).GroupBy(x => x.DefinitionIdentity, StringComparer.Ordinal).OrderBy(x => x.Key, StringComparer.Ordinal))
                    stdout.WriteLine($"- {group.Key}: quantity={group.Count()} instances=[{string.Join(",", group.Select(x => x.Path))}]");
            }
            stdout.WriteLine("Tolerance stackups:");
            foreach (var stack in ir.ToleranceStackups)
                stdout.WriteLine($"- {stack.Name}: nominal={stack.Nominal:G6} {stack.Unit}, worst=[{stack.WorstCaseMinimum:G6},{stack.WorstCaseMaximum:G6}], {stack.Status}, contributors={stack.Contributions.Count}");
            var fits = ir.FitResults.Concat((ir.AssemblyDefinitions ?? []).SelectMany(definition => definition.LocalFitResults ?? []))
                .DistinctBy(fit => fit.MateStableId).OrderBy(fit => fit.MateStableId, StringComparer.Ordinal).ToArray();
            if (fits.Length > 0)
            {
                stdout.WriteLine("Fit evidence:");
                foreach (var fit in fits)
                    stdout.WriteLine($"- {fit.MateStableId}: nominal={fit.NominalClearance:G6}{fit.Unit}; envelope=[{fit.WorstCaseMinimum:G6},{fit.WorstCaseMaximum:G6}]{fit.Unit}; {fit.NominalState} -> {fit.VariationEnvelopeState}; penetration={fit.MaximumPenetration:G6}{fit.Unit}");
            }
            foreach (var diagnostic in assemblyDiagnostics)
                (diagnostic.Severity == AssemblyDiagnosticSeverity.Error ? stderr : stdout).WriteLine($"{diagnostic.Severity}: {diagnostic.Code}: {diagnostic.Message}");
        }
        else
        {
            foreach (var diagnostic in assemblyDiagnostics) stderr.WriteLine($"{diagnostic.Code}: {diagnostic.Message}");
        }
        return success ? 0 : 1;

        void WriteGearEndpoint(string role, GearEndpointIr endpoint) => stdout.WriteLine(
            $"    {role}: port={endpoint.ExposedPortPath}; source={endpoint.HierarchicalPath}; definition={endpoint.DefinitionIdentity}; occurrence={endpoint.OccurrenceIdentity}; family={endpoint.Family}; teeth={endpoint.Teeth}; module={endpoint.ModuleMm:G6}mm; pressure-angle={endpoint.PressureAngleDegrees:G6}deg; axis=[{string.Join(',', endpoint.Axis.Select(value => value.ToString("G6", System.Globalization.CultureInfo.InvariantCulture)))}]; phase={endpoint.PhaseDegrees:G6}deg");
    }

    private static int RunAsmExec(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0)
        {
            stderr.WriteLine(AsmExecUsage);
            stderr.WriteLine("Run 'aetheris asm --help' for examples.");
            return 1;
        }

        if (IsHelpFlag(args[0]))
        {
            WriteAsmHelp(stdout);
            return 0;
        }

        if (args[0].StartsWith("-", StringComparison.Ordinal))
        {
            stderr.WriteLine("Asm exec requires <file.firmasm> as the first argument.");
            stderr.WriteLine(AsmExecUsage);
            return 1;
        }

        var manifestPath = args[0];
        var json = false;
        for (var i = 1; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--json":
                    json = true;
                    break;
                case "-h":
                case "--help":
                    WriteAsmHelp(stdout);
                    return 0;
                default:
                    stderr.WriteLine($"Unknown asm exec option '{args[i]}'.");
                    stderr.WriteLine(AsmExecUsage);
                    return 1;
            }
        }

        var executor = new FirmasmAssemblyExecutor();
        var execute = executor.ExecuteFromFile(manifestPath);
        if (!execute.IsSuccess)
        {
            if (json)
            {
                stdout.WriteLine(JsonSerializer.Serialize(new
                {
                    success = false,
                    manifestPath = Path.GetFullPath(manifestPath),
                    diagnostics = execute.Diagnostics.Select(d => new { d.Source, d.Message, severity = d.Severity.ToString() })
                }, JsonOptions));
            }
            else
            {
                stderr.WriteLine("ASM execution failed:");
                foreach (var diagnostic in execute.Diagnostics)
                {
                    stderr.WriteLine($"- [{diagnostic.Severity}] {diagnostic.Source}: {diagnostic.Message}");
                }
            }

            return 1;
        }

        var analysis = StepAnalyzer.AnalyzeImportedBody(execute.Value.ComposedBody, Path.GetFullPath(manifestPath));
        if (json)
        {
            stdout.WriteLine(JsonSerializer.Serialize(new
            {
                success = true,
                manifestPath = execute.Value.LoadedAssembly.SourcePath,
                assemblyName = execute.Value.LoadedAssembly.Manifest.Assembly.Name,
                partCount = execute.Value.LoadedAssembly.LoadedParts.Count,
                instanceCount = execute.Value.Instances.Count,
                bodyCount = execute.Value.ComposedBody.Topology.Bodies.Count(),
                 shellCount = execute.Value.ComposedBody.Topology.Shells.Count(),
                 boundingBox = analysis.Summary.BoundingBox,
                 analysis,
                 diagnostics = execute.Diagnostics.Select(d => new { d.Source, d.Message, severity = d.Severity.ToString() })
            }, JsonOptions));
            return 0;
        }

        stdout.WriteLine($"ASM execution succeeded: {execute.Value.LoadedAssembly.Manifest.Assembly.Name}");
        foreach (var diagnostic in execute.Diagnostics)
            stderr.WriteLine($"- [{diagnostic.Severity}] {diagnostic.Source}: {diagnostic.Message}");
        stdout.WriteLine($"Parts: {execute.Value.LoadedAssembly.LoadedParts.Count}");
        stdout.WriteLine($"Instances: {execute.Value.Instances.Count}");
        stdout.WriteLine($"Bodies: {execute.Value.ComposedBody.Topology.Bodies.Count()}");
        return 0;
    }

    private static int RunAsmExport(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0)
        {
            stderr.WriteLine(AsmExportUsage);
            stderr.WriteLine("Run 'aetheris asm --help' for examples.");
            return 1;
        }

        if (IsHelpFlag(args[0]))
        {
            WriteAsmHelp(stdout);
            return 0;
        }

        if (args[0].StartsWith("-", StringComparison.Ordinal))
        {
            stderr.WriteLine("Asm export requires <file.firmasm> as the first argument.");
            stderr.WriteLine(AsmExportUsage);
            return 1;
        }

        var manifestPath = args[0];
        string? outputDirectory = null;
        var json = false;
        for (var i = 1; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--out" when i + 1 < args.Length:
                    outputDirectory = args[++i];
                    break;
                case "--out":
                    stderr.WriteLine("Asm export option --out requires a directory path.");
                    stderr.WriteLine(AsmExportUsage);
                    return 1;
                case "--json":
                    json = true;
                    break;
                case "-h":
                case "--help":
                    WriteAsmHelp(stdout);
                    return 0;
                default:
                    stderr.WriteLine($"Unknown asm export option '{args[i]}'.");
                    stderr.WriteLine(AsmExportUsage);
                    return 1;
            }
        }

        if (string.IsNullOrWhiteSpace(outputDirectory))
        {
            stderr.WriteLine("Asm export requires --out <directory>.");
            stderr.WriteLine(AsmExportUsage);
            return 1;
        }

        var exporter = new FirmasmAssemblyRoundtripExporter();
        var export = exporter.ExportFromFile(manifestPath, outputDirectory);
        if (!export.IsSuccess)
        {
            if (json)
            {
                stdout.WriteLine(JsonSerializer.Serialize(new
                {
                    success = false,
                    manifestPath = Path.GetFullPath(manifestPath),
                    outputDirectory = Path.GetFullPath(outputDirectory),
                    diagnostics = export.Diagnostics.Select(d => new { d.Source, d.Message, severity = d.Severity.ToString() })
                }, JsonOptions));
            }
            else
            {
                stderr.WriteLine("ASM export failed:");
                foreach (var diagnostic in export.Diagnostics)
                {
                    stderr.WriteLine($"- [{diagnostic.Severity}] {diagnostic.Source}: {diagnostic.Message}");
                }
            }

            return 1;
        }

        if (json)
        {
            stdout.WriteLine(JsonSerializer.Serialize(new
            {
                success = true,
                manifestPath = export.Value.SourceManifestPath,
                outputDirectory = export.Value.OutputDirectory,
                packageManifestPath = export.Value.PackageManifestPath,
                nativeAuthority = ".firmasm",
                exportShape = "step-instance-package",
                instanceCount = export.Value.InstanceCount,
                composedBodyCount = export.Value.ComposedBodyCount,
                exportedInstanceStepCount = export.Value.ExportedInstances.Count
            }, JsonOptions));
            return 0;
        }

        stdout.WriteLine($"ASM export succeeded: {export.Value.SourceManifestPath}");
        stdout.WriteLine($"Output directory: {export.Value.OutputDirectory}");
        stdout.WriteLine($"Exported instance STEP files: {export.Value.ExportedInstances.Count}");
        stdout.WriteLine($"Package manifest: {export.Value.PackageManifestPath}");
        return 0;
    }

    private static int RunAnalyzeMap(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0)
        {
            stderr.WriteLine(AnalyzeMapUsage);
            stderr.WriteLine("Run 'aetheris analyze map --help' for examples.");
            return 1;
        }

        if (IsHelpFlag(args[0]))
        {
            WriteAnalyzeMapHelp(stdout);
            return 0;
        }

        if (args[0].StartsWith("-", StringComparison.Ordinal))
        {
            stderr.WriteLine("Analyze map requires <file.step> as the first argument.");
            stderr.WriteLine(AnalyzeMapUsage);
            return 1;
        }

        var stepPath = args[0];
        OrthographicView? view = null;
        var viewOptionCount = 0;
        int? rows = null;
        int? cols = null;
        string? plane = null;
        string? direction = null;
        string? views = null;
        (double U, double V)? point = null;
        var json = false;
        var llm = false;
        var rankProbes = false;
        var evidenceBundle = false;

        for (var i = 1; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--top":
                    view = OrthographicView.Top;
                    viewOptionCount++;
                    break;
                case "--bottom":
                    view = OrthographicView.Bottom;
                    viewOptionCount++;
                    break;
                case "--front":
                    view = OrthographicView.Front;
                    viewOptionCount++;
                    break;
                case "--back":
                    view = OrthographicView.Back;
                    viewOptionCount++;
                    break;
                case "--left":
                    view = OrthographicView.Left;
                    viewOptionCount++;
                    break;
                case "--right":
                    view = OrthographicView.Right;
                    viewOptionCount++;
                    break;
                case "--rows" when i + 1 < args.Length && int.TryParse(args[++i], out var parsedRows):
                    rows = parsedRows;
                    break;
                case "--resolution" when i + 1 < args.Length && TryParseResolution(args[++i], out var parsedCols2, out var parsedRows2):
                    cols = parsedCols2;
                    rows = parsedRows2;
                    break;
                case "--resolution":
                    stderr.WriteLine("Analyze map option --resolution requires a value like 32x32.");
                    stderr.WriteLine(AnalyzeMapUsage);
                    return 1;
                case "--plane" when i + 1 < args.Length:
                    plane = args[++i];
                    break;
                case "--plane":
                    stderr.WriteLine("Analyze map option --plane requires xy, xz, or yz.");
                    stderr.WriteLine(AnalyzeMapUsage);
                    return 1;
                case "--direction" when i + 1 < args.Length:
                    direction = args[++i];
                    break;
                case "--views" when i + 1 < args.Length:
                    views = args[++i];
                    break;
                case "--views":
                    stderr.WriteLine("Analyze map option --views requires six.");
                    stderr.WriteLine(AnalyzeMapUsage);
                    return 1;
                case "--llm":
                case "--summary":
                    llm = true;
                    break;
                case "--rank-probes":
                    rankProbes = true;
                    llm = true;
                    break;
                case "--evidence-bundle":
                    evidenceBundle = true;
                    rankProbes = true;
                    llm = true;
                    break;
                case "--direction":
                    stderr.WriteLine("Analyze map option --direction requires +x, -x, +y, -y, +z, or -z.");
                    stderr.WriteLine(AnalyzeMapUsage);
                    return 1;
                case "--point" when i + 1 < args.Length && TryParsePoint(args[++i], out var parsedPoint):
                    point = parsedPoint;
                    rows ??= 1;
                    cols ??= 1;
                    break;
                case "--point":
                    stderr.WriteLine("Analyze map option --point requires a comma-separated coordinate like 3,4.");
                    stderr.WriteLine(AnalyzeMapUsage);
                    return 1;
                case "--rows":
                    stderr.WriteLine("Analyze map option --rows requires an integer value.");
                    stderr.WriteLine(AnalyzeMapUsage);
                    return 1;
                case "--cols" when i + 1 < args.Length && int.TryParse(args[++i], out var parsedCols):
                    cols = parsedCols;
                    break;
                case "--cols":
                    stderr.WriteLine("Analyze map option --cols requires an integer value.");
                    stderr.WriteLine(AnalyzeMapUsage);
                    return 1;
                case "--json":
                    json = true;
                    break;
                case "-h":
                case "--help":
                    WriteAnalyzeMapHelp(stdout);
                    return 0;
                default:
                    stderr.WriteLine($"Unknown analyze map option '{args[i]}'.");
                    stderr.WriteLine(AnalyzeMapUsage);
                    return 1;
            }
        }

        var sixViewMode = string.Equals(views, "six", StringComparison.OrdinalIgnoreCase);
        if (views is not null && !sixViewMode)
        {
            stderr.WriteLine("Analyze map option --views currently supports only 'six'.");
            stderr.WriteLine(AnalyzeMapUsage);
            return 1;
        }

        var legacyViewMode = plane is null && view.HasValue;
        if (legacyViewMode)
        {
            var legacyView = view.GetValueOrDefault();
            (plane, direction) = legacyView switch
            {
                OrthographicView.Top => ("xy", "-z"),
                OrthographicView.Bottom => ("xy", "+z"),
                OrthographicView.Front => ("xz", "-y"),
                OrthographicView.Back => ("xz", "+y"),
                OrthographicView.Left => ("yz", "+x"),
                OrthographicView.Right => ("yz", "-x"),
                _ => ("xy", "-z")
            };
        }

        if (!sixViewMode && (plane is null || direction is null || (viewOptionCount > 0 && viewOptionCount != 1)))
        {
            stderr.WriteLine("Analyze map requires --plane and --direction (or one legacy view option --top|--bottom|--front|--back|--left|--right).");
            return 1;
        }

        if (sixViewMode && (point.HasValue || plane is not null || direction is not null || viewOptionCount > 0 || !llm))
        {
            stderr.WriteLine("Analyze map --views six requires --llm or --summary and cannot be combined with --point, --plane, --direction, or legacy view flags.");
            return 1;
        }

        if (!rows.HasValue || !cols.HasValue)
        {
            stderr.WriteLine("Analyze map requires both --rows <N> and --cols <N>.");
            return 1;
        }

        if (rows <= 0 || cols <= 0)
        {
            stderr.WriteLine("Analyze map requires positive --rows and --cols values.");
            return 1;
        }

        object map;
        try
        {
            map = sixViewMode
                ? (rankProbes || evidenceBundle ? StepAnalyzer.AnalyzeSixViewMapEvidenceBundle(stepPath, cols.Value, rows.Value) : StepAnalyzer.AnalyzeSixViewMapSummary(stepPath, cols.Value, rows.Value))
                : legacyViewMode
                ? StepAnalyzer.AnalyzeMap(stepPath, view.GetValueOrDefault(), rows.Value, cols.Value)
                : StepAnalyzer.AnalyzeRayMap(stepPath, plane!, direction!, cols.Value, rows.Value, point);
        }
        catch (Exception ex)
        {
            if (!json)
            {
                stderr.WriteLine(ex.Message);
                return 1;
            }

            WriteAnalyzeFailureJson(stdout, stepPath, ex);
            return 1;
        }

        if (!json)
        {
            stderr.WriteLine("Analyze map currently requires --json output. Re-run with --json.");
            return 1;
        }

        stdout.WriteLine(JsonSerializer.Serialize(map, JsonOptions));
        return 0;
    }

    private static int RunAnalyzeCompound(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0]))
        {
            stdout.WriteLine("Inspect every exact rigid root in a STEP serialization without assigning Part or Assembly semantics.");
            stdout.WriteLine(AnalyzeCompoundUsage);
            return args.Length == 0 ? 1 : 0;
        }
        var json = args.Skip(1).Any(arg => arg == "--json");
        if (args.Skip(1).Any(arg => arg != "--json"))
        {
            stderr.WriteLine(AnalyzeCompoundUsage);
            return 1;
        }
        try
        {
            var result = StepAnalyzer.AnalyzeCompound(args[0]);
            if (json) stdout.WriteLine(JsonSerializer.Serialize(result, JsonOptions));
            else
            {
                stdout.WriteLine($"Roots: {result.RootCount}; solids: {result.SolidCount}; aggregate volume: {result.AggregateVolume?.ToString("G12", System.Globalization.CultureInfo.InvariantCulture) ?? "unavailable"}");
                foreach (var solid in result.Solids)
                    stdout.WriteLine($"  #{solid.RootEntityId}: solids={solid.SolidCount}, volume={solid.Volume?.ToString("G12", System.Globalization.CultureInfo.InvariantCulture) ?? "unavailable"}, center=({solid.PlacementCenter.X:G6},{solid.PlacementCenter.Y:G6},{solid.PlacementCenter.Z:G6})");
            }
            return 0;
        }
        catch (Exception ex)
        {
            WriteAnalyzeFailureJson(stdout, args[0], ex);
            return 1;
        }
    }

    private static int RunAnalyzeSection(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0)
        {
            stderr.WriteLine(AnalyzeSectionUsage);
            stderr.WriteLine("Run 'aetheris analyze section --help' for examples.");
            return 1;
        }

        if (IsHelpFlag(args[0]))
        {
            WriteAnalyzeSectionHelp(stdout);
            return 0;
        }

        if (args[0].StartsWith("-", StringComparison.Ordinal))
        {
            stderr.WriteLine("Analyze section requires <file.step> as the first argument.");
            stderr.WriteLine(AnalyzeSectionUsage);
            return 1;
        }

        var stepPath = args[0];
        SectionPlaneFamily? plane = null;
        var planeOptionCount = 0;
        double? offset = null;
        Point3D? customOrigin = null;
        Vector3D? customNormal = null;
        string? outputSvg = null;
        var json = false;

        for (var i = 1; i < args.Length; i++)
        {
            switch (args[i])
            {
                case "--xy":
                    plane = SectionPlaneFamily.XY;
                    planeOptionCount++;
                    break;
                case "--xz":
                    plane = SectionPlaneFamily.XZ;
                    planeOptionCount++;
                    break;
                case "--yz":
                    plane = SectionPlaneFamily.YZ;
                    planeOptionCount++;
                    break;
                case "--offset" when i + 1 < args.Length && double.TryParse(args[++i], out var parsedOffset):
                    offset = parsedOffset;
                    break;
                case "--offset":
                    stderr.WriteLine("Analyze section option --offset requires a numeric value.");
                    stderr.WriteLine(AnalyzeSectionUsage);
                    return 1;
                case "--origin" when i + 1 < args.Length && TryParseTriple(args[++i], out var parsedOrigin):
                    customOrigin = new Point3D(parsedOrigin.X, parsedOrigin.Y, parsedOrigin.Z);
                    break;
                case "--normal" when i + 1 < args.Length && TryParseTriple(args[++i], out var parsedNormal):
                    customNormal = new Vector3D(parsedNormal.X, parsedNormal.Y, parsedNormal.Z);
                    break;
                case "--origin":
                case "--normal":
                    stderr.WriteLine($"Analyze section option {args[i]} requires x,y,z numeric values.");
                    return 1;
                case "--out" when i + 1 < args.Length:
                    outputSvg = Path.GetFullPath(args[++i]);
                    break;
                case "--out":
                    stderr.WriteLine("Analyze section option --out requires an SVG path.");
                    return 1;
                case "--json":
                    json = true;
                    break;
                case "-h":
                case "--help":
                    WriteAnalyzeSectionHelp(stdout);
                    return 0;
                default:
                    stderr.WriteLine($"Unknown analyze section option '{args[i]}'.");
                    stderr.WriteLine(AnalyzeSectionUsage);
                    return 1;
            }
        }

        var custom = customOrigin.HasValue || customNormal.HasValue;
        if (custom && (!customOrigin.HasValue || !customNormal.HasValue || planeOptionCount != 0 || offset.HasValue))
        {
            stderr.WriteLine("Custom section requires both --origin and --normal, without a principal plane or --offset.");
            return 1;
        }
        if (!custom && (!plane.HasValue || planeOptionCount != 1 || !offset.HasValue))
        {
            stderr.WriteLine(planeOptionCount == 1 && !offset.HasValue
                ? "Analyze section requires --offset <value>."
                : "Principal section requires exactly one of --xy|--xz|--yz and --offset <value>.");
            return 1;
        }
        if (!json && outputSvg is null)
        {
            stderr.WriteLine("Analyze section requires --json, --out <section.svg>, or both.");
            return 1;
        }

        SectionAnalysisResult section;
        try
        {
            section = custom
                ? StepAnalyzer.AnalyzeSection(stepPath, customOrigin!.Value, customNormal!.Value)
                : StepAnalyzer.AnalyzeSection(stepPath, plane!.Value, offset!.Value);
        }
        catch (Exception ex)
        {
            WriteAnalyzeFailureJson(stdout, stepPath, ex);
            return 1;
        }

        if (outputSvg is not null)
        {
            Directory.CreateDirectory(Path.GetDirectoryName(outputSvg)!);
            File.WriteAllText(outputSvg, StepSectionSvgRenderer.Render(section));
        }
        if (json) stdout.WriteLine(JsonSerializer.Serialize(section, JsonOptions));
        else stdout.WriteLine($"Section SVG: {outputSvg}");
        return 0;
    }

    private static int RunSections(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0])) { stdout.WriteLine(SectionsUsage); return args.Length == 0 ? 1 : 0; }
        var step = args[0]; string? axis = null; string? levelText = null; var epsilon = .001d; var json = false;
        for (var i = 1; i < args.Length; i++)
            switch (args[i])
            {
                case "--axis" when i + 1 < args.Length: axis = args[++i]; break;
                case "--levels" when i + 1 < args.Length: levelText = args[++i]; break;
                case "--epsilon" when i + 1 < args.Length && double.TryParse(args[++i], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var e) && e > 0: epsilon = e; break;
                case "--json": json = true; break;
                default: stderr.WriteLine(SectionsUsage); return 1;
            }
        if (!json || !string.Equals(axis, "Z", StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(levelText)) { stderr.WriteLine(SectionsUsage); return 1; }
        var levels = levelText.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(x => double.TryParse(x, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var z) ? (double?)z : null).ToArray();
        if (levels.Length == 0 || levels.Any(x => x is null)) { stderr.WriteLine("--levels requires comma-separated numeric values."); return 1; }
        try
        {
            var result = new { artifact = Path.GetFullPath(step), axis = "Z", epsilon, policy = "Below/Above are requested level ± epsilon; At is never shifted and is diagnostic.", levels = levels.Select(x => new { requestedLevel = x!.Value, below = StepAnalyzer.AnalyzeSection(step, SectionPlaneFamily.XY, x.Value - epsilon), at = StepAnalyzer.AnalyzeSection(step, SectionPlaneFamily.XY, x.Value), above = StepAnalyzer.AnalyzeSection(step, SectionPlaneFamily.XY, x.Value + epsilon) }).ToArray() };
            stdout.WriteLine(JsonSerializer.Serialize(result, JsonOptions)); return 0;
        }
        catch (Exception ex) { stderr.WriteLine($"sections failed: {ex.Message}"); return 1; }
    }


    private static void WriteSummaryText(AnalyzeResult analysis, TextWriter stdout)
    {
        var summary = analysis.Summary;
        stdout.WriteLine($"Input file: {analysis.StepPath}");
        stdout.WriteLine("Success: yes");
        stdout.WriteLine($"Structural assessment: {summary.StructuralAssessment} ({summary.StructuralAssessmentBasis})");
        if (summary.ImportQualification is { } qualification)
            stdout.WriteLine($"Import qualification: {qualification.Status}; geometry={qualification.GeometryStatus}; display not assessed; missing pcurves={qualification.MissingPcurves}.");
        stdout.WriteLine($"Length unit: {summary.LengthUnit} ({summary.LengthUnitBasis})");
        stdout.WriteLine($"Bodies: {summary.BodyCount}");
        stdout.WriteLine($"Shells: {summary.ShellCount}");
        stdout.WriteLine($"Bounding box: {FormatBox(summary.BoundingBox)}");
        stdout.WriteLine($"Faces: {summary.FaceCount}");
        stdout.WriteLine($"Edges: {summary.EdgeCount}");
        stdout.WriteLine($"Vertices: {summary.VertexCount}");
        stdout.WriteLine($"Face IDs: min={summary.FaceIds.Min}, max={summary.FaceIds.Max}, count={summary.FaceIds.Count}, contiguous={summary.FaceIds.Contiguous}");
        stdout.WriteLine($"Edge IDs: min={summary.EdgeIds.Min}, max={summary.EdgeIds.Max}, count={summary.EdgeIds.Count}, contiguous={summary.EdgeIds.Contiguous}");
        stdout.WriteLine($"Vertex IDs: min={summary.VertexIds.Min}, max={summary.VertexIds.Max}, count={summary.VertexIds.Count}, contiguous={summary.VertexIds.Contiguous}");
        if (summary.BoundaryTopology is { } boundaries)
        {
            stdout.WriteLine($"Boundary topology: edge-loops={boundaries.EdgeLoopCount}; vertex-loops={boundaries.VertexLoopCount}; pcurves={boundaries.PcurveCount}; seam-pairs={boundaries.SeamPcurvePairCount}");
            if (boundaries.PcurveTypes.Count > 0)
                stdout.WriteLine($"Pcurve types: {string.Join(", ", boundaries.PcurveTypes.OrderBy(pair => pair.Key).Select(pair => $"{pair.Key}={pair.Value}"))}");
        }
        stdout.WriteLine("Surface Families:");
        foreach (var family in summary.SurfaceFamilies)
        {
            stdout.WriteLine($"  {family.Key}: {family.Value}");
        }

        if (analysis.SemanticPmi is { } semanticPmi)
        {
            stdout.WriteLine($"Semantic PMI: {semanticPmi.Items.Count} records (datums={semanticPmi.DatumCount}, dimensions={semanticPmi.DimensionCount}, geometricTolerances={semanticPmi.GeometricToleranceCount}, annotations={semanticPmi.AnnotationCount})");
            foreach (var item in semanticPmi.Items)
                stdout.WriteLine($"  {item.Kind} {item.Name}: target={item.Target}, value={FormatDouble(item.Value)}, quantity={item.Quantity?.ToString() ?? "n/a"}, datums=[{string.Join(",", item.DatumReferences)}]");
        }

        if (analysis.Face is not null)
        {
            stdout.WriteLine($"Face {analysis.Face.FaceId}: stepEntity={analysis.Face.StepEntity ?? "n/a"}, type={analysis.Face.SurfaceType ?? "n/a"}, status={analysis.Face.SurfaceStatus}, bbox={FormatBox(analysis.Face.BoundingBox)}, point={FormatPoint(analysis.Face.RepresentativePoint)}, anchor={FormatPoint(analysis.Face.AnchorPoint)}, apex={FormatPoint(analysis.Face.Apex)}, normal={FormatVector(analysis.Face.PlanarNormal)}, axis={FormatVector(analysis.Face.Axis)}, radius={FormatDouble(analysis.Face.Radius)}, placementRadius={FormatDouble(analysis.Face.PlacementRadius)}, majorRadius={FormatDouble(analysis.Face.MajorRadius)}, minorRadius={FormatDouble(analysis.Face.MinorRadius)}, semiAngleRadians={FormatDouble(analysis.Face.SemiAngleRadians)}, edges=[{string.Join(",", analysis.Face.AdjacentEdgeIds)}]");
        }

        if (analysis.Edge is not null)
        {
            stdout.WriteLine($"Edge {analysis.Edge.EdgeId}: curve={analysis.Edge.CurveType}, start={analysis.Edge.StartVertexId}:{FormatPoint(analysis.Edge.StartVertex)}, end={analysis.Edge.EndVertexId}:{FormatPoint(analysis.Edge.EndVertex)}, faces=[{string.Join(",", analysis.Edge.AdjacentFaceIds)}], parameterRange={FormatDouble(analysis.Edge.ParameterRange)}, arcLength={FormatDouble(analysis.Edge.ArcLength)}, arcLengthStatus={analysis.Edge.ArcLengthStatus}");
        }

        if (analysis.Vertex is not null)
        {
            stdout.WriteLine($"Vertex {analysis.Vertex.VertexId}: xyz={FormatPoint(analysis.Vertex.Position)}, edges=[{string.Join(",", analysis.Vertex.IncidentEdgeIds)}]");
        }

        if (analysis.Notes.Count > 0)
        {
            stdout.WriteLine("Notes:");
            foreach (var note in analysis.Notes)
            {
                stdout.WriteLine($"  - {note}");
            }
        }
    }

    private static void WriteAnalyzeFailureText(TextWriter stderr, string stepPath, Exception exception)
    {
        var fullPath = Path.GetFullPath(stepPath);
        if (exception is not StepAnalysisImportException importFailure)
        {
            stderr.WriteLine($"Analyze failed for: {fullPath}");
            stderr.WriteLine($"Reason: {exception.Message}");
            return;
        }

        var multiRootDiagnostic = importFailure.Diagnostics.FirstOrDefault(d => string.Equals(d.Source, "Importer.AssemblyLike.StepMultiRoot", StringComparison.Ordinal));
        if (multiRootDiagnostic is not null)
        {
            var rigidRootCount = CountExactBrepRigidRoots(multiRootDiagnostic.Message);
            stderr.WriteLine($"Input file: {fullPath}");
            stderr.WriteLine("Success: no");
            stderr.WriteLine("Classification: assembly-like STEP (multi-root exact BRep solids).");
            if (rigidRootCount.HasValue)
            {
                stderr.WriteLine($"Detected exact BRep rigid roots: {rigidRootCount.Value}");
            }

            stderr.WriteLine("Guidance: Use the assembly extraction/import workflow for this STEP input.");
            stderr.WriteLine($"Reason: {multiRootDiagnostic.Message}");
            return;
        }

        stderr.WriteLine($"Analyze failed for: {fullPath}");
        stderr.WriteLine("Reason: STEP import failure.");
        foreach (var diagnostic in importFailure.Diagnostics)
        {
            stderr.WriteLine($"- [{diagnostic.Severity}] {diagnostic.Source}: {diagnostic.Message}");
        }
    }

    private static int UnknownCommand(string command, TextWriter stderr)
    {
        stderr.WriteLine($"Unknown command '{command}'. Expected one of: validate, build, mesh, reconstruct, drawing, inspect, analyze, verify, view.");
        stderr.WriteLine("Run 'aetheris --help' for usage and examples.");
        return 1;
    }

    private static int RunAnalyzeAssembly(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0])) { (args.Length == 0 ? stderr : stdout).WriteLine(AnalyzeAssemblyUsage); return args.Length == 0 ? 1 : 0; }
        if (args.Length > 2 || args.Length == 2 && args[1] != "--json" || !File.Exists(args[0]))
        {
            stderr.WriteLine(AnalyzeAssemblyUsage);
            return 1;
        }
        var stepText = File.ReadAllText(args[0]);
        var imported = Step242AssemblyImporter.Import(stepText);
        if (!imported.IsSuccess)
        {
            foreach (var diagnostic in imported.Diagnostics) stderr.WriteLine($"{diagnostic.Source}: {diagnostic.Message}");
            return 1;
        }
        var structure = imported.Value;
        var definitions = structure.Definitions.ToDictionary(item => item.StableId, StringComparer.Ordinal);
        var occurrences = structure.Occurrences.ToDictionary(item => item.StableId, StringComparer.Ordinal);
        var world = new Dictionary<string, Transform3D>(StringComparer.Ordinal);
        var depths = new Dictionary<string, int>(StringComparer.Ordinal);
        Transform3D World(Step242ImportedProductOccurrence occurrence)
        {
            if (world.TryGetValue(occurrence.StableId, out var cached)) return cached;
            var local = Transform3D.FromRowMajor(occurrence.LocalTransform);
            return world[occurrence.StableId] = occurrence.ParentStableId is null ? local : local * World(occurrences[occurrence.ParentStableId]);
        }
        int Depth(Step242ImportedProductOccurrence occurrence)
        {
            if (depths.TryGetValue(occurrence.StableId, out var cached)) return cached;
            return depths[occurrence.StableId] = occurrence.ParentStableId is null ? 1 : 1 + Depth(occurrences[occurrence.ParentStableId]);
        }
        var points = new List<Point3D>();
        foreach (var occurrence in structure.Occurrences)
        {
            var body = definitions[occurrence.DefinitionStableId].Geometry;
            if (body is null) continue;
            var placement = World(occurrence);
            foreach (var vertex in body.Topology.Vertices)
                if (body.TryGetVertexPoint(vertex.Id, out var point)) points.Add(placement.Apply(point));
        }
        var assemblyName = definitions.GetValueOrDefault(structure.RootDefinitionStableId)?.Name ?? "RecoveredMultiBodyAssembly";
        var report = new {
            command = "analyze assembly", success = true, assemblyName, provenance = structure.Provenance,
            definitionCount = structure.Definitions.Count(item => item.Geometry is not null),
            occurrenceCount = structure.Occurrences.Count,
            subassemblyCount = structure.Occurrences.Count(item => definitions[item.DefinitionStableId].Geometry is null),
            bodyCount = structure.Occurrences.Count(item => definitions[item.DefinitionStableId].Geometry is not null),
            repeatedInstanceCount = structure.Occurrences.Where(item => definitions[item.DefinitionStableId].Geometry is not null)
                .GroupBy(item => item.DefinitionStableId).Sum(group => Math.Max(0, group.Count() - 1)),
            maxHierarchyDepth = structure.Occurrences.Count == 0 ? 0 : structure.Occurrences.Max(Depth),
            assemblyBoundingBox = points.Count == 0 ? null : new {
                minimum = new[] { points.Min(p => p.X), points.Min(p => p.Y), points.Min(p => p.Z) },
                maximum = new[] { points.Max(p => p.X), points.Max(p => p.Y), points.Max(p => p.Z) }
            },
            importStatus = structure.Definitions.Where(d => d.Geometry is not null)
                .Select(d => d.Geometry!.ImportQualification?.Status ?? Aetheris.Kernel.Core.Import.ImportQualificationStatus.Inspectable)
                .DefaultIfEmpty(Aetheris.Kernel.Core.Import.ImportQualificationStatus.Failed).Max().ToString(),
            importQualifications = structure.Definitions.Where(d => d.Geometry is not null)
                .Select(d => new { d.StableId, Qualification = d.Geometry!.ImportQualification }),
            performance = structure.Performance,
            semanticPmi = Step242SemanticPmiInspector.Inspect(stepText),
            definitions = structure.Definitions.Select(item => new { item.StableId, item.Name, hasGeometry = item.Geometry is not null, item.ProductDefinitionEntityId }).ToArray(),
            occurrences = structure.Occurrences.Select(item => new { item.StableId, item.Name, item.ParentStableId, item.DefinitionStableId,
                item.LocalTransform, worldTransform = World(item).ToRowMajor(), item.StepEntityId }).ToArray()
        };
        stdout.WriteLine(args.Length == 2 ? JsonSerializer.Serialize(report, JsonOptions)
            : $"Assembly '{assemblyName}': {report.definitionCount} definitions, {report.occurrenceCount} occurrences, {report.subassemblyCount} subassemblies, {report.repeatedInstanceCount} repeated instances; bbox {string.Join(",", report.assemblyBoundingBox?.minimum ?? [])} to {string.Join(",", report.assemblyBoundingBox?.maximum ?? [])}.");
        return 0;
    }

    private static int RunAsmImportStep(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0])) { (args.Length == 0 ? stderr : stdout).WriteLine(AsmImportStepUsage); return args.Length == 0 ? 1 : 0; }
        string? output = null; var json = false;
        for (var i = 1; i < args.Length; i++) if (args[i] == "--out" && i + 1 < args.Length) output = args[++i]; else if (args[i] == "--json") json = true; else { stderr.WriteLine(AsmImportStepUsage); return 1; }
        if (output is null || !File.Exists(args[0])) { stderr.WriteLine(AsmImportStepUsage); return 1; }
        var result = Step242FirmasmPackageImporter.Import(args[0], output);
        if (!result.IsSuccess) { foreach (var diagnostic in result.Diagnostics) stderr.WriteLine($"{diagnostic.Source}: {diagnostic.Message}"); return 1; }
        var structure = result.Value.ProductStructure;
        var definitions = structure.Definitions.ToDictionary(item => item.StableId, StringComparer.Ordinal);
        var occurrences = structure.Occurrences.ToDictionary(item => item.StableId, StringComparer.Ordinal);
        var world = new Dictionary<string, Transform3D>(StringComparer.Ordinal);
        var depths = new Dictionary<string, int>(StringComparer.Ordinal);
        Transform3D World(Step242ImportedProductOccurrence occurrence)
        {
            if (world.TryGetValue(occurrence.StableId, out var cached)) return cached;
            var local = Transform3D.FromRowMajor(occurrence.LocalTransform);
            return world[occurrence.StableId] = occurrence.ParentStableId is null ? local : local * World(occurrences[occurrence.ParentStableId]);
        }
        int Depth(Step242ImportedProductOccurrence occurrence)
        {
            if (depths.TryGetValue(occurrence.StableId, out var cached)) return cached;
            return depths[occurrence.StableId] = occurrence.ParentStableId is null ? 1 : 1 + Depth(occurrences[occurrence.ParentStableId]);
        }
        var points = new List<Point3D>();
        foreach (var occurrence in structure.Occurrences)
        {
            var body = definitions[occurrence.DefinitionStableId].Geometry;
            if (body is null) continue;
            var placement = World(occurrence);
            foreach (var vertex in body.Topology.Vertices)
                if (body.TryGetVertexPoint(vertex.Id, out var point)) points.Add(placement.Apply(point));
        }
        var assemblyName = definitions.GetValueOrDefault(structure.RootDefinitionStableId)?.Name ?? "ImportedAssembly";
        var report = new {
            success = true, result.Value.FirmasmPath, result.Value.ManifestPath, assemblyName,
            provenance = structure.Provenance,
            definitionCount = structure.Definitions.Count(item => item.Geometry is not null),
            occurrenceCount = structure.Occurrences.Count,
            subassemblyCount = structure.Occurrences.Count(item => definitions[item.DefinitionStableId].Geometry is null),
            bodyCount = structure.Occurrences.Count(item => definitions[item.DefinitionStableId].Geometry is not null),
            repeatedInstanceCount = structure.Occurrences.Where(item => definitions[item.DefinitionStableId].Geometry is not null)
                .GroupBy(item => item.DefinitionStableId).Sum(group => Math.Max(0, group.Count() - 1)),
            maxHierarchyDepth = structure.Occurrences.Count == 0 ? 0 : structure.Occurrences.Max(Depth),
            assemblyBoundingBox = points.Count == 0 ? null : new {
                minimum = new[] { points.Min(p => p.X), points.Min(p => p.Y), points.Min(p => p.Z) },
                maximum = new[] { points.Max(p => p.X), points.Max(p => p.Y), points.Max(p => p.Z) }
            },
            performance = structure.Performance,
            definitions = structure.Definitions.Select(item => new { item.StableId, item.Name, hasGeometry = item.Geometry is not null, item.ProductDefinitionEntityId }).ToArray(),
            occurrences = structure.Occurrences.Select(item => new { item.StableId, item.Name, item.ParentStableId, item.DefinitionStableId,
                item.LocalTransform, worldTransform = World(item).ToRowMajor(), item.StepEntityId }).ToArray(),
            result.Value.FirmasmSha256
        };
        stdout.WriteLine(json ? JsonSerializer.Serialize(report, JsonOptions) : $"Imported AP242 assembly '{assemblyName}' to {result.Value.FirmasmPath} ({report.definitionCount} definitions, {report.occurrenceCount} occurrences, {report.subassemblyCount} subassemblies; bbox {string.Join(",", report.assemblyBoundingBox?.minimum ?? [])} to {string.Join(",", report.assemblyBoundingBox?.maximum ?? [])}).");
        return 0;
    }

    private static int RunAsmExportAp242(string[] args, TextWriter stdout, TextWriter stderr)
    {
        if (args.Length == 0 || IsHelpFlag(args[0])) { (args.Length == 0 ? stderr : stdout).WriteLine(AsmExportAp242Usage); return args.Length == 0 ? 1 : 0; }
        string? output = null; var json = false;
        for (var i = 1; i < args.Length; i++) if (args[i] == "--out" && i + 1 < args.Length) output = args[++i]; else if (args[i] == "--json") json = true; else { stderr.WriteLine(AsmExportAp242Usage); return 1; }
        if (output is null || !File.Exists(args[0])) { stderr.WriteLine(AsmExportAp242Usage); return 1; }
        var sourceText = File.ReadAllText(args[0]);
        var usesSheetMetalParts = sourceText.Contains("Use SheetMetal.ProductFamilies", StringComparison.Ordinal);
        var compilation = string.Equals(Path.GetExtension(args[0]), ".firmasm", StringComparison.OrdinalIgnoreCase) && !usesSheetMetalParts
            ? new FirmamentAssemblyDocumentCompiler().CompileFile(args[0]).Compilation
            : usesSheetMetalParts ? EnclosureProductFamilies.CompileAssemblyFile(args[0]) : new AssemblyM1Pipeline().CompileFile(args[0]);
        if (!compilation.IsSuccess)
        {
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = false, diagnostics = compilation.Diagnostics }, JsonOptions));
            else foreach (var diagnostic in compilation.Diagnostics)
            {
                var span = diagnostic.SourceSpan;
                var file = span?.Source ?? args[0];
                var text = File.Exists(file) ? File.ReadAllText(file) : null;
                var presented = FirmamentBuildAdmissionValidation.Locate(new(diagnostic.Code,
                    diagnostic.Severity == AssemblyDiagnosticSeverity.Error ? "error" : "warning", diagnostic.Message)
                    { SourceSpan = span is null ? null : new(span.Start, span.Length), LocationNote = diagnostic.LocationNote }, text, file);
                stderr.WriteLine($"{file}:{presented.Line}:{presented.Column}: {presented.Severity} {diagnostic.Code}: {diagnostic.Message}");
            }
            return 1;
        }
        var export = AssemblyIrAp242Exporter.Export(compilation);
        if (!export.IsSuccess)
        {
            var diagnostics = export.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, args[0], sourceText)).ToArray();
            if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = false, diagnostics }, JsonOptions));
            else foreach (var diagnostic in diagnostics) stderr.WriteLine($"{diagnostic.SourceFile}:{diagnostic.Line}:{diagnostic.Column}: {diagnostic.Severity} {diagnostic.Code}: {diagnostic.Message}");
            return 1;
        }
        var fullOutput = Path.GetFullPath(output); Directory.CreateDirectory(Path.GetDirectoryName(fullOutput)!); File.WriteAllText(fullOutput, export.Value);
        var hash = Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(export.Value)));
        stdout.WriteLine(json ? JsonSerializer.Serialize(new { success = true, output = fullOutput, sha256 = hash, occurrenceCount = compilation.Ir!.Instances.Count - 1, definitionCount = compilation.Geometry!.Artifact.Definitions.Count + (compilation.Ir.AssemblyDefinitions?.Count ?? 0) }, JsonOptions) : $"Exported native AP242 assembly: {fullOutput} sha256={hash}");
        return 0;
    }

    private static bool IsTopLevelHelpRequest(string value) =>
        IsHelpFlag(value)
        || string.Equals(value, "help", StringComparison.Ordinal);

    private static bool IsHelpFlag(string value) =>
        string.Equals(value, "--help", StringComparison.Ordinal)
        || string.Equals(value, "-h", StringComparison.Ordinal);

    private static bool TryParseResolution(string value, out int cols, out int rows)
    {
        cols = 0;
        rows = 0;
        var parts = value.Split('x', 'X');
        return parts.Length == 2
            && int.TryParse(parts[0], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out cols)
            && int.TryParse(parts[1], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out rows);
    }

    private static bool TryParsePoint(string value, out (double U, double V) point)
    {
        point = default;
        var parts = value.Split(',');
        if (parts.Length != 2) return false;
        if (!double.TryParse(parts[0], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var u)) return false;
        if (!double.TryParse(parts[1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var v)) return false;
        point = (u, v);
        return true;
    }

    private static bool TryParseTriple(string value, out (double X, double Y, double Z) triple)
    {
        triple = default;
        var parts = value.Split(',');
        return parts.Length == 3
            && double.TryParse(parts[0], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out triple.X)
            && double.TryParse(parts[1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out triple.Y)
            && double.TryParse(parts[2], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out triple.Z)
            && double.IsFinite(triple.X) && double.IsFinite(triple.Y) && double.IsFinite(triple.Z);
    }

    private static bool IsVersionFlag(string value) =>
        string.Equals(value, "--version", StringComparison.Ordinal)
        || string.Equals(value, "-v", StringComparison.Ordinal);

    private static string GetDisplayVersion()
    {
        var assembly = typeof(CliRunner).Assembly;
        var informational = assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyInformationalVersionAttribute), inherit: false)
            .OfType<System.Reflection.AssemblyInformationalVersionAttribute>()
            .SingleOrDefault()?.InformationalVersion;
        return string.IsNullOrWhiteSpace(informational)
            ? assembly.GetName().Version?.ToString() ?? "unknown"
            : informational.Split('+', 2)[0];
    }

    private static void WriteTopLevelHelp(TextWriter stdout)
    {
        stdout.WriteLine("Aetheris — exact code-first CAD");
        stdout.WriteLine();
        stdout.WriteLine(TopLevelUsage);
        stdout.WriteLine();
        stdout.WriteLine("Commands:");
        stdout.WriteLine("  validate   Validate source through its engineering admission path.");
        stdout.WriteLine("  format     Prefer mixed-case vocabulary spellings; preserve layout and authored names.");
        stdout.WriteLine("  build      Compile Firmament to exact STEP AP242.");
        stdout.WriteLine("  mesh       Export a supported exact B-rep as STL or topology-preserving OBJ.");
        stdout.WriteLine("  view       Build/open a model in Cadmata.");
        stdout.WriteLine("  imported-features Discover proved imported-hole candidates and build named revision plans.");
        stdout.WriteLine("  lock          Generate or explicitly update firmament.lock.toml dependency receipts.");
        stdout.WriteLine("  inspect    Inspect Firmament semantics or STEP topology.");
        stdout.WriteLine("  measure    Measure a compiled part and print assertion templates without claiming its assertions passed.");
        stdout.WriteLine("  3DM interop   Optional aetheris-3dm tool: inspect/recover Rhino geometry and bind qualified BReps to STEP.");
        stdout.WriteLine("  analyze    Analyze STEP topology and analytic surfaces.");
        stdout.WriteLine("  fea        Compile and solve a Firmament linear-elastic analysis and export Abaqus verification input.");
        stdout.WriteLine("  drawing    Compile production drawings or inspect/highlight PDFs with source-linked Drawing Notes.");
        stdout.WriteLine("  asm        Inspect, execute, import, and export Firmament V2 assemblies.");
        stdout.WriteLine("  scene      Inspect spatial scenes and export OpenUSD or GLB.");
        stdout.WriteLine("  garment    Compile panels and stitches, export patterns, and drape on a humanoid.");
        stdout.WriteLine("  modules    Inspect built-in engineering Modules and capabilities.");
        stdout.WriteLine("  sheetmetal Inspect/recover sheet semantics and generate manufacturing flat-pattern SVG.");
        stdout.WriteLine("  sculpture  Build bounded non-manufacturing virtual sculpture artifacts.");
        stdout.WriteLine("  section-chain  Build bounded G0/G1 SectionChain qualification artifacts.");
        stdout.WriteLine("  wireframe  Render a deterministic trim-aware SVG preview from a STEP BRep.");
        stdout.WriteLine("  verify     Build/reimport and verify a model.");
        stdout.WriteLine("  reconstruct  Experimentally reconstruct a structured mesh from triangle PLY input.");
        stdout.WriteLine("  continuum    Run bounded point-torus queries or sharp sampled-grid contouring.");
        stdout.WriteLine();
        stdout.WriteLine("Global options:");
        stdout.WriteLine("  -h, --help       Show help.");
        stdout.WriteLine("  -v, --version    Show CLI version.");
        stdout.WriteLine();
        stdout.WriteLine("Examples:");
        stdout.WriteLine("  aetheris validate bracket.firmament");
        stdout.WriteLine("  aetheris build bracket.firmament");
        stdout.WriteLine("  aetheris view bracket.firmament");
        stdout.WriteLine("  aetheris analyze imported.step --json");
        stdout.WriteLine("  aetheris fea plate-with-hole.firmament --out-dir artifacts --json");
        stdout.WriteLine("  aetheris drawing compile bearing-block-drawing.firmament --out-dir artifacts/drawing --json");
        stdout.WriteLine("  aetheris drawing notes create engineering-drawing.pdf --out drawing-notes --json");
        stdout.WriteLine("  aetheris asm inspect bearing-module.firmament --json");
        stdout.WriteLine("  aetheris sheetmetal flatten bracket.firmament --step bracket-flat.step --svg bracket-flat.svg --json");
        stdout.WriteLine("  aetheris sculpture build fixtures/Canonical/VirtualSculpture/sol-1.sculpture.json");
        stdout.WriteLine("  aetheris section-chain build flagship --json");
        stdout.WriteLine("  aetheris wireframe model.step --out model.wireframe.svg --view iso --density 8");
        stdout.WriteLine("  aetheris reconstruct mesh scan.ply --mode fast --out scan-remesh.obj --report scan-report.json");
        stdout.WriteLine("  aetheris continuum --help");
        stdout.WriteLine();
        stdout.WriteLine("Run 'aetheris <command> --help' for command-specific usage.");
    }

    private static void WriteSculptureHelp(TextWriter stdout)
    {
        stdout.WriteLine("Build the bounded ART-X0 flagship virtual sculpture, Sol 1.");
        stdout.WriteLine("This lane is explicitly non-manufacturing and does not alter Firmament engineering domains.");
        stdout.WriteLine();
        stdout.WriteLine(SculptureUsage);
        stdout.WriteLine("  --out <path>       STEP/AP242 assembly output; defaults under artifacts/local/virtual-sculpture/.");
        stdout.WriteLine("  --evidence <path>  Structured deterministic and representation evidence JSON.");
        stdout.WriteLine("  --preview <path>   Deterministic authored SVG composition preview.");
        stdout.WriteLine("  --json             Emit machine-readable command output.");
    }

    private static void WriteBuildHelp(TextWriter stdout)
    {
        stdout.WriteLine("Build canonical Firmament V2 .firmament input into STEP output.");
        stdout.WriteLine("Explicitly versioned Firmament V1 TOON/JSON files remain readable through the historical compatibility route and emit one warning.");
        stdout.WriteLine("Legacy JSON .firmasm is a separate assembly compatibility format; inspect or export it with 'aetheris asm'.");
        stdout.WriteLine();
        stdout.WriteLine(BuildUsage);
        stdout.WriteLine();
        stdout.WriteLine("Options:");
        stdout.WriteLine("  --output <path> Optional output STEP path; defaults to a .step file beside the source.");
        stdout.WriteLine("  --locked        Require firmament.lock.toml; an existing lock is always checked.");
        stdout.WriteLine("  --json         Emit machine-readable success/failure JSON.");
        stdout.WriteLine("  -h, --help     Show this help.");
        stdout.WriteLine();
        stdout.WriteLine("Example:");
        stdout.WriteLine("  aetheris build part.firmament");
        stdout.WriteLine("  aetheris build part.firmament --output out/part.step --json");
    }

    private static void WriteMatchHelp(TextWriter stdout)
    {
        stdout.WriteLine("Match a compile-time Concept Struct against observed STEP geometry.");
        stdout.WriteLine("This does not reconstruct the original feature history.");
        stdout.WriteLine();
        stdout.WriteLine(MatchUsage);
        stdout.WriteLine();
        stdout.WriteLine("Supported M5 evidence: body bounds, analytic planar faces, cylindrical axes, and declared hole-center point sets.");
        stdout.WriteLine("Use `Match { MountPoints As HoleCenters { Diameter: 8.5mm Axis: +Z Kind: Through } }` in the source for point-set hole matching.");
        stdout.WriteLine("Matched and Partial exit 0; Conflicted or invalid input exits 1.");
    }

    private static void WriteValidateHelp(TextWriter stdout)
    {
        stdout.WriteLine("Check V2 syntax and binding, then run engineering compilation to verify build admission.");
        stdout.WriteLine("Generic V2 validation includes in-memory geometry/STEP preflight and writes no output file. Domain-specific reports retain their stated validation scope.");
        stdout.WriteLine();
        stdout.WriteLine(ValidateUsage);
        stdout.WriteLine("  --json                Emit Firmament V2 validation report JSON, including validation level and parser route.");
        stdout.WriteLine("  --explain             Show V2 parser route, admission level and available instance counts.");
        stdout.WriteLine("  --shadow              Developer report with separate original-source AST, bounded comparison and normal production validation.");
        stdout.WriteLine("  --ast                 Include the detailed AST with --shadow. Structural parsing does not establish semantic admission.");
        stdout.WriteLine("  --parse-only          Use an available static analyzer; success is labelled parsed-not-built.");
        stdout.WriteLine("  --locked              Require firmament.lock.toml; an existing lock is always checked.");
        stdout.WriteLine("  --forge-pack <path>   Load a trusted local .NET assembly containing IForgeConceptPack implementations. This executes local code; Aetheris does not sandbox external packs. Do not load untrusted packs.");
    }

    private static void WriteSheetMetalHelp(TextWriter stdout)
    {
        stdout.WriteLine("Recover bounded constant-thickness sheet, planar regions, cylindrical bends, and cuts from ordinary STEP, or compile the SheetMetal Firmament V2 module construct.");
        stdout.WriteLine();
        stdout.WriteLine(SheetMetalUsage);
        stdout.WriteLine();
        stdout.WriteLine("  inspect                 Print a compact recognition, bend-evidence, flat-status, DFM, and timing summary.");
        stdout.WriteLine("  recognize               Separate machine bend candidates from a validated, editable recognition plan.");
        stdout.WriteLine("  recover-flat             Unfold accepted imported bends into a source-derived geometric mid-surface reference.");
        stdout.WriteLine("  compare-flat             Compare a recovered source reference directly with a native Firmament flat.");
        stdout.WriteLine("  paths                   List stable authored Sheet Metal Concept Paths, capabilities, and formed/flat correspondence.");
        stdout.WriteLine("  recover                 Emit forensic summary JSON, editable recovered draft, and concise LLM/engineer reconstruction brief.");
        stdout.WriteLine("  compare                 Compare source and reconstructed intent with localized formed, bend, feature, and flat residuals.");
        stdout.WriteLine("  flatten                 Run recovery once and emit manufacturing and review artifacts from the same flat-pattern IR.");
        stdout.WriteLine("  --step <flat.step>      Write the thickness-bearing flat solid through the real AP242 BRep exporter.");
        stdout.WriteLine("  --firmament <file>      Write explicit recovered regions, bends, cuts, evidence bindings, and policy.");
        stdout.WriteLine("  --svg <flat.svg>        Write the secondary review drawing (--output remains an alias).");
        stdout.WriteLine("  --k-factor <0..1>       Override the source neutral-axis policy (STEP default 0.5).");
        stdout.WriteLine("  --json                  Emit compact deterministic JSON.");
        stdout.WriteLine();
        stdout.WriteLine("Examples:");
        stdout.WriteLine("  aetheris sheetmetal recognize part.step --plan artifacts/recognition-plan.json --json");
        stdout.WriteLine("  aetheris sheetmetal recover-flat part.step --recognition-plan artifacts/recognition-plan.json --out-dir artifacts/recovered-flat --json");
        stdout.WriteLine("  aetheris sheetmetal compare-flat artifacts/recovered-flat/recovered-flat.json reconstructed.firmament --json");
        stdout.WriteLine("  aetheris sheetmetal inspect testdata/step242/nist/CTC/nist_ctc_03_asme1_ap242-e2.stp");
        stdout.WriteLine("  aetheris sheetmetal paths fixtures/Canonical/SheetMetal/electronics-tray.firmament");
        stdout.WriteLine("  aetheris sheetmetal recover part.step --out-dir artifacts/recovery --json");
        stdout.WriteLine("  aetheris sheetmetal compare part.step reconstructed.firmament --json");
        stdout.WriteLine("  aetheris sheetmetal flatten testdata/step242/nist/CTC/nist_ctc_03_asme1_ap242-e2.stp --step artifacts/ctc03-flat.step --firmament artifacts/ctc03-recovered.firmament --svg artifacts/ctc03-flat.svg");
    }

    private static void WriteInspectHelp(TextWriter stdout)
    {
        stdout.WriteLine("Inspect what Aetheris understands a model to mean.");
        stdout.WriteLine("Firmament input reports semantic declarations; STEP input reports topology through analyze.");
        stdout.WriteLine();
        stdout.WriteLine(InspectUsage);
        stdout.WriteLine("Example: aetheris inspect part.firmament --json");
    }

    private static void WriteViewHelp(TextWriter stdout)
    {
        stdout.WriteLine("Build and open Firmament, or open an existing STEP model, in Cadmata.");
        stdout.WriteLine("Firmament input is built to its adjacent .step artifact before launch; STEP input opens directly.");
        stdout.WriteLine();
        stdout.WriteLine(ViewUsage);
        stdout.WriteLine("  --cadmata-path <path>  Explicit Cadmata executable (legacy --cad-assistant-path is accepted). Otherwise packaged siblings, environment compatibility settings, PATH, and a development build are checked.");
        stdout.WriteLine("  --json                 Emit launch details without waiting for Cadmata to exit.");
        stdout.WriteLine("Example: aetheris view part.firmament");
    }

    private static void WriteTraceHelp(TextWriter stdout)
    {
        stdout.WriteLine("Trace a built-in Aetheris lowering case through AIR, route selection, BRepPlan, emitted BRep/STEP smoke, and CIR mirror admission. Use `analyze` for existing STEP/BRep geometry.");
        stdout.WriteLine();
        stdout.WriteLine(TraceUsage);
        stdout.WriteLine();
        stdout.WriteLine("Scope:");
        stdout.WriteLine("  trace reports compiler lowering; analyze reports geometric analysis of existing STEP/BRep artifacts.");
        stdout.WriteLine("  Supported cases: prismatic-section-transition, top-face-loop-chamfer");
        stdout.WriteLine("  Supported fixture extensions: .valid.firmfixture, .invalid.firmfixture.");
        stdout.WriteLine("  Optional aliases: prismatic, loop-chamfer.");
        stdout.WriteLine("  No STEP input is accepted by trace.");
        stdout.WriteLine();
        stdout.WriteLine("Options:");
        stdout.WriteLine("  --case <name>      Built-in lowering case name.");
        stdout.WriteLine("  --fixture <path>   Firmament fixture trace input (.valid/.invalid.firmfixture).");
        stdout.WriteLine("  --json          Emit deterministic machine-readable JSON (default output is human-readable text).");
        stdout.WriteLine("  --out-dir <dir> Write trace artifacts into a directory; the controlled side-hole fixture also writes side-hole.step, side-hole.trace.json, side-hole.trace.txt, and manifest.json.");
        stdout.WriteLine("  -h, --help      Show this help.");
        stdout.WriteLine();
        stdout.WriteLine("Examples:");
        stdout.WriteLine("  aetheris trace --case prismatic-section-transition");
        stdout.WriteLine("  aetheris trace --case top-face-loop-chamfer --json");
        stdout.WriteLine("  aetheris trace --fixture fixtures/Regression/Chamfer/valid/top-face-loop-chamfer.valid.firmfixture --json");
        stdout.WriteLine("  aetheris trace --fixture fixtures/Regression/Chamfer/valid/top-face-loop-chamfer.valid.firmfixture --out-dir artifacts/air-x7");
        stdout.WriteLine("  aetheris trace --fixture fixtures/Regression/Region/valid/side-hole-face-attached-region.valid.firmfixture --out-dir artifacts/air-region-x13/side-hole");
    }

    private static void WriteAnalyzeHelp(TextWriter stdout)
    {
        stdout.WriteLine("Analyze part-like STEP geometry and topology.");
        stdout.WriteLine();
        stdout.WriteLine(AnalyzeUsage);
        stdout.WriteLine($"   or: {AnalyzeMapUsage[7..]}");
        stdout.WriteLine($"   or: {AnalyzeSectionUsage[7..]}");
        stdout.WriteLine($"   or: {AnalyzeCompoundUsage[7..]}");
        stdout.WriteLine();
        stdout.WriteLine("Options (summary mode):");
        stdout.WriteLine("  --face <id>     Inspect one face.");
        stdout.WriteLine("  --edge <id>     Inspect one edge.");
        stdout.WriteLine("  --vertex <id>   Inspect one vertex.");
        stdout.WriteLine("  --json          Emit machine-readable JSON (default output is human-readable text).");
        stdout.WriteLine("  -h, --help      Show this help.");
        stdout.WriteLine();
        stdout.WriteLine("Rules:");
        stdout.WriteLine("  - At most one of --face, --edge, --vertex may be supplied.");
        stdout.WriteLine("  - Use 'aetheris analyze map --help' for orthographic map options.");
        stdout.WriteLine("  - Use 'aetheris analyze section --help' for section options.");
        stdout.WriteLine("  - Use 'aetheris analyze volume --help' for volume options.");
        stdout.WriteLine("  - Summary mode remains single-part; use 'analyze assembly' for product structure, transforms, and world bounds.");
        stdout.WriteLine("  - Use 'analyze compound' to inspect multi-root solids without assigning product semantics.");
        stdout.WriteLine();
        stdout.WriteLine("Examples:");
        stdout.WriteLine("  aetheris analyze part.step");
        stdout.WriteLine("  aetheris analyze part.step --json");
        stdout.WriteLine("  aetheris analyze part.step --face 12");
        stdout.WriteLine("  aetheris analyze part.step --face 12 --json");
        stdout.WriteLine("  aetheris analyze map part.step --right --rows 20 --cols 30 --json");
        stdout.WriteLine("  aetheris analyze section part.step --yz --offset 1.25 --json");
        stdout.WriteLine("  aetheris analyze compound multi-solid.step --json");
        stdout.WriteLine("  aetheris analyze assembly machine.step --json");
    }

    private static void WriteAnalyzeMapHelp(TextWriter stdout)
    {
        stdout.WriteLine("Analyze STEP body as an orthographic depth/thickness map.");
        stdout.WriteLine();
        stdout.WriteLine(AnalyzeMapUsage);
        stdout.WriteLine();
        stdout.WriteLine("Required:");
        stdout.WriteLine("  either --plane <xy|xz|yz> with --direction <axis>, exactly one legacy view, or --views six --llm.");
        stdout.WriteLine("  legacy views: --top | --bottom | --front | --back | --left | --right");
        stdout.WriteLine("  --rows <N>       Positive integer row count.");
        stdout.WriteLine("  --cols <N>       Positive integer column count.");
        stdout.WriteLine("  --resolution NxM Alternative to --cols N --rows M.");
        stdout.WriteLine("  --json           Required output mode.");
        stdout.WriteLine();
        stdout.WriteLine("Six-view convention:");
        stdout.WriteLine("  top xy/-z, bottom xy/+z, right yz/-x, left yz/+x, back xz/+y, front xz/-y.");
        stdout.WriteLine();
        stdout.WriteLine("Example:");
        stdout.WriteLine("  aetheris analyze map part.step --top --rows 48 --cols 64 --json");
        stdout.WriteLine("  aetheris analyze map part.step --views six --resolution 16x16 --llm --rank-probes --json");
    }

    private static void WriteAnalyzeSectionHelp(TextWriter stdout)
    {
        stdout.WriteLine("Analyze STEP body by intersecting a principal or arbitrary section plane.");
        stdout.WriteLine();
        stdout.WriteLine(AnalyzeSectionUsage);
        stdout.WriteLine();
        stdout.WriteLine("Required:");
        stdout.WriteLine("  principal: exactly one of --xy | --xz | --yz plus --offset <value>");
        stdout.WriteLine("  arbitrary: --origin <x,y,z> plus --normal <x,y,z>");
        stdout.WriteLine("  --out <path>      Write deterministic 2D SVG evidence.");
        stdout.WriteLine("  --json            Emit ordered analytic loops and provenance.");
        stdout.WriteLine();
        stdout.WriteLine("Example:");
        stdout.WriteLine("  aetheris analyze section part.step --xz --offset 5.0 --json");
        stdout.WriteLine("  aetheris analyze section part.step --origin 1,2,3 --normal 1,1,0 --out section.svg --json");
    }

    private static void WriteAnalyzeVolumeHelp(TextWriter stdout)
    {
        stdout.WriteLine(AnalyzeVolumeUsage);
        stdout.WriteLine();
        stdout.WriteLine("Analyze STEP body volume using kernel B-rep topology/geometry.");
        stdout.WriteLine();
        stdout.WriteLine("Options:");
        stdout.WriteLine("  --json         Emit machine-readable JSON output.");
        stdout.WriteLine("  --approximate  Compute explicit voxel-based approximate volume.");
        stdout.WriteLine("  --resolution   Required with --approximate. Integer samples along longest bbox axis.");
        stdout.WriteLine();
        stdout.WriteLine("Notes:");
        stdout.WriteLine("  - Exact whole-body volume currently supports canonical spheres and single-lateral-face cylinders.");
        stdout.WriteLine("  - Approximate mode is opt-in and deterministic (center-point voxel occupancy sampling).");
        stdout.WriteLine("  - Exact sub-box volume clipping (--box ...) is deferred in ANALYZE-P1.");
        stdout.WriteLine();
        stdout.WriteLine("Examples:");
        stdout.WriteLine("  aetheris analyze volume part.step");
        stdout.WriteLine("  aetheris analyze volume part.step --json");
        stdout.WriteLine("  aetheris analyze volume part.step --approximate --resolution 64 --json");
    }

    private static void WriteVerifyHelp(TextWriter stdout)
    {
        stdout.WriteLine(VerifyUsage);
        stdout.WriteLine();
        stdout.WriteLine("Firmament input is built first; STEP input is reimported directly for independent B-rep mass properties and optional external display inspection.");
        stdout.WriteLine("The report is hash-tied to artifacts/local/verification/<fixture>/<sha256>/ by default.");
        stdout.WriteLine();
        stdout.WriteLine("Options:");
        stdout.WriteLine("  --expected-volume <value>   Compare independent measured volume with external analytic evidence; never used by the evaluator.");
        stdout.WriteLine("  --cad-assistant              Launch configured CAD Assistant for external display observation.");
        stdout.WriteLine("  --cad-assistant-path <path> Explicit CAD Assistant executable; otherwise AETHERIS_CAD_ASSISTANT_PATH and two standard install paths are checked.");
        stdout.WriteLine("  --timeout <seconds>          External inspection timeout (default 30).");
        stdout.WriteLine("  --evidence-dir <path>        Override hash-tied evidence directory.");
        stdout.WriteLine("  --require-external           Return exit 2 when CAD Assistant is unavailable.");
        stdout.WriteLine("  --json                       Emit the unified report on stdout.");
    }

    private static void WriteCanonHelp(TextWriter stdout)
    {
        stdout.WriteLine("Canonicalize part-like STEP/AP242 through Aetheris import/export.");
        stdout.WriteLine();
        stdout.WriteLine(CanonUsage);
        stdout.WriteLine();
        stdout.WriteLine("Options:");
        stdout.WriteLine("  --out <path>   Required canonical AP242 output path.");
        stdout.WriteLine("  --mode <mode>  deterministic (default) or production metadata preservation.");
        stdout.WriteLine("  (Assembly-like multi-root STEP is not canonicalized by this command.)");
        stdout.WriteLine("  --json         Emit machine-readable success/failure JSON.");
        stdout.WriteLine("  -h, --help     Show this help.");
        stdout.WriteLine();
        stdout.WriteLine("Example:");
        stdout.WriteLine("  aetheris canon input.step --out canonical.step --json");
    }


    private static void WriteExperimentalHelp(TextWriter stdout)
    {
        stdout.WriteLine("Experimental/lab-only artifact export commands.");
        stdout.WriteLine();
        stdout.WriteLine(ExperimentalUsage);
        stdout.WriteLine();
        stdout.WriteLine("Subcommands:");
        stdout.WriteLine("  airchamfer-cube    Export a controlled one-edge AirChamfer candidate cube/box STEP artifact.");
        stdout.WriteLine("  airchamfer-corpus  Generate the EDGE-X11 tiny AirChamfer STEP regression corpus.");
        stdout.WriteLine("  prismatic-corpus   Generate the EDGE-PRISMATIC-X5 split-preserving prismatic corpus.");
        stdout.WriteLine("  prismatic-map      Inspect EDGE-PRISMATIC-X9 generated-source-only prismatic map JSON.");
        stdout.WriteLine("  loop-chamfer-corpus Generate the EDGE-LOOP-X2 top-face loop chamfer STEP/JSON corpus.");
        stdout.WriteLine("  heightfield-art     Export the retired polar PlasticShell height field as non-manufacturing computer art.");
        stdout.WriteLine();
        stdout.WriteLine("Notes:");
        stdout.WriteLine("  - Experimental only; does not route production Firmament chamfer operations through AirChamfer.");
        stdout.WriteLine("  - Legacy BrepBoundedChamfer remains production-authoritative.");
        stdout.WriteLine("  - The candidate path uses no 3D Boolean fallback.");
        stdout.WriteLine("  - The prismatic corpus preserves section-boundary split faces and performs no coplanar merge.");
        stdout.WriteLine("  - experimental prismatic-map is generated-source-only, not normal analyze map, and accepts no STEP input.");
        stdout.WriteLine("  - loop-chamfer-corpus is a lab-only Class B top-face outer-loop route and does not change production chamfer or fillet behavior.");
        stdout.WriteLine("  - heightfield-art is a visual Easter egg and never participates in normal PlasticShell build or manufacturing evidence.");
        stdout.WriteLine();
        stdout.WriteLine("Examples:");
        stdout.WriteLine("  aetheris experimental airchamfer-cube --out edge-x10-airchamfer-cube-one-edge.step --json");
        stdout.WriteLine("  aetheris experimental airchamfer-corpus --out-dir artifacts/edge-x11 --json");
        stdout.WriteLine("  aetheris experimental prismatic-corpus --out-dir artifacts/edge-prismatic-x5 --json");
        stdout.WriteLine("  aetheris experimental prismatic-map --case rectangle-inset --rows 16 --cols 16 --json");
        stdout.WriteLine("  aetheris experimental loop-chamfer-corpus --out-dir artifacts/edge-loop-x2 --json");
        stdout.WriteLine("  aetheris experimental heightfield-art enclosure.firmament --out artifacts/local/happy-little-accident.step --json");
    }

    private static void WriteExperimentalLoopChamferCorpusHelp(TextWriter stdout)
    {
        stdout.WriteLine("Generate the EDGE-LOOP-X2 top-face outer-loop chamfer artifact corpus.");
        stdout.WriteLine();
        stdout.WriteLine(ExperimentalLoopChamferCorpusUsage);
        stdout.WriteLine();
        stdout.WriteLine("Options:");
        stdout.WriteLine("  --out-dir <dir>  Required deterministic corpus output directory.");
        stdout.WriteLine("  --json           Emit the corpus JSON summary to stdout after writing it to disk.");
        stdout.WriteLine("  -h, --help       Show this help.");
        stdout.WriteLine();
        stdout.WriteLine("Artifacts:");
        stdout.WriteLine("  edge-loop-x2-canonical-top-face-loop-chamfer.step");
        stdout.WriteLine("  edge-loop-x2-larger-top-face-loop-chamfer.step");
        stdout.WriteLine("  edge-loop-x2-non-square-top-face-loop-chamfer.step");
        stdout.WriteLine($"  {EdgeLoopX2TopFaceLoopChamferCorpusLab.DefaultSummaryFileName}");
        stdout.WriteLine();
        stdout.WriteLine("Production safety:");
        stdout.WriteLine("  Experimental/lab-only route; no production route replacement, AirEdgeSweep, BrepBoundedChamfer, topology graft, 3D Boolean, coplanar merge, or production chamfer/fillet behavior change.");
        stdout.WriteLine();
        stdout.WriteLine("Example:");
        stdout.WriteLine("  aetheris experimental loop-chamfer-corpus --out-dir artifacts/edge-loop-x2 --json");
    }

    private static void WriteExperimentalAirChamferCubeHelp(TextWriter stdout)
    {
        stdout.WriteLine("Export a controlled one-edge AirChamfer candidate cube/box STEP artifact.");
        stdout.WriteLine();
        stdout.WriteLine(ExperimentalAirChamferCubeUsage);
        stdout.WriteLine();
        stdout.WriteLine("Options:");
        stdout.WriteLine("  --out <path>   Required deterministic STEP output path.");
        stdout.WriteLine("  --json         Emit machine-readable success/failure JSON.");
        stdout.WriteLine("  -h, --help     Show this help.");
        stdout.WriteLine();
        stdout.WriteLine("Expected artifact name:");
        stdout.WriteLine($"  {AirChamferStepArtifactLab.DefaultArtifactFileName}");
        stdout.WriteLine();
        stdout.WriteLine("Production safety:");
        stdout.WriteLine("  Experimental/lab-only route; no production chamfer route replacement and no 3D Boolean.");
        stdout.WriteLine();
        stdout.WriteLine("Example:");
        stdout.WriteLine("  aetheris experimental airchamfer-cube --out edge-x10-airchamfer-cube-one-edge.step --json");
    }

    private static void WriteExperimentalAirChamferCorpusHelp(TextWriter stdout)
    {
        stdout.WriteLine("Generate the EDGE-X11 tiny AirChamfer STEP artifact regression corpus.");
        stdout.WriteLine();
        stdout.WriteLine(ExperimentalAirChamferCorpusUsage);
        stdout.WriteLine();
        stdout.WriteLine("Options:");
        stdout.WriteLine("  --out-dir <dir>  Required deterministic corpus output directory.");
        stdout.WriteLine("  --json           Emit the corpus JSON summary to stdout after writing it to disk.");
        stdout.WriteLine("  -h, --help       Show this help.");
        stdout.WriteLine();
        stdout.WriteLine("Artifacts:");
        stdout.WriteLine("  edge-x11-airchamfer-cube-canonical.step");
        stdout.WriteLine("  edge-x11-airchamfer-cube-nonorthogonal.step when supported; otherwise JSON-only deferred diagnostics.");
        stdout.WriteLine($"  {AirChamferStepArtifactLab.DefaultCorpusSummaryFileName}");
        stdout.WriteLine();
        stdout.WriteLine("Production safety:");
        stdout.WriteLine("  Experimental/lab-only route; no production chamfer route replacement and no 3D Boolean.");
        stdout.WriteLine();
        stdout.WriteLine("Example:");
        stdout.WriteLine("  aetheris experimental airchamfer-corpus --out-dir artifacts/edge-x11 --json");
    }


    private static void WriteExperimentalPrismaticCorpusHelp(TextWriter stdout)
    {
        stdout.WriteLine("Generate the EDGE-PRISMATIC-X5 split-preserving prismatic section-transition artifact corpus.");
        stdout.WriteLine();
        stdout.WriteLine(ExperimentalPrismaticCorpusUsage);
        stdout.WriteLine();
        stdout.WriteLine("Options:");
        stdout.WriteLine("  --out-dir <dir>  Required deterministic corpus output directory.");
        stdout.WriteLine("  --json           Emit the corpus JSON summary to stdout after writing it to disk.");
        stdout.WriteLine("  -h, --help       Show this help.");
        stdout.WriteLine();
        stdout.WriteLine("Artifacts:");
        stdout.WriteLine("  edge-prismatic-x5-rectangle-inset.step");
        stdout.WriteLine("  edge-prismatic-x5-top-edge-chamfer.step");
        stdout.WriteLine("  edge-prismatic-x5-pentagon-scaled.step");
        stdout.WriteLine("  edge-prismatic-x5-hexagon-scaled.step");
        stdout.WriteLine("  edge-prismatic-x5-pentagon-asymmetric.step");
        stdout.WriteLine($"  {PrismaticSectionTransitionCorpusLab.DefaultSummaryFileName}");
        stdout.WriteLine();
        stdout.WriteLine("Production safety:");
        stdout.WriteLine("  Experimental/lab-only route; no production route replacement, AirEdgeSweep, BrepBoundedChamfer, topology graft, 3D Boolean, and no coplanar merge.");
        stdout.WriteLine();
        stdout.WriteLine("Example:");
        stdout.WriteLine("  aetheris experimental prismatic-corpus --out-dir artifacts/edge-prismatic-x5 --json");
    }



    private static void WriteExperimentalPrismaticMapHelp(TextWriter stdout)
    {
        stdout.WriteLine("Inspect the EDGE-PRISMATIC-X9 generated-source-only prismatic map proof as JSON.");
        stdout.WriteLine();
        stdout.WriteLine(ExperimentalPrismaticMapUsage);
        stdout.WriteLine();
        stdout.WriteLine("Options:");
        stdout.WriteLine("  --case <case>     Required generated case: rectangle-inset or top-edge-chamfer.");
        stdout.WriteLine("  --rows <N>        Required positive row count.");
        stdout.WriteLine("  --cols <N>        Required positive column count.");
        stdout.WriteLine("  --json            Required machine-readable output; no stable text API is promised.");
        stdout.WriteLine("  --request <use>   Optional; only map-occupancy is supported. Face identity/topology parity reject as lossy.");
        stdout.WriteLine("  -h, --help        Show this help.");
        stdout.WriteLine();
        stdout.WriteLine("Scope and authority:");
        stdout.WriteLine("  - Experimental generated AIR/prismatic source route only.");
        stdout.WriteLine("  - This is not normal 'aetheris analyze map' and does not change its STEP behavior.");
        stdout.WriteLine("  - No STEP input, imported STEP prismatic body, or arbitrary user geometry is accepted.");
        stdout.WriteLine("  - Output supports map occupancy only; no topology or face identity claims are made.");
        stdout.WriteLine();
        stdout.WriteLine("Example:");
        stdout.WriteLine("  aetheris experimental prismatic-map --case rectangle-inset --rows 16 --cols 16 --json");
    }

    private static void WriteAsmHelp(TextWriter stdout)
    {
        stdout.WriteLine("Inspect Firmament V2 assemblies authored in .firmament or the .firmasm Assembly document profile. Historical JSON-shaped .firmasm syntax is legacy.");
        stdout.WriteLine();
        stdout.WriteLine(AsmExecUsage);
        stdout.WriteLine($"   or: {AsmExportUsage[7..]}");
        stdout.WriteLine($"   or: {AsmInspectUsage[7..]}");
        stdout.WriteLine($"   or: {AsmImportStepUsage[7..]}");
        stdout.WriteLine($"   or: {AsmExportAp242Usage[7..]}");
        stdout.WriteLine($"   or: {AssemblyUsdCommand.Usage}");
        stdout.WriteLine($"   or: {AssemblyMotionCommand.Usage}");
        stdout.WriteLine($"   or: {AssemblyGlbCommand.Usage}");
        stdout.WriteLine($"   or: {Presentation3DCommand.Usage}");
        stdout.WriteLine();
        stdout.WriteLine("Options:");
        stdout.WriteLine("  --out <path>   Required for 'asm export'; output directory for package artifacts.");
        stdout.WriteLine("  --json         Emit machine-readable execution and analyzer JSON.");
        stdout.WriteLine("  -h, --help     Show this help.");
        stdout.WriteLine();
        stdout.WriteLine("Example:");
        stdout.WriteLine("  aetheris asm exec fixtures/Compatibility/Firmasm/LegacyAssembly/examples/occt-as1/as1-assembly.firmasm --json");
        stdout.WriteLine("  aetheris asm export fixtures/Compatibility/Firmasm/LegacyAssembly/examples/occt-nut-bolt/nut-bolt-assembly.firmasm --out tmp/nutbolt-export --json");
        stdout.WriteLine("  aetheris asm inspect fixtures/Canonical/Assembly/bearing-module.firmament --json");
        stdout.WriteLine("  aetheris asm import-step testdata/step242/OCCT/as1.step --out tmp/as1-package --json");
        stdout.WriteLine("  aetheris asm export-ap242 tmp/as1-package/as1.firmasm --out tmp/as1.step --json");
    }

    private static string FormatBox(Aetheris.Kernel.Core.Math.BoundingBox3D? box) =>
        box is null ? "unknown" : $"min{FormatPoint(box.Value.Min)} max{FormatPoint(box.Value.Max)}";

    private static string FormatPoint(Aetheris.Kernel.Core.Math.Point3D? point) =>
        point is null ? "unknown" : $"({point.Value.X:F6},{point.Value.Y:F6},{point.Value.Z:F6})";

    private static string FormatVector(Aetheris.Kernel.Core.Math.Vector3D? vector) =>
        vector is null ? "n/a" : $"({vector.Value.X:F6},{vector.Value.Y:F6},{vector.Value.Z:F6})";

    private static string FormatDouble(double? value) => value?.ToString("G17") ?? "n/a";

    private sealed record ProfileJunctionInspection(
        string ProfileId, string LoopId, string PredecessorSegment, string SuccessorSegment,
        string VertexId, double SignedTurnDegrees, double MaterialInteriorAngleDegrees,
        string Classification, bool SelectedByEdgeFinish, IReadOnlyList<string> GeneratedDescendants);

    private sealed record ProfileStraightEdgeFilletInspection(
        bool Succeeded, string? Diagnostic, string? EdgeFinishId, string? ProfileId, string? LoopId, string? TargetKind, IReadOnlyList<string> SegmentIds,
        string? Side, double? Radius, double? EndClearance, string? EndpointPolicy,
        double[]? CylinderAxis, double[]? CylinderCenterlineStart, double[]? CylinderCenterlineEnd,
        double[]? CapContactStart, double[]? CapContactEnd, double[]? SideContactStart, double[]? SideContactEnd,
        string CorridorClassification, IReadOnlyList<string> GeneratedDescendants, IReadOnlyList<string> Provenance,
        ProfileConvexFilletJunctionInspection? ConvexJunction, string? ReflexJunctionStyle = null);

    private sealed record ProfileConvexFilletJunctionInspection(
        string VertexId, string Classification, double InteriorAngleDegrees, double Radius,
        double[] SphereCenter, IReadOnlyList<double[]> RollAxes, IReadOnlyList<double[]> RollExternalCenters,
        IReadOnlyList<double[]> RollJunctionCenters, string SurfaceFamily, double? MajorRadius,
        double? MinorRadius, double[]? ParametricBounds);

    private static ProfileStraightEdgeFilletInspection? DescribeProfileStraightEdgeFillet(ResolvedProfile2D profile, string source, string hostBodyId)
    {
        if (!ProfileBoundaryChamferSourceBinder.HasProfileBoundaryFillet(source)) return null;
        if (!ProfileBoundaryChamferSourceBinder.TryBindFillet(source, profile, hostBodyId, out var target, out var radius, out var clearance, out var diagnostic))
            return new(false, diagnostic, null, null, null, null, [], null, null, null, null, null, null, null, null, null, null, null, "RejectedBeforePlan", [], [], null);
        var result = ProfileFilletShellPlanner.TryPlan(profile, target!, radius, clearance);
        if (!result.Succeeded)
            return new(false, result.Diagnostics.FirstOrDefault(), target!.StableId, target.ProfileId, target.LoopId, target.ChainKind.ToString(), target.SegmentIds, target.Side.ToString(), radius, clearance, null, null, null, null, null, null, null, null, "RejectedBeforeTopology", [], [], null);
        static double[] V(Direction3D value) => [value.ToVector().X, value.ToVector().Y, value.ToVector().Z];
        static double[] P(Point3D value) => [value.X, value.Y, value.Z];
        if (result.Plan is not null)
        {
            var plan = result.Plan;
            var reflex = plan.Junction as ProfileReflexFilletJunctionPlan;
            var sphereSeam = plan.Junction is ProfileReflexSphereSeamCompatibilityJunctionPlan;
            var junction = new ProfileConvexFilletJunctionInspection(plan.Junction.VertexId, plan.Junction.Classification.Classification.ToString(), plan.Junction.Classification.MaterialInteriorAngleRadians * 180d / Math.PI, plan.Junction.Radius, P(plan.Junction.Center), plan.Rolls.Select(roll => V(roll.Tangent)).ToArray(), plan.Rolls.Select(roll => P(roll.ExternalCenter)).ToArray(), plan.Rolls.Select(roll => P(roll.JunctionCenter)).ToArray(), reflex is null ? sphereSeam ? "SphereSeamCompatibility" : "Sphere" : "HornTorus", reflex?.Torus.MajorRadius, reflex?.Torus.MinorRadius, reflex is null ? null : [reflex.MajorStartRadians, reflex.MajorEndRadians, reflex.MinorStartRadians, reflex.MinorEndRadians]);
            return new(true, null, target!.StableId, target.ProfileId, target.LoopId, target.ChainKind.ToString(), target.SegmentIds, target.Side.ToString(), radius, clearance, plan.EndpointPolicy,
                null, null, null, null, null, null, null, "DisjointNoCavitiesInBareProfileM2", result.Correspondence?.Descendants.Select(x => x.StableId).OrderBy(x => x, StringComparer.Ordinal).ToArray() ?? [], result.Correspondence?.ProvenanceChain ?? [], junction, target.ReflexJunctionStyle.ToString());
        }
        var single = result.SingleSegmentPlan!;
        return new(true, null, target!.StableId, target.ProfileId, target.LoopId, target.ChainKind.ToString(), target.SegmentIds, target.Side.ToString(), radius, clearance, single.EndpointPolicy,
            V(single.Tangent), P(single.CylinderCenterlineStart), P(single.CylinderCenterlineEnd), P(single.CapContactStart), P(single.CapContactEnd), P(single.SideContactStart), P(single.SideContactEnd),
            "DisjointNoCavitiesInBareProfileM1", result.Correspondence?.Descendants.Select(x => x.StableId).OrderBy(x => x, StringComparer.Ordinal).ToArray() ?? [], result.Correspondence?.ProvenanceChain ?? [], null);
    }

    private static IReadOnlyList<ProfileJunctionInspection> DescribeProfileJunctions(ResolvedProfile2D profile, string source, string hostBodyId)
    {
        ProfileBoundaryChamferTarget? target = null;
        SemanticTopologyCorrespondence? correspondence = null;
        if (ProfileBoundaryChamferSourceBinder.TryBind(source, profile, hostBodyId, out var bound, out var distance, out _))
        {
            target = bound;
            var plan = ProfileBoundaryChamferPlanner.TryPlan(profile, bound!, distance);
            correspondence = plan.Correspondence;
        }
        var selected = target?.SegmentIds.ToHashSet(StringComparer.Ordinal) ?? [];
        return ProfileJunctionClassifier.Classify(profile).Select(junction =>
        {
            var selectedByFinish = selected.Contains(junction.PredecessorSegmentId) && selected.Contains(junction.SuccessorSegmentId);
            var descendantPrefix = target is null ? string.Empty : $"{target.StableId}:{junction.Classification}({junction.VertexId})";
            var descendants = correspondence?.Descendants.Where(descendant => descendant.StableId == descendantPrefix).Select(descendant => descendant.StableId).ToArray() ?? [];
            return new ProfileJunctionInspection(junction.ProfileId, junction.LoopId, junction.PredecessorSegmentId, junction.SuccessorSegmentId,
                junction.VertexId, junction.SignedTurnRadians * 180d / Math.PI, junction.MaterialInteriorAngleRadians * 180d / Math.PI,
                junction.Classification.ToString(), selectedByFinish, descendants);
        }).ToArray();
    }

    private static string ProfileSignature(ResolvedProfile2D profile) => Hash(string.Join(";", profile.Loops.SelectMany(l => l.Segments).Select(s => s.Geometry switch
    {
        LineArcLineSegment2D line => $"L:{Q(line.Start.X)},{Q(line.Start.Y)}:{Q(line.End.X)},{Q(line.End.Y)}",
        LineArcCircularArc2D arc => $"A:{Q(arc.Center.X)},{Q(arc.Center.Y)}:{Q(arc.Radius)}:{Q(arc.StartAngleRadians)}:{Q(arc.SweepAngleRadians)}",
        _ => s.Geometry.GetType().Name
    }).OrderBy(x => x, StringComparer.Ordinal)));

    private static string CompositionSignature(PrismaticSectionStackConstruction stack) => Hash(string.Join("|", stack.Slabs.Select(s =>
        $"{Q(s.From)}:{Q(s.To)}:{string.Join(";", s.MaterialRegions.Select(r => $"{ProfileSignature(r.Outer)}:{Q(PrismaticSectionStackCompiler.Area(r))}"))}")));
    private static string Hash(string value) => Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(value))).ToLowerInvariant();
    private static long Q(double value) => (long)Math.Round(value * 1_000_000d, MidpointRounding.AwayFromZero);
}