Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

266 KB
Raw Blame
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Diagnostics;
using Aetheris.Kernel.Core.Air;
using Aetheris.Kernel.Core.Results;
using Aetheris.Kernel.Core.Diagnostics;
using Aetheris.Kernel.Core.Step242;
using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Brep.Verification;
using Aetheris.Kernel.Core.Brep.Boolean;
using Aetheris.Kernel.Core.Brep.Features;
using Aetheris.Kernel.Core.Geometry;
using Aetheris.Kernel.Core.Geometry.Curves;
using Aetheris.Kernel.Core.Geometry.Surfaces;
using Aetheris.Kernel.Core.Math;
using Aetheris.Kernel.Core.Numerics;
using Aetheris.Kernel.Core.Topology;
using Aetheris.Kernel.Firmament.Execution;
using Aetheris.Kernel.Firmament.Lowering;
using Aetheris.Kernel.Firmament.FirmamentV2;
using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
using Aetheris.Kernel.Firmament.Materializer;
using Aetheris.Kernel.StandardLibrary;
using Aetheris.Kernel.Firmament.Structural;
using Aetheris.Kernel.Firmament.Piping;

namespace Aetheris.Kernel.Firmament;

public static partial class FirmamentBuildAndExport
{
    public const string EdgeFinishProfileComposeBoundaryUnsupported = "EdgeFinishProfileComposeBoundaryUnsupported";
    private enum ExportRouteDisposition { Declined, Failed, Succeeded }
    private sealed record ExportRouteResult(string Route, ExportRouteDisposition Disposition, KernelResult<FirmamentStepExportResult>? Artifact = null)
    {
        public static ExportRouteResult Decline(string route) => new(route, ExportRouteDisposition.Declined);
        public static ExportRouteResult Complete(string route, KernelResult<FirmamentStepExportResult> artifact) => new(route, artifact.IsSuccess ? ExportRouteDisposition.Succeeded : ExportRouteDisposition.Failed, artifact);
    }

    public static KernelResult<FirmamentBuildAndExportResult> Run(string sourcePath, string? outputPath = null)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(sourcePath);

        var fullSourcePath = Path.GetFullPath(sourcePath);
        var lockDiagnostics = Modules.FirmamentDependencies.VerifyFile(fullSourcePath);
        if (lockDiagnostics.Count > 0) return KernelResult<FirmamentBuildAndExportResult>.Failure(
            lockDiagnostics.Select(d => SchemaDiagnostic(d.Code + ": " + d.Message)).ToArray());
        var sourceText = File.ReadAllText(fullSourcePath, Encoding.UTF8);
        var authoredSource = sourceText;
        // The lexer accepts authored line endings. Keep their offsets intact for
        // admission diagnostics and runtime assertion spans on Windows as well.
        var frontend = FirmamentFrontendSchemas.Select(sourceText);
        if (!frontend.IsSuccess) return KernelResult<FirmamentBuildAndExportResult>.Failure(frontend.LocatedDiagnostics.Select(d => SchemaDiagnostic(d.Code + ": " + d.Message)).ToArray());
        sourceText = frontend.Source;
        if (PipingAuthoring.IsPipingSource(sourceText))
        {
            var piping = PipingAuthoring.Compile(sourceText, fullSourcePath);
            if (!piping.IsSuccess || piping.StepText is null || piping.Report is null)
                return KernelResult<FirmamentBuildAndExportResult>.Failure(piping.KernelDiagnostics());
            var pipingOutputPath = string.IsNullOrWhiteSpace(outputPath) ? ResolveDefaultOutputPath(fullSourcePath) : Path.GetFullPath(outputPath);
            Directory.CreateDirectory(Path.GetDirectoryName(pipingOutputPath)!);
            File.WriteAllText(pipingOutputPath, piping.StepText, new UTF8Encoding(false));
            var stem = Path.Combine(Path.GetDirectoryName(pipingOutputPath)!, Path.GetFileNameWithoutExtension(pipingOutputPath));
            var routingPath = stem + ".routing.json"; var cutListPath = stem + ".cutlist.json"; var bomPath = stem + ".bom.json";
            File.WriteAllText(routingPath, PipingAuthoring.RoutingJson(piping.Report), new UTF8Encoding(false));
            File.WriteAllText(cutListPath, PipingAuthoring.CutListJson(piping.Report), new UTF8Encoding(false));
            File.WriteAllText(bomPath, PipingAuthoring.BomJson(piping.Report), new UTF8Encoding(false));
            var report = piping.Report with { RoutingReportArtifactPath = routingPath, CutListArtifactPath = cutListPath, BomArtifactPath = bomPath };
            return KernelResult<FirmamentBuildAndExportResult>.Success(new(fullSourcePath, pipingOutputPath,
                new(piping.StepText, "piping-system:" + report.PipingSystem, -1, "Assembly", "PipingSystem", Piping: report)));
        }
        if (StructuralAuthoring.IsStructuralSource(sourceText))
        {
            var structural = StructuralAuthoring.Compile(sourceText, fullSourcePath);
            if (!structural.IsSuccess || structural.StepText is null || structural.Report is null)
                return KernelResult<FirmamentBuildAndExportResult>.Failure(structural.KernelDiagnostics());
            var structuralOutputPath = string.IsNullOrWhiteSpace(outputPath) ? ResolveDefaultOutputPath(fullSourcePath) : Path.GetFullPath(outputPath);
            Directory.CreateDirectory(Path.GetDirectoryName(structuralOutputPath)!);
            File.WriteAllText(structuralOutputPath, structural.StepText, new UTF8Encoding(false));
            var cutListPath = Path.Combine(Path.GetDirectoryName(structuralOutputPath)!, Path.GetFileNameWithoutExtension(structuralOutputPath) + ".cutlist.json");
            File.WriteAllText(cutListPath, StructuralAuthoring.CutListJson(structural.Report), new UTF8Encoding(false));
            var report = structural.Report with { CutListArtifactPath = cutListPath };
            var structuralExport = new FirmamentStepExportResult(structural.StepText, "structure:" + report.Structure, -1, "Assembly", "Structure", Structural: report);
            return KernelResult<FirmamentBuildAndExportResult>.Success(new(fullSourcePath, structuralOutputPath, structuralExport));
        }
        var library = FirmamentStandardLibraryResolver.Resolve(sourceText, out var libraryDiagnostics);
        if (library is null)
            return KernelResult<FirmamentBuildAndExportResult>.Failure(LibraryDiagnostics(libraryDiagnostics));
        sourceText = library.Source;
        var exportResult = ExportSource(sourceText, Path.GetDirectoryName(fullSourcePath), allowV1Compatibility: true, frontend.Schema, authoredSource: authoredSource);
        if (!exportResult.IsSuccess)
        {
            return KernelResult<FirmamentBuildAndExportResult>.Failure(exportResult.Diagnostics);
        }

        var enrichedExport = AttachAuthoredFeatureReports(sourceText, Path.GetDirectoryName(fullSourcePath), exportResult.Value);
        var pmiParity = VerifyV2PmiExportParity(sourceText, Path.GetDirectoryName(fullSourcePath), enrichedExport);
        if (!pmiParity.IsSuccess)
        {
            return KernelResult<FirmamentBuildAndExportResult>.Failure(pmiParity.Diagnostics);
        }

        var assertions = EvaluateAssertions(sourceText, Path.GetDirectoryName(fullSourcePath), enrichedExport);
        if (!assertions.IsSuccess)
        {
            return KernelResult<FirmamentBuildAndExportResult>.Failure(assertions.Diagnostics);
        }
        var export = assertions.Value;
        var resolvedOutputPath = string.IsNullOrWhiteSpace(outputPath)
            ? ResolveDefaultOutputPath(fullSourcePath)
            : Path.GetFullPath(outputPath);

        Directory.CreateDirectory(Path.GetDirectoryName(resolvedOutputPath)!);
        File.WriteAllText(resolvedOutputPath, export.StepText, new UTF8Encoding(false));

        return KernelResult<FirmamentBuildAndExportResult>.Success(
            new FirmamentBuildAndExportResult(
                fullSourcePath,
                resolvedOutputPath,
                export),
            exportResult.Diagnostics);
    }

    /// <summary>
    /// Compiles an already-resolved in-memory module through the same materialization and
    /// validation path as file builds. Forge uses this after typed Template specialization.
    /// </summary>
    public static KernelResult<FirmamentStepExportResult> CompileSource(
        string sourceText,
        string? sourceDirectory = null, IReadOnlyDictionary<string, string>? resources = null) => CompileSourceCore(sourceText, sourceDirectory, true, resources);

    /// <summary>Explicit inspection boundary: admit and build geometry, but do not
    /// claim that its declared assertions passed. Used to discover assertion inputs.</summary>
    public static KernelResult<FirmamentStepExportResult> CompileForMeasurement(string sourceText, string? sourceDirectory = null)
        => CompileSourceCore(sourceText, sourceDirectory, false);

    private static KernelResult<FirmamentStepExportResult> CompileSourceCore(string sourceText, string? sourceDirectory, bool enforceAssertions,
        IReadOnlyDictionary<string, string>? resources = null)
    {
        ArgumentNullException.ThrowIfNull(sourceText);
        // Do not collapse CRLF here: bound declaration spans belong to this input.
        var normalized = sourceText;
        var frontend = FirmamentFrontendSchemas.Select(normalized);
        if (!frontend.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(frontend.LocatedDiagnostics.Select(d => SchemaDiagnostic(d.Code + ": " + d.Message)).ToArray());
        normalized = frontend.Source;
        if (PipingAuthoring.IsPipingSource(normalized))
        {
            var piping = PipingAuthoring.Compile(normalized, sourceDirectory ?? "memory");
            return piping.IsSuccess && piping.StepText is not null && piping.Report is not null
                ? KernelResult<FirmamentStepExportResult>.Success(new(piping.StepText, "piping-system:" + piping.Report.PipingSystem, -1, "Assembly", "PipingSystem", Piping: piping.Report))
                : KernelResult<FirmamentStepExportResult>.Failure(piping.KernelDiagnostics());
        }
        if (StructuralAuthoring.IsStructuralSource(normalized))
        {
            var structural = StructuralAuthoring.Compile(normalized, sourceDirectory ?? "memory");
            return structural.IsSuccess && structural.StepText is not null && structural.Report is not null
                ? KernelResult<FirmamentStepExportResult>.Success(new(structural.StepText, "structure:" + structural.Report.Structure, -1, "Assembly", "Structure", Structural: structural.Report))
                : KernelResult<FirmamentStepExportResult>.Failure(structural.KernelDiagnostics());
        }
        var library = FirmamentStandardLibraryResolver.Resolve(normalized, out var libraryDiagnostics);
        if (library is null)
            return KernelResult<FirmamentStepExportResult>.Failure(LibraryDiagnostics(libraryDiagnostics));
        normalized = library.Source;
        // In-memory compilation is the canonical V2 boundary used by Forge,
        // assemblies, and drawings. Historical V1 execution is intentionally
        // available only to the explicitly versioned file compatibility route.
        var export = ExportSource(normalized, sourceDirectory, allowV1Compatibility: false, frontend.Schema, resources, sourceText);
        if (!export.IsSuccess) return export;
        var enrichedExport = AttachAuthoredFeatureReports(normalized, sourceDirectory, export.Value, resources);
        var pmiParity = VerifyV2PmiExportParity(normalized, sourceDirectory, enrichedExport, resources);
        if (!pmiParity.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(pmiParity.Diagnostics);
        if (!enforceAssertions) return KernelResult<FirmamentStepExportResult>.Success(enrichedExport, export.Diagnostics);
        var assertions = EvaluateAssertions(normalized, sourceDirectory, enrichedExport);
        return assertions.IsSuccess
            ? KernelResult<FirmamentStepExportResult>.Success(assertions.Value, export.Diagnostics)
            : KernelResult<FirmamentStepExportResult>.Failure(assertions.Diagnostics);
    }

    private static FirmamentStepExportResult AttachAuthoredFeatureReports(
        string source,
        string? sourceDirectory,
        FirmamentStepExportResult export, IReadOnlyDictionary<string, string>? resources = null)
    {
        var parsed = FirmamentV2Parser.Parse(source, sourceDirectory, null, null, resources);
        if (!parsed.IsSuccess || parsed.Document is null) return export;
        export = export with
        {
            DocumentName = parsed.Document.ModelName,
            RuntimeAdmissionDocument = export.RuntimeAdmissionDocument ?? parsed.Document,
            ConceptDisplayValues = parsed.Document.ConceptIr?.Structs
                ?? ConceptIrResolver.RetainSpatialStructs(parsed.DiagnosticSource ?? parsed.BoundSource ?? source) };

        var edgeFinishes = (parsed.Document.ModifyBlocks ?? [])
            .SelectMany(modification => (modification.EdgeFinishes ?? []).Select(finish => new FirmamentEngineeringFeatureReport(
                finish.Name,
                "EdgeFinish",
                $"edgefinish:{finish.Name}",
                modification.TargetSolid,
                finish.Target == "AllEdges" ? "AllEdges" : finish.FaceAxis,
                finish.Target == "AllEdges" ? "" : finish.Target,
                finish.Distance,
                string.Equals(finish.Kind, "Fillet", StringComparison.Ordinal) ? "Radius" : "Distance",
                "Remove",
                PolicySource: finish.Kind,
                MaterializationRoute: finish.Target == "AllEdges" ? "ConvexStockRollingBall" : "SemanticEdgeFinish",
                SupportSpan: finish.Target == "AllEdges" ? $"{finish.SourceSpan.Start}:{finish.SourceSpan.Length}" : null)))
            .ToArray();
        var patterns = (parsed.Document.StaticAuthoring?.Patterns ?? [])
            .Select(pattern => new FirmamentSemanticPatternReport(
                pattern.Name,
                pattern.Source,
                pattern.Template,
                pattern.GeneratedCount,
                pattern.GeneratedIds,
                pattern.Associations is null ? "FiniteStaticArray" : "NamedSetAuthoredSourceOrder",
                Associations: pattern.Associations))
            .OrderBy(pattern => pattern.Name, StringComparer.Ordinal)
            .ToArray();
        if (edgeFinishes.Length == 0 && patterns.Length == 0) return export;

        var existing = export.EngineeringFeatures ?? [];
        return export with
        {
            EngineeringFeatures = existing
                .Concat(edgeFinishes)
                .DistinctBy(feature => feature.FeatureId, StringComparer.Ordinal)
                .OrderBy(feature => feature.FeatureId, StringComparer.Ordinal)
                .ToArray(),
            Patterns = patterns
        };
    }

    private static KernelResult<bool> VerifyV2PmiExportParity(string source, string? sourceDirectory, FirmamentStepExportResult export,
        IReadOnlyDictionary<string, string>? resources = null)
    {
        var document = export.RuntimeAdmissionDocument;
        if (document is null)
        {
            var parsed = FirmamentV2Parser.Parse(source, sourceDirectory, null, null, resources);
            if (!parsed.IsSuccess || parsed.Document is null) return KernelResult<bool>.Success(true);
            document = parsed.Document;
        }
        var pmi = document.Pmi ?? [];
        if (pmi.Count == 0 && export.GeneratedSemanticPmi.Count == 0 && !document.Solids.Any(s => s.InlineStep is { GeometryOnly: false })) return KernelResult<bool>.Success(true);

        var support = ValidateV2PmiExportSupport(document);
        if (!support.IsSuccess) return support;

        var expectedDatums = pmi.Count(record => record.Kind == FirmamentV2PmiKind.DatumPlane) + export.GeneratedSemanticPmi.OfType<Step242SemanticPmiDatum>().Count();
        // Projected sizes and locations are dimensions too; a hole callout on counterbores adds its
        // counterbore diameter and depth.
        var counterbores = Regex.Matches(source, @"\bHole<Counterbore>\s+(?<name>[A-Za-z_]\w*)").Select(m => m.Groups["name"].Value).ToHashSet(StringComparer.Ordinal);
        var calloutExtras = 2 * (document.BoundPmi?.Dimensions ?? []).Count(b => b.Callout && b.Targets.Any(counterbores.Contains));
        var expectedDiameters = pmi.Count(record => record.Kind is FirmamentV2PmiKind.HoleDiameter or FirmamentV2PmiKind.Dimension or FirmamentV2PmiKind.Location)
            + calloutExtras + export.GeneratedSemanticPmi.OfType<Step242SemanticPmiHole>().Count();
        var expectedControls = pmi.Count(record => Step242GeometricToleranceKinds.Find(record.Kind.ToString()) is not null)
            + export.GeneratedSemanticPmi.OfType<Step242SemanticPmiGeometricTolerance>().Count();
        foreach (var imported in document.Solids.Select(s => s.InlineStep).OfType<FirmamentV2InlineStepRecord>().Where(s => !s.GeometryOnly))
        {
            var original = Step242SemanticPmiInspector.Inspect(imported.SourceText ?? File.ReadAllText(imported.NormalizedPath, Encoding.UTF8));
            if (!original.Success) return KernelResult<bool>.Failure([new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,
                "firmament-v2-pmi-source-inspection-failed: Cannot verify imported PMI parity.", "FirmamentV2.PmiExportParity")]);
            expectedDatums += original.DatumCount; expectedDiameters += original.DimensionCount; expectedControls += original.GeometricToleranceCount;
        }
        var inspection = Step242SemanticPmiInspector.Inspect(export.StepText);
        if (inspection.Success && inspection.DatumCount == expectedDatums && inspection.DimensionCount == expectedDiameters && inspection.GeometricToleranceCount == expectedControls)
            return KernelResult<bool>.Success(true);

        var actualDatums = inspection.Success ? inspection.DatumCount : 0;
        var actualDiameters = inspection.Success ? inspection.DimensionCount : 0;
        var detail = inspection.Success ? string.Empty : $" Inspector diagnostics: {string.Join("; ", inspection.Diagnostics)}";
        return KernelResult<bool>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(
            Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
            Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
            $"firmament-v2-pmi-export-evidence-mismatch: validation admitted {expectedDatums} datum, {expectedDiameters} dimension and {expectedControls} geometric-control records; AP242 reinspection found {actualDatums} datum, {actualDiameters} dimension and {inspection.GeometricToleranceCount} geometric-control records.{detail}",
            "FirmamentV2.PmiExportParity")]);
    }


    private static KernelResult<FirmamentStepExportResult> ExportSource(
        string sourceText,
        string? sourceDirectory = null,
        bool allowV1Compatibility = false,
        FirmamentFrontendSchema? explicitSchema = null, IReadOnlyDictionary<string, string>? resources = null,
        string? authoredSource = null)
    {
        authoredSource ??= sourceText;
        // Production mechanical execution consumes the result of AST admission.
        // Its expansion pipeline runs once in the frontend. Unmigrated domain owners
        // retain their existing expansion boundary until their own cutover.
        sourceText = ProfileModificationTemplateLibrary.ResolveImports(sourceText);
        // Fillets where two Compose operations meet (`where: A meets B`): build the body without them, then round the
        // edges between the two operations' faces.
        if (JunctionFilletRoute.Find(sourceText) is { } junction)
        {
            var filleted = JunctionFilletRoute.Export(junction, stripped => ExportSource(stripped, sourceDirectory, allowV1Compatibility, explicitSchema, resources, authoredSource), sourceDirectory);
            return filleted.IsSuccess && filleted.Value.RuntimeAdmissionDocument is null && ParseSemanticSource(junction.Stripped, sourceDirectory).Document is { } admittedJunction
                ? KernelResult<FirmamentStepExportResult>.Success(filleted.Value with { RuntimeAdmissionDocument = admittedJunction }, filleted.Diagnostics)
                : filleted;
        }
        var canonicalParseWatch = System.Diagnostics.Stopwatch.StartNew();
        var v2Parse = FirmamentV2Parser.Parse(sourceText, sourceDirectory, null, explicitSchema, resources);
        canonicalParseWatch.Stop();
        // Fillet every edge on a body no dedicated route takes: the source fails only because of the finish (without
        // it, it parses), or it parses but the edge-finish lowering refuses the whole-body selector. Build the body
        // without the finish, then round it whole, or refuse with the rounding's reason, at the finish. The
        // dedicated Box/Polyhedron builder keeps its own refusals (UniformFillet...).
        KernelResult<FirmamentStepExportResult> Round(UniformRoundingRoute.Request rounding)
        {
            // The admitted document (bodies, assertions) is the one without the finish; assertions then measure the
            // rounded body.
            var rounded = UniformRoundingRoute.Export(rounding, stripped => ExportSource(stripped, sourceDirectory, allowV1Compatibility, explicitSchema, resources));
            return rounded.IsSuccess && rounded.Value.RuntimeAdmissionDocument is null && ParseSemanticSource(rounding.Stripped, sourceDirectory).Document is { } admitted
                ? KernelResult<FirmamentStepExportResult>.Success(rounded.Value with { RuntimeAdmissionDocument = admitted }, rounded.Diagnostics)
                : rounded;
        }
        if (!v2Parse.IsSuccess && UniformRoundingRoute.Find(sourceText) is { } unparsed
            && FirmamentV2Parser.Parse(unparsed.Stripped, sourceDirectory, null, explicitSchema, resources).IsSuccess)
            return Round(unparsed);
        var built = ExportAdmittedSource(sourceText, sourceDirectory, allowV1Compatibility, explicitSchema, resources, v2Parse, canonicalParseWatch);
        if (!built.IsSuccess && !built.Diagnostics.Any(d => d.Message.StartsWith("UniformFillet", StringComparison.Ordinal))
            && UniformRoundingRoute.Find(sourceText) is { } unbuilt)
            return Round(unbuilt);
        if (!built.IsSuccess) return built;
        var accounting = FirmamentFeatureAccounting.Verify(v2Parse, authoredSource, built.Value);
        return accounting.IsSuccess ? KernelResult<FirmamentStepExportResult>.Success(accounting.Value, built.Diagnostics) : accounting;
    }

    private static KernelResult<FirmamentStepExportResult> ExportAdmittedSource(
        string sourceText, string? sourceDirectory, bool allowV1Compatibility, FirmamentFrontendSchema? explicitSchema,
        IReadOnlyDictionary<string, string>? resources, FirmamentV2ParseResult v2Parse, Stopwatch canonicalParseWatch)
    {
        var templateBindWatch = new System.Diagnostics.Stopwatch();
        string materializerSource;
        if (v2Parse.OwnsUnifiedAdmission)
        {
            if (!v2Parse.IsSuccess) return V2ParseFailure(v2Parse);
            materializerSource = v2Parse.BoundSource!;
        }
        else if (v2Parse.Disposition == FirmamentV2ParseDisposition.NotRecognized)
        {
            // The explicit versioned V1 reader below owns compatibility. Do not
            // interpret serialized data as a second V2 expansion input. The later
            // allowV1Compatibility/version checks remain mandatory.
            materializerSource = sourceText;
        }
        else
        {
            var staticDiagnostics = new List<string>();
            var boundaryExpansion = ClosedBoundary2Authoring.Expand(sourceText, staticDiagnostics);
            if (boundaryExpansion is null)
            {
                return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics.Select(diagnostic => new Kernel.Core.Diagnostics.KernelDiagnostic(
                    Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, diagnostic, "FirmamentV2.ClosedBoundary2")).ToArray());
            }
            templateBindWatch.Start();
            var templateExpansion = FirmamentV2TemplateExpansion.Expand(boundaryExpansion.Source, staticDiagnostics);
            templateBindWatch.Stop();
            if (templateExpansion is null)
            {
                return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics.Select(diagnostic => new Kernel.Core.Diagnostics.KernelDiagnostic(
                    Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, diagnostic, "FirmamentV2.TemplateExpansion")).ToArray());
            }
            var featureExpansion = FirmamentV2FeatureExpansion.Expand(templateExpansion.Source, staticDiagnostics);
            if (featureExpansion is null)
            {
                return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics.Select(diagnostic => new Kernel.Core.Diagnostics.KernelDiagnostic(
                    Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, diagnostic, "FirmamentV2.FeatureExpansion")).ToArray());
            }
            var specializedBoundaries = ClosedBoundary2Authoring.Expand(featureExpansion.Source, staticDiagnostics);
            if (specializedBoundaries is null)
                return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics.Select(SchemaDiagnostic).ToArray());
            var staticExpansion = CanonicalStaticAuthoring.Expand(specializedBoundaries.Source, staticDiagnostics);
            if (staticExpansion is null)
            {
                return KernelResult<FirmamentStepExportResult>.Failure(staticDiagnostics
                    .Distinct(StringComparer.Ordinal)
                    .Order(StringComparer.Ordinal)
                    .Select(diagnostic => new Kernel.Core.Diagnostics.KernelDiagnostic(
                        Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
                        Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
                        diagnostic,
                        "FirmamentV2.StaticAuthoring"))
                    .ToArray());
            }
            var materializerInput = staticExpansion.Source;
            materializerSource = FirmamentV2Parser.TryGetCanonicalAdvancedBody(materializerInput, out var canonicalBody) ? canonicalBody : materializerInput;
        }
        if (explicitSchema is { } declaredSchema && FirmamentFrontendSchemas.DomainMismatch(declaredSchema, materializerSource, admittedSchema: v2Parse.BoundSchema) is { } mismatch)
            return KernelResult<FirmamentStepExportResult>.Failure([SchemaDiagnostic(mismatch.Code + ": " + mismatch.Message)]);
        if (v2Parse.BoundSectionChain?.Chain is { } chain)
        {
            var materialized = Aetheris.Surfacing.SectionChainMaterializer.Materialize(chain);
            if (!materialized.IsSuccess || materialized.Body is null)
                return KernelResult<FirmamentStepExportResult>.Failure(materialized.Diagnostics.Select(d => SchemaDiagnostic(d.Code + ":" + d.Message)).ToArray());
            var step = Step242Exporter.ExportBody(materialized.Body, new Step242ExportOptions { ProductName = chain.StableId });
            return step.IsSuccess
                ? KernelResult<FirmamentStepExportResult>.Success(new(step.Value, chain.StableId, 0, "section-chain", "section-chain") { RuntimeBodySourceName = chain.StableId })
                : KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        }
        if (v2Parse.BoundGear is { } gear) return ExportGear(gear);
        if (v2Parse.BoundPlateau is not null || !v2Parse.OwnsUnifiedAdmission && PlateauAuthoring.IsSource(materializerSource))
        {
            if (!v2Parse.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(v2Parse.Diagnostics.Select(SchemaDiagnostic).ToArray());
            return PlateauAuthoring.Compile(materializerSource, v2Parse.BoundPlateau, v2Parse.BoundProfile, v2Parse.ExtrusionHeight);
        }
        if (v2Parse.BoundCoaxialComposition is { } coaxial)
        {
            var built = Kernel.Core.Brep.Features.RevolvedProfileStackEmitter.Emit(coaxial.Topology);
            if (!built.Succeeded || built.Body is null)
                return KernelResult<FirmamentStepExportResult>.Failure(built.Diagnostics.Select(SchemaDiagnostic).ToArray());
            var step = Step242Exporter.ExportBody(built.Body, new Step242ExportOptions { ProductName = coaxial.Name, BrepExportPreflightMode = BrepExportPreflightMode.Enforce });
            if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
            return KernelResult<FirmamentStepExportResult>.Success(new(step.Value, v2Parse.Document!.ModelName, 0, "coaxial-primitive-compose", "compose",
                EngineeringFeatures: coaxial.Spans.Select(span => new FirmamentEngineeringFeatureReport(span.Name, span.Kind,
                    "compose:" + coaxial.Name + "." + span.Name, coaxial.Name, null, null, span.To - span.From, "Height", "Add",
                    MaterializationRoute: "RevolvedProfileStack"))
                    .Concat(coaxial.Chamfers.Select(chamfer => new FirmamentEngineeringFeatureReport(chamfer.Name, "Chamfer",
                        "compose:" + coaxial.Name + "." + chamfer.Name, coaxial.Name, chamfer.On, null, chamfer.Distance, "Distance", "Remove",
                        MaterializationRoute: "RevolvedProfileStack"))).ToArray())
                { RuntimeBody = built.Body, RuntimeBodySourceName = coaxial.Name, MaterializedFeatures = coaxial.Spans.Select(s => new FirmamentFeatureReceipt(coaxial.Name, s.Kind, s.Name)).Concat(coaxial.Chamfers.Select(c => new FirmamentFeatureReceipt(coaxial.Name, "EdgeFinish", c.Name))).ToArray() });
        }
        if (v2Parse.BoundRevolve is { } boundRevolve)
        {
            var authored = boundRevolve;
            if (authored.Hollow is { } revolveHollow) return ExportHollowRevolve(authored, revolveHollow);
            var built = ResolvedProfileRevolveEmitter.TryEmit(authored);
            if (!built.Succeeded || built.Body is null || built.Plan is null)
                return KernelResult<FirmamentStepExportResult>.Failure(built.Diagnostics.Select(message => new Kernel.Core.Diagnostics.KernelDiagnostic(
                    Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "FirmamentV2.Revolve")).ToArray());
            var step = Step242Exporter.ExportBody(built.Body, new Step242ExportOptions { ProductName = authored.Name });
            if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
            var reimport = Step242Importer.ImportBody(step.Value);
            if (!reimport.IsSuccess || reimport.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(reimport.Diagnostics);
            var reimportedManifold = reimport.Value.Topology.Edges.All(edge => reimport.Value.Topology.Coedges.Count(use => use.EdgeId == edge.Id) == 2);
            if (!reimportedManifold)
                return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(
                    Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
                    $"firmament-revolve-step-reimport-not-manifold:{authored.Name}", "FirmamentV2.Revolve")]);
            var surfaces = built.Body.Topology.Faces.Select(face => built.Body.GetFaceSurface(face.Id).Kind).ToArray();
            var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))).ToLowerInvariant();
            var report = new FirmamentRevolveReport(authored.Profile.Name, authored.AxisName, authored.SweepRadians,
                authored.SweepRadians * 180d / Math.PI, authored.AuthoredAlias, authored.SweepRadians < 0d ? "Negative" : "Positive",
                built.Plan.IsFull ? "Full" : "Partial", built.Plan.DeterministicSignature, built.Plan.SurfaceRoles,
                built.Body.Topology.Vertices.Count(), built.Body.Topology.Edges.Count(), built.Body.Topology.Faces.Count(),
                surfaces.Count(kind => kind == SurfaceGeometryKind.Plane), surfaces.Count(kind => kind == SurfaceGeometryKind.Cylinder),
                surfaces.Count(kind => kind == SurfaceGeometryKind.Cone), surfaces.Count(kind => kind == SurfaceGeometryKind.Sphere),
                surfaces.Count(kind => kind == SurfaceGeometryKind.Torus), surfaces.Count(kind => kind == SurfaceGeometryKind.SurfaceOfRevolution),
                reimportedManifold, hash);
            return KernelResult<FirmamentStepExportResult>.Success(new(step.Value, authored.Name, 0, "bounded-revolve", "revolve", Revolve: report,
                EngineeringFeatures: [new(authored.Name, "Revolve", authored.StableId, authored.Name, authored.Axis.StableId, authored.Profile.Name,
                    authored.SweepRadians, "SweepRadians", "Base", PolicySource: "ResolvedProfileRevolveEmitter", MaterializationRoute: "RevolveBRepPlan")]) { RuntimeBodySourceName = authored.Name });
        }
        if (explicitSchema == FirmamentFrontendSchema.WireForm || !v2Parse.OwnsUnifiedAdmission && WireFormAuthoring.IsWireFormSource(materializerSource))
        {
            var parsePhase = BuildPerfTrace.Phase("firmament.wire-parse-and-bind");
            var authored = WireFormAuthoring.Parse(materializerSource);
            parsePhase.Dispose();
            if (!authored.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(authored.Diagnostics);
            var buildPhase = BuildPerfTrace.Phase("firmament.wire-brep-materialize");
            var built = WireFormBRepMaterializer.Build(authored.Value);
            buildPhase.Dispose();
            if (!built.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(built.Diagnostics);
            var stepPhase = BuildPerfTrace.Phase("firmament.step-export");
            var step = Step242Exporter.ExportBody(built.Value.Body, new Step242ExportOptions { ProductName = authored.Value.Name });
            stepPhase.Dispose();
            if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
            var importPhase = BuildPerfTrace.Phase("firmament.step-reimport");
            var reimport = Step242Importer.ImportBody(step.Value);
            importPhase.Dispose();
            if (!reimport.IsSuccess || reimport.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(reimport.Diagnostics);
            var manifold = reimport.Value.Topology.Edges.All(edge => reimport.Value.Topology.Coedges.Count(use => use.EdgeId == edge.Id) == 2);
            if (!manifold) return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(
                Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
                "wireform-step-reimport-not-manifold: exported WireForm did not reimport as an enclosed manifold.", "FirmamentV2.WireForm")]);
            var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))).ToLowerInvariant();
            var reportPhase = BuildPerfTrace.Phase("firmament.wire-report-validation");
            var report = WireFormReportFactory.Create(built.Value, hash, manifold);
            reportPhase.Dispose();
            return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, authored.Value.Name, 0,
                "wire-form", "wireform", WireForm: report,
                EngineeringFeatures: authored.Value.Operations.Select(operation => new FirmamentEngineeringFeatureReport(
                    operation.Name, operation switch { WireStraightAir => "Straight", WireBendAir => "Bend", WireAxisCoilAir => "Helix", WireSurfaceCoilAir => "SurfaceCoil", WireKnotPathAir => "KnotPath", _ => "Unknown" }, operation.StableId(authored.Value.Name),
                    authored.Value.Name, "WireState", "CircularSection", operation.LengthMm, "CenterlineLength", "Add",
                    PolicySource: "WireFormFeatureAir", MaterializationRoute: "WireFormCenterlineAir->CircularSweepBRepPlan")).ToArray())
                { RuntimeBody = reimport.Value, RuntimeBodySourceName = authored.Value.Name }, []);
        }
        if (explicitSchema == FirmamentFrontendSchema.Sweep || !v2Parse.OwnsUnifiedAdmission && CircularSweepAuthoring.IsSweepSource(materializerSource))
        {
            var airWatch = System.Diagnostics.Stopwatch.StartNew();
            var authored = CircularSweepAuthoring.Parse(materializerSource);
            airWatch.Stop();
            if (!authored.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(authored.Diagnostics);
            var brepWatch = System.Diagnostics.Stopwatch.StartNew();
            var built = CircularSweepBRepMaterializer.Build(authored.Value);
            brepWatch.Stop();
            if (!built.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(built.Diagnostics);
            var stepWatch = System.Diagnostics.Stopwatch.StartNew();
            var step = Step242Exporter.ExportBody(built.Value.Body, new Step242ExportOptions { ProductName = authored.Value.Name });
            stepWatch.Stop();
            if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
            var reimportWatch = System.Diagnostics.Stopwatch.StartNew();
            var reimport = Step242Importer.ImportBody(step.Value);
            reimportWatch.Stop();
            if (!reimport.IsSuccess || reimport.Value is null)
                return KernelResult<FirmamentStepExportResult>.Failure(reimport.Diagnostics);
            var reimportedManifold = reimport.Value.Topology.Edges.All(edge => reimport.Value.Topology.Coedges.Count(use => use.EdgeId == edge.Id) == 2);
            if (!reimportedManifold)
                return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(
                    Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
                    "firmament-sweep-step-reimport-not-manifold: exported Sweep did not reimport as an enclosed manifold.", "FirmamentV2.Sweep")]);
            var surfaces = built.Value.Body.Topology.Faces.Select(face => built.Value.Body.GetFaceSurface(face.Id).Kind).ToArray();
            var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))).ToLowerInvariant();
            var report = new FirmamentSweepReport(
                authored.Value.Path.Name, authored.Value.Path.Segments.Count, authored.Value.Diameter, built.Value.CenterlineLength,
                built.Value.Volume, built.Value.MassKilograms, built.Value.Bounds, authored.Value.Material.Identity.FirmamentPath,
                surfaces.Count(kind => kind == SurfaceGeometryKind.Cylinder), surfaces.Count(kind => kind == SurfaceGeometryKind.Torus),
                surfaces.Count(kind => kind == SurfaceGeometryKind.Plane), true, hash, true, true,
                "Nonadjacent line pairs are exact; arc-involving clearance uses a deterministic conservative chord witness.",
                new(templateBindWatch.Elapsed.TotalMilliseconds, canonicalParseWatch.Elapsed.TotalMilliseconds,
                    airWatch.Elapsed.TotalMilliseconds, brepWatch.Elapsed.TotalMilliseconds, stepWatch.Elapsed.TotalMilliseconds,
                    reimportWatch.Elapsed.TotalMilliseconds));
            return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, authored.Value.Name, 0,
                "circular-sweep", "sweep", Sweep: report,
                EngineeringFeatures: [new(authored.Value.Name, "Sweep", "sweep:" + authored.Value.Name, authored.Value.Name,
                    authored.Value.Path.StableId, "Circle", authored.Value.Diameter, "Diameter", "Add", PolicySource: "CircularSweepFeatureAir", MaterializationRoute: "CircularSweepBRepPlan")]) { RuntimeBodySourceName = authored.Value.Name },
                []);
        }
        if (v2Parse.BoundComposition is not null || (!v2Parse.OwnsUnifiedAdmission && PrismaticProfileCompositionParser.IsCompositionSource(materializerSource)))
        {
            var parsed = v2Parse.BoundComposition ?? PrismaticProfileCompositionParser.Parse(materializerSource);
            if (TryExportProfileCornerHost(materializerSource, parsed, v2Parse.DiagnosticSource, v2Parse.Document) is { } cornerHost)
                return cornerHost;
            var stack = PrismaticSectionStackCompiler.Normalize(parsed, out var diagnostics);
            if (stack is null)
                return KernelResult<FirmamentStepExportResult>.Failure(diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.ProfileComposition")).ToArray());
            var emitted = PrismaticSectionStackEmitter.Emit(stack);
            if (emitted.Body is null)
                return KernelResult<FirmamentStepExportResult>.Failure(emitted.Diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.ProfileComposition")).ToArray());
            if (ApplyConstructionPlaneBlindDrills(stack, emitted, out var drilled) is { } drillFailure) return drillFailure;
            emitted = drilled;
            foreach (var faceHole in stack.Feature.FaceHoles)
            {
                emitted = PlanarFaceThroughHole.Apply(emitted, faceHole);
                if (emitted.Body is null)
                    return KernelResult<FirmamentStepExportResult>.Failure(emitted.Diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.FaceHole")).ToArray());
            }
            if (materializerSource.Contains("EdgeFinish", StringComparison.Ordinal))
                return ExportComposedSemanticTopBoundaryChamfer(materializerSource, parsed, stack, emitted, v2Parse.Document);
            // The composition route either retained the checked body above or
            // replaced it with a checked blind-drill materialization.
            var completedBody = emitted.Body;
            if (completedBody is null)
                return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, "profile-composition-materialization-missing-body", "FirmamentV2.ProfileComposition")]);
            var semanticPmi = Array.Empty<Step242SemanticPmi>();
            if (v2Parse.IsSuccess && v2Parse.Document is not null)
            {
                var support = ValidateV2PmiExportSupport(v2Parse.Document);
                if (!support.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(support.Diagnostics);
                var features = (stack.Feature.ShaftHoles ?? []).ToDictionary(hole => hole.Name, hole => hole.StableId, StringComparer.Ordinal);
                foreach (var hole in stack.Feature.CounterboreHoles ?? []) features[hole.Name] = hole.StableId;
                foreach (var hole in stack.Feature.CountersinkHoles ?? []) features[hole.Name] = hole.StableId;
                semanticPmi = BuildV2SemanticPmi(v2Parse.Document, [], stack.Feature.Name, features, emitted.Correspondence, completedBody,
                    ComposeOperationCapFaces(stack.Feature, completedBody, emitted.Correspondence), stack.Feature).ToArray();
            }
            var step = Step242Exporter.ExportBody(completedBody, semanticPmi);
            if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
            return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, stack.Feature.Name, 0, "prismatic-section-stack", "line-arc-profile-composition",
                DatumInspection: v2Parse.Document?.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.DatumPlane).Select(p => new FirmamentPmiInspectionDatum(p.Name, "planar", p.Target)).ToArray() ?? [],
                DimensionInspection: v2Parse.Document?.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.HoleDiameter).Select(p => new FirmamentPmiInspectionDimension("Diameter", p.Target, null, p.Value ?? 0d, "explicit-v2-record-pmi", p.Name)).ToArray() ?? [],
                Features: CompositionHoleReports(stack.Feature, completedBody, emitted.Correspondence),
                EngineeringFeatures: EngineeringFeatureReports(stack.Feature))
            { RuntimeBody = completedBody, RuntimeCorrespondence = emitted.Correspondence, RuntimeBodySourceName = stack.Feature.Name, MaterializedFeatures = FirmamentFeatureAccounting.Composition(stack, emitted.Correspondence) });
        }
        if (v2Parse.BoundProfile is not null || (!v2Parse.OwnsUnifiedAdmission && ProfileAuthoringParser.IsProfileSource(materializerSource)))
        {
            var parsed = v2Parse.BoundProfile is { } boundProfile
                ? (Profile: (ResolvedProfile2D?)boundProfile, Height: v2Parse.ExtrusionHeight, Diagnostics: (IReadOnlyList<string>)[])
                : ProfileAuthoringParser.Parse(materializerSource);
            if (parsed.Profile is null) return KernelResult<FirmamentStepExportResult>.Failure(parsed.Diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.Profile")).ToArray());
            var emitted = ResolvedProfile2DValidator.Extrude(parsed.Profile, parsed.Height);
            if (emitted.Status != LineArcProfileExtrudeStatus.Succeeded || emitted.Body is null) return KernelResult<FirmamentStepExportResult>.Failure(emitted.Diagnostics.Select(x => new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.Profile")).ToArray());
            var extrusionName = FirmamentV2Parser.MechanicalDeclarations(FirmamentSyntaxParser.Parse(materializerSource).Document.Statements)
                .FirstOrDefault(d => d.Type.Name.Text == "Extrude")?.Name?.Text ?? parsed.Profile.Name;
            if (ProfileLongitudinalEdgeFinish.Requested(materializerSource))
                return ExportLongitudinalFinish(materializerSource, parsed.Profile, parsed.Height, extrusionName, v2Parse.DiagnosticSource);
            if (materializerSource.Contains("EdgeFinish", StringComparison.Ordinal))
                return ExportProfileSemanticTopBoundaryChamfer(materializerSource, parsed.Profile, parsed.Height, emitted, v2Parse.DiagnosticSource);
            var step = Step242Exporter.ExportBody(emitted.Body); if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
            var profileCorrespondence = ProfileDisplayCorrespondence(parsed.Profile, emitted, extrusionName);
            return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, parsed.Profile.Name, 0, "profile-extrude", "line-arc-profile") {
                RuntimeBody = emitted.Body, RuntimeCorrespondence = profileCorrespondence, RuntimeBodySourceName = extrusionName });
        }
        if (v2Parse.IsSuccess && v2Parse.Document is not null)
        {
            if (v2Parse.Document.Solids.Count == 0 && v2Parse.Document.Panels is { Count: > 0 })
            {
                return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(
                    Kernel.Core.Diagnostics.KernelDiagnosticCode.NotImplemented,
                    Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
                    "firmament-panel-only-step-materialization-unsupported: the document contains authored Panels but no solid body. Panel geometry remains available to public pre-realization predicates; the ordinary STEP build route does not yet define a shell/product export contract.",
                    "FirmamentV2.Panel")]);
            }

            var dfm = FirmamentV2DfmEnforcement.Validate(v2Parse.Document);
            if (!dfm.IsSuccess)
            {
                return KernelResult<FirmamentStepExportResult>.Failure(dfm.Diagnostics);
            }
            if (v2Parse.Document.PathFeatures.Count > 0)
                return ExportPathFeatures(v2Parse.Document);

            if (v2Parse.Document.Solids.Any(s => s.InlineStep?.SourceHashPin is not null)
                && (v2Parse.Document.Solids.Count != 1 || v2Parse.Document.Replacements is { Count: > 0 } || v2Parse.Document.Removals.Count > 0
                    || v2Parse.Document.ModifyBlocks is { Count: > 0 }))
                return ExportPinnedImportedRevision(v2Parse.Document);

            if (TryExportV2StandaloneCubicLattice(v2Parse.Document) is { } latticeExport)
            {
                return latticeExport;
            }

            if (TryExportV2HollowBody(v2Parse.Document) is { } hollowExport)
            {
                return hollowExport;
            }

            if (TryExportV2RoundedBoxBody(v2Parse.Document) is { } roundedBoxExport)
            {
                return roundedBoxExport;
            }

            if (TryExportV2ThreadBody(v2Parse.Document) is { } threadExport)
            {
                return threadExport;
            }

            if (TryExportV2ExactCoaxialPart(v2Parse.Document) is { } exactCoaxialExport)
            {
                return exactCoaxialExport;
            }

            if (TryExportV2StandardPart(v2Parse.Document) is { } standardPartExport)
            {
                return standardPartExport;
            }
            if (TryExportV2PerforationBody(v2Parse.Document) is { } perforationExport)
            {
                return perforationExport;
            }

            // Do not let the existing semantic-hole route silently export the unmodified host.
            // M9 has an explicit AIR/graph contract, but the authoritative single-body merge
            // (retained box-with-void plus analytic struts/nodes/bonds) is not yet materialized.
            if (v2Parse.Document.LatticeFills is { Count: > 0 })
            {
                return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(
                    Kernel.Core.Diagnostics.KernelDiagnosticCode.NotImplemented,
                    Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
                    "lattice-fill-brep-plan-not-materialized: M9 parsed and DFM-validated the explicit FillRegion, but the current BRep backend cannot emit the required single authoritative body combining an internal box cavity, a preserved through-hole, and bonded analytic lattice members. No STEP artifact was emitted.",
                    "FirmamentV2.LatticeFill")]);
            }

            var routed = DispatchV2Routes(v2Parse.Document,
                ("CombinedHoleEdgeFinish", TryExportV2CombinedHoleEdgeFinishBody),
                ("AirChamfer", TryExportV2AirChamferBody),
                ("SemanticHole", TryExportV2SemanticHoleBody),
                ("ControlledSideHole", TryExportV2ControlledSideHoleBody),
                ("InlineStepReplacement", TryExportV2InlineStepReplacementBody),
                ("InlineStep", TryExportV2InlineStepBody));
            if (routed is not null)
            {
                return routed;
            }

            var lowering = FirmamentV2BuildLowering.LowerPrimitiveBridge(v2Parse.Document);
            if (!lowering.IsSuccess)
            {
                return KernelResult<FirmamentStepExportResult>.Failure(lowering.Diagnostics);
            }

            var execution = FirmamentPrimitiveExecutor.Execute(lowering.Value);
            if (!execution.IsSuccess)
            {
                var span = (v2Parse.Document.ModifyBlocks ?? []).SelectMany(m => m.EdgeFinishes ?? []).FirstOrDefault(f => f.Target == "AllEdges")?.SourceSpan ?? v2Parse.Document.Solid.SourceSpan;
                return KernelResult<FirmamentStepExportResult>.Failure(execution.Diagnostics.Select(d => d with
                { SourceSpan = span is { } location ? new(location.Start, location.Length) : d.SourceSpan }).ToArray());
            }

            var executedPrimitive = execution.Value.ExecutedPrimitives.LastOrDefault();
            if (executedPrimitive is null)
            {
                return KernelResult<FirmamentStepExportResult>.Failure(execution.Diagnostics);
            }

            var semanticPmi = BuildV2SemanticPmi(v2Parse.Document, [], executedPrimitive.FeatureId, body: executedPrimitive.Body);
            var step = Step242Exporter.ExportBody(executedPrimitive.Body, semanticPmi);
            if (!step.IsSuccess)
            {
                return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
            }

            var primitiveExport = new FirmamentStepExportResult(
                    step.Value,
                    executedPrimitive.FeatureId,
                    executedPrimitive.OpIndex,
                    "primitive",
                    v2Parse.Document.Solid.RecordType.ToLowerInvariant(),
                    DatumInspection: v2Parse.Document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.DatumPlane).Select(p => new FirmamentPmiInspectionDatum(p.Name, "planar", p.Target)).ToArray() ?? [],
                    DimensionInspection: [])
            {
                RuntimeBody = executedPrimitive.Body,
                MaterializedFeatures = (v2Parse.Document.ModifyBlocks ?? []).SelectMany(m => (m.EdgeFinishes ?? []).Where(f => f.Target == "AllEdges").Select(f => new FirmamentFeatureReceipt(m.TargetSolid, "EdgeFinish", f.Name))).ToArray(),
                Cir = FirmamentCirRetention.FromRoot(execution.Value.NativeGeometryState.CirMirror.RuntimeRoot, step.Value,
                    exportedPrimitive: execution.Value.ExecutedPrimitives.Count == 1 && execution.Value.ExecutedBooleans.Count == 0)
            };
            if (executedPrimitive.Kind == FirmamentLoweredPrimitiveKind.Box
                && executedPrimitive.BoxConstructionTopology is { } boxTopology
                && v2Parse.Document.Solids.Count == 1
                && execution.Value.ExecutedBooleans.Count == 0)
                primitiveExport = primitiveExport with
                {
                    RuntimeBody = executedPrimitive.Body,
                    RuntimeCorrespondence = BoxConstructionCorrespondence.Create(executedPrimitive.FeatureId, boxTopology,
                        v2Parse.Document.Solids.Single(s => s.Name == executedPrimitive.FeatureId).SourceSpan)
                };
            return KernelResult<FirmamentStepExportResult>.Success(primitiveExport);
        }

        if (v2Parse.Diagnostics.Contains(FirmamentV2Parser.InlineStepRequiresCanonical, StringComparer.Ordinal))
        {
            return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(
                Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
                Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
                "firmament-inline-step-requires-aetheris-canonical-step: Inline STEP requires an Aetheris-canonical AP242 file. Run `aetheris canon <input.step> --out <canonical.step>` first.",
                "FirmamentV2.InlineStep")]);
        }

        if (v2Parse.Diagnostics.Any(d => d.StartsWith("firmament-v2-inline-step-", StringComparison.Ordinal)))
        {
            return KernelResult<FirmamentStepExportResult>.Failure(v2Parse.Diagnostics.Select(d => new Kernel.Core.Diagnostics.KernelDiagnostic(
                Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
                Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
                d,
                "FirmamentV2.InlineStep")).ToArray());
        }

        if (v2Parse.Disposition == FirmamentV2ParseDisposition.RecognizedInvalid)
            return V2ParseFailure(v2Parse);

        if (!allowV1Compatibility)
        {
            return V2SourceRequired(v2Parse);
        }

        // V1 is not a peer authoring route. File builds admit it only when the
        // historical reader proves that the document explicitly declares version 1.
        // This prevents V1's permissive serialization parser from accepting malformed
        // or serialization-shaped V2 input.
        var compatibility = new Compatibility.V1.LegacyFirmamentV1SourceReader().ReadAuto(sourceText);
        if (!compatibility.IsSuccess)
        {
            return KernelResult<FirmamentStepExportResult>.Failure(compatibility.Diagnostics);
        }
        if (!string.Equals(compatibility.Value.Firmament.Version, "1", StringComparison.Ordinal))
        {
            return V2SourceRequired(v2Parse);
        }

        return ExportV1CompatibilitySource(sourceText);
    }

    private static KernelResult<FirmamentStepExportResult> ExportGear(GearAuthoringDocument authored)
    {
        if (!authored.IsSuccess)
            return KernelResult<FirmamentStepExportResult>.Failure(authored.Diagnostics.Select(message => new Kernel.Core.Diagnostics.KernelDiagnostic(
                Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
                message, "Firmament.GearAir")).ToArray());
        if (authored.Gears.Count != 1)
            return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(
                Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
                $"{GearAuthoring.Prefix}build-body-count-invalid:expected=1:actual={authored.Gears.Count}:use-Assembly-for-a-gear-train",
                "Firmament.GearAir")]);
        var gear = authored.Gears[0];
        var materialized = GearAuthoring.Materialize(gear, out var materializationDiagnostics);
        if (materialized is null)
            return KernelResult<FirmamentStepExportResult>.Failure(materializationDiagnostics.Select(message => new Kernel.Core.Diagnostics.KernelDiagnostic(
                Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
                message, "Firmament.GearBRep")).ToArray());
        var step = Step242Exporter.ExportBody(materialized.Body, new Step242ExportOptions
        {
            ProductName = gear.Name,
            ApplicationName = "Aetheris.Firmament.GearLibrary.X0"
        });
        if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        var reimport = Step242Importer.ImportBody(step.Value);
        var reimportedManifold = reimport.IsSuccess && reimport.Value is not null && FirmamentManifoldChecker.IsManifold(reimport.Value);
        if (!reimportedManifold)
            return KernelResult<FirmamentStepExportResult>.Failure(reimport.Diagnostics.Append(new Kernel.Core.Diagnostics.KernelDiagnostic(
                Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
                $"{GearAuthoring.Prefix}step-reimport-not-manifold:{gear.Name}", "Firmament.GearBRep")).ToArray());
        var surfaces = materialized.Body.Topology.Faces.Select(face => materialized.Body.GetFaceSurface(face.Id).Kind).ToArray();
        var item = new FirmamentGearItemReport(gear.Name, gear.Family.ToString(), gear.Teeth, gear.ModuleMm, gear.PressureAngleDegrees,
            gear.PitchDiameterMm, gear.BaseDiameterMm, gear.AddendumDiameterMm, gear.RootDiameterMm, gear.FaceWidthMm,
            gear.BoreDiameterMm, gear.PhaseDegrees, gear.BacklashMm, gear.PitchConeAngleDegrees, gear.Axis,
            materialized.ToothProfileCurveCount, materialized.InvoluteSpanCount, materialized.MaximumInvoluteApproximationErrorMm,
            materialized.ToothConstruction, materialized.StableToothIds);
        var interfaces = authored.Interfaces.Select(value => new FirmamentGearInterfaceReport(value.Name, value.A.Name, value.B.Name,
            value.Kind, value.Compatible, value.ExpectedCenterDistanceMm, value.Ratio, value.RotationSign,
            value.AxisRelation, value.ShaftAngleDegrees, value.EngagementPhaseDegrees, value.AllowedDirection, value.RejectionReasons)).ToArray();
        var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))).ToLowerInvariant();
        var report = new FirmamentGearReport(authored.ModelName, [item], interfaces,
            materialized.Body.Topology.Vertices.Count(), materialized.Body.Topology.Edges.Count(), materialized.Body.Topology.Faces.Count(),
            surfaces.Count(kind => kind == SurfaceGeometryKind.Plane), surfaces.Count(kind => kind == SurfaceGeometryKind.Cylinder),
            surfaces.Count(kind => kind == SurfaceGeometryKind.Cone), surfaces.Count(kind => kind == SurfaceGeometryKind.BSplineSurfaceWithKnots),
            surfaces.Count(kind => kind == SurfaceGeometryKind.LinearExtrusion), FirmamentManifoldChecker.IsManifold(materialized.Body),
            true, true, hash, "DeterministicExactBRepAP242", gear.Family is GearFamily.BevelGear or GearFamily.MiterGear ? "BoundedStraightBevel" : "QualifiedX0");
        return KernelResult<FirmamentStepExportResult>.Success(new(step.Value, $"gear:{gear.Name}", 0, "gear", gear.Family.ToString(), Gear: report) { RuntimeBodySourceName = gear.Name });
    }

    private static FirmamentV2ParseResult ParseSemanticSource(string source, string? sourceDirectory)
        => FirmamentV2Parser.Parse(source, sourceDirectory);

    private static Kernel.Core.Diagnostics.KernelDiagnostic SchemaDiagnostic(string message) => new(
        Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
        Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
        message,
        "Firmament.Schema");

    private static IReadOnlyList<Kernel.Core.Diagnostics.KernelDiagnostic> LibraryDiagnostics(IEnumerable<string> diagnostics) =>
        diagnostics.Select(message => new Kernel.Core.Diagnostics.KernelDiagnostic(
            Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
            Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
            message,
            "FirmamentV2.LibraryResolution")).ToArray();

    private static KernelResult<FirmamentStepExportResult> V2ParseFailure(FirmamentV2ParseResult parse)
    {
        var syntaxCodes = parse.SyntaxDiagnostics.Select(d => d.Code).ToHashSet(StringComparer.Ordinal);
        // parse-failed is a result status, used only when the producer supplied no explanation.
        var errors = parse.Diagnostics.Where(FirmamentV2Parser.IsFatalDiagnosticCode).Where(code => code != "firmament-v2-parse-failed" && !syntaxCodes.Contains(code))
            .Concat(parse.SyntaxDiagnostics.Select(d => d.Code + ": " + d.Message)).Distinct(StringComparer.Ordinal).ToArray();
        // A bare code is redundant beside the same code with its parameters and explanation.
        errors = errors.Where(code => code.Contains(':') || !errors.Any(other => other.StartsWith(code + ":", StringComparison.Ordinal))).ToArray();
        if (errors.Length == 0) errors = ["firmament-v2-parse-failed"];
        return KernelResult<FirmamentStepExportResult>.Failure(errors.Select(code => new KernelDiagnostic(
            KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, code, "FirmamentV2.Parse")).ToArray());
    }

    private static KernelResult<FirmamentStepExportResult> V2SourceRequired(FirmamentV2ParseResult parse)
    {
        var fatal = parse.Diagnostics
            .Where(FirmamentV2Parser.IsFatalDiagnosticCode)
            .Distinct(StringComparer.Ordinal)
            .Select(code => new Kernel.Core.Diagnostics.KernelDiagnostic(
                Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
                Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
                code,
                "FirmamentV2.Parse"))
            .ToList();
        fatal.Add(new Kernel.Core.Diagnostics.KernelDiagnostic(
            Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
            Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
            "firmament-v2-source-required: canonical in-memory compilation requires Firmament V2; historical V1 is accepted only from an explicitly versioned file compatibility input.",
            "FirmamentV2.CompatibilityFirewall"));
        return KernelResult<FirmamentStepExportResult>.Failure(fatal);
    }

    private static KernelResult<FirmamentStepExportResult> ExportV1CompatibilitySource(string sourceText)
    {
        var legacy = FirmamentStepExporter.Export(new FirmamentCompileRequest(new FirmamentSourceDocument(sourceText)));
        if (!legacy.IsSuccess)
        {
            return legacy;
        }

        return KernelResult<FirmamentStepExportResult>.Success(legacy.Value, [
            .. legacy.Diagnostics,
            new Kernel.Core.Diagnostics.KernelDiagnostic(
                Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
                Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Warning,
                "firmament-v1-compatibility-input: historical Firmament V1 source was accepted through the compatibility build route; Firmament V2 is the canonical authoring language.",
                "FirmamentV1.Compatibility")]);
    }

    private static KernelResult<FirmamentStepExportResult>? TryExportV2StandardPart(FirmamentV2Document document)
    {
        if (document.Solids.Count != 1 || document.Solid.StandardPart is not { } authored) return null;
        var definition = StandardLibraryReusableParts.TryCreate(authored.Family, authored.Parameters, deferMakerMarkToCompiler: true);
        if (!definition.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(definition.Diagnostics);
        if (definition.Value.HexBolt is not { } bolt)
        {
            return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(
                Kernel.Core.Diagnostics.KernelDiagnosticCode.NotImplemented,
                Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
                $"Firmament V2 StandardPart family '{authored.Family}' does not publish a typed part definition.",
                "FirmamentV2.StandardPart")]);
        }

        var step = Step242Exporter.ExportBody(definition.Value.Body);
        if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        var semantics = bolt.Semantics.Descendants.Select(descendant => new FirmamentStandardPartSemanticReport(
            descendant.StableId,
            descendant.Kind.ToString(),
            descendant.ParentStableId,
            descendant.Face?.Value,
            descendant.Metadata)).ToArray();
        var report = new FirmamentStandardPartReport(
            authored.Family,
            document.StaticAuthoring?.Templates.SingleOrDefault()?.Name,
            bolt.DeterministicSignature,
            authored.Parameters,
            semantics);
        return ApplyHexBoltMakerMark(new FirmamentStepExportResult(
            step.Value,
            bolt.Semantics.BodyStableId,
            0,
            "standard-part",
            authored.Family,
            ConceptIr: document.ConceptIr,
            StandardPart: report) { RuntimeBody = bolt.Body });
    }

    private static KernelResult<FirmamentStepExportResult>? TryExportV2ThreadBody(FirmamentV2Document document)
    {
        if (document.Threads is not { Count: > 0 }) return null;
        KernelResult<FirmamentStepExportResult> Failure(string code, string message) =>
            KernelResult<FirmamentStepExportResult>.Failure([new KernelDiagnostic(
                KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,
                $"thread-{code}: {message}", "FirmamentV2.Thread")]);
        if (document.Threads.Count != 1 || document.Solids.Count != 1 || (document.ModifyBlocks?.Count ?? 0) != 0)
            return Failure("composition-unsupported", "X1 admits one Thread on one unmodified cylindrical support.");
        var feature = document.Threads[0];
        var solid = document.Solid;
        if (feature.SupportSolid != solid.Name)
            return Failure("support-unresolved", $"Surface refers to '{feature.SupportSolid}', but the authored solid is '{solid.Name}'.");
        if (solid.StandardPart is { } authoredPart && feature.SupportRole == "Shank")
            return TryExportV2HexBoltThread(document, feature, authoredPart);
        if (solid.Cylinder is not { } support || feature.SupportRole != "OuterWall")
            return Failure("support-not-cylinder", "Surface must bind to face(<Cylinder>.OuterWall), an analytic cylindrical support.");
        if (!double.IsFinite(feature.MajorDiameterMm) || feature.MajorDiameterMm <= 0d ||
            double.Abs(feature.MajorDiameterMm - 2d * support.Radius) > 1e-6d)
            return Failure("major-diameter-incompatible", "MajorDiameter must be positive and equal to the cylindrical precursor stock diameter.");
        if (!double.IsFinite(feature.PitchMm) || feature.PitchMm <= 0d)
            return Failure("pitch-invalid", "Pitch must be finite and positive.");
        if (!double.IsFinite(feature.LengthMm) || feature.LengthMm <= 0d)
            return Failure("length-invalid", "Length must be finite and positive.");
        if (feature.StartOffsetMm is { } authoredOffset && (!double.IsFinite(authoredOffset) || authoredOffset < 0d))
            return Failure("start-offset-invalid", "StartOffset must be finite and nonnegative.");

        // External 60-degree truncated profile: root width 5P/6 and crest P/8.
        // Each flank has axial run 17P/48, giving depth 17*sqrt(3)*P/48.
        var rootWidth = 5d * feature.PitchMm / 6d;
        var crestWidth = feature.PitchMm / 8d;
        var depth = (rootWidth - crestWidth) * double.Sqrt(3d) / 2d;
        var rootRadius = feature.MajorDiameterMm / 2d - depth;
        if (rootRadius <= 0d)
            return Failure("profile-self-intersection", "The 60-degree profile depth consumes the support radius.");
        var grooveWidth = feature.PitchMm - crestWidth;
        var grooveBottomWidth = feature.PitchMm - rootWidth;
        var start = feature.StartOffsetMm ?? grooveWidth / 2d + 1d;
        var end = start + feature.LengthMm;
        if (start - grooveWidth / 2d <= 1e-6d || end + grooveWidth / 2d >= support.Height - 1e-6d)
            return Failure("support-bounds", "Thread footprint requires exposed cylindrical stock before and after its finite span.");
        var buildStart = Stopwatch.GetTimestamp();
        var rib = HelicalRibGeometry.Create(new HelicalRibParameters(Point3D.Origin,
            Direction3D.Create(new Vector3D(0d, 0d, 1d)), Direction3D.Create(new Vector3D(1d, 0d, 0d)),
            0d, support.Height, feature.MajorDiameterMm / 2d, rootRadius, feature.PitchMm,
            start, end, grooveWidth, grooveBottomWidth, Intent: HelicalProfileIntent.RemoveGroove));
        if (!rib.IsSuccess) return Failure("geometry-invalid", string.Join(" | ", rib.Diagnostics.Select(d => d.Message)));
        var built = BrepHelicalRib.Create(rib.Value);
        if (!built.IsSuccess) return Failure("brep-invalid", string.Join(" | ", built.Diagnostics.Select(d => d.Message)));
        var constructionMs = Stopwatch.GetElapsedTime(buildStart).TotalMilliseconds;
        var featureId = $"{solid.Name}.{feature.Name}";
        var exportStart = Stopwatch.GetTimestamp();
        var step = Step242Exporter.ExportBody(built.Value.Body, new Step242ExportOptions
        {
            ProductName = featureId,
            ApplicationName = "Aetheris.Firmament.Thread.External.X1",
            BrepExportPreflightMode = BrepExportPreflightMode.Enforce
        });
        if (!step.IsSuccess) return Failure("step-export-failed", string.Join(" | ", step.Diagnostics.Select(d => d.Message)));
        var exportMs = Stopwatch.GetElapsedTime(exportStart).TotalMilliseconds;
        var faceDescendants = built.Value.FaceRoles.Select(pair => new SemanticTopologyDescendant(
            $"{featureId}.Face[{pair.Key.Value}]", "Face", pair.Value switch
            {
                var role when role.StartsWith("LeadingFlank", StringComparison.Ordinal) => SemanticTopologyRole.ThreadLeadingFlank,
                var role when role.StartsWith("TrailingFlank", StringComparison.Ordinal) => SemanticTopologyRole.ThreadTrailingFlank,
                var role when role.StartsWith("Crest", StringComparison.Ordinal) => SemanticTopologyRole.ThreadRootFace,
                var role when role.StartsWith("RootCylinderSkin", StringComparison.Ordinal) => SemanticTopologyRole.ThreadCrest,
                "StartCap" => SemanticTopologyRole.ThreadStartCap,
                "EndCap" => SemanticTopologyRole.ThreadEndCap,
                _ => SemanticTopologyRole.ThreadRootFace
            }, featureId, Face: pair.Key, ParentStableId: featureId,
            Addressability: SemanticTopologyAddressability.DerivedStable));
        var edgeDescendants = built.Value.EdgeRoles.Select(pair => new SemanticTopologyDescendant(
            $"{featureId}.Edge[{pair.Key.Value}]", "Edge", SemanticTopologyRole.ThreadBoundaryEdge,
            featureId, Edge: pair.Key, ParentStableId: featureId,
            Addressability: SemanticTopologyAddressability.DerivedStable));
        var descendants = faceDescendants.Concat(edgeDescendants).ToArray();
        var correspondence = new SemanticTopologyCorrespondence(featureId, descendants,
            ["Thread", "HelicalRib", "BrepHelicalRib"],
            new Dictionary<string, FirmamentV2SourceSpan> { [featureId] = feature.SourceSpan });
        var report = new FirmamentThreadReport(featureId, $"face({solid.Name}.{feature.SupportRole})",
            feature.MajorDiameterMm, 2d * rootRadius, feature.PitchMm, feature.PitchMm, feature.LengthMm,
            start, start, feature.Hand, "metric-60-degree-truncated", (int)double.Round(rib.Value.Turns), built.Value.Body.Topology.Faces.Count(),
            built.Value.Body.Topology.Edges.Count(), built.Value.Body.Topology.Vertices.Count(),
            built.Value.SeamSplits, constructionMs, exportMs,
            Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))))
        { HeadSideLandMm = start - grooveWidth / 2d, TipSideLandMm = support.Height - end - grooveWidth / 2d };
        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(
            step.Value, featureId, 0, "thread-external", "metric-60-degree", Thread: report)
        { RuntimeBody = built.Value.Body, RuntimeCorrespondence = correspondence });
    }

    private static KernelResult<FirmamentStepExportResult> TryExportV2HexBoltThread(
        FirmamentV2Document document, FirmamentV2ThreadDecl feature, FirmamentV2StandardPartRecord authoredPart)
    {
        KernelResult<FirmamentStepExportResult> Failure(string code, string message) =>
            KernelResult<FirmamentStepExportResult>.Failure([new KernelDiagnostic(
                KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,
                $"thread-{code}: {message}", "FirmamentV2.Thread")]);
        if (authoredPart.Family != "HexBolt")
            return Failure("support-not-hexbolt", "face(Bolt.Shank) is admitted only for the HexBolt standard part.");
        var definition = StandardLibraryReusableParts.TryCreate(authoredPart.Family, authoredPart.Parameters, deferMakerMarkToCompiler: true);
        if (!definition.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(definition.Diagnostics);
        var bolt = definition.Value.HexBolt!;
        if (!double.IsFinite(feature.MajorDiameterMm) || feature.MajorDiameterMm <= 0d ||
            Math.Abs(feature.MajorDiameterMm - bolt.Spec.NominalDiameter) > 1e-6d)
            return Failure("major-diameter-incompatible", "MajorDiameter must equal the HexBolt precursor shank diameter.");
        if (!double.IsFinite(feature.PitchMm) || feature.PitchMm <= 0d)
            return Failure("pitch-invalid", "Pitch must be finite and positive.");
        if (!double.IsFinite(feature.LengthMm) || feature.LengthMm <= 0d)
            return Failure("length-invalid", "Length must be finite and positive.");
        if (feature.StartOffsetMm is { } authoredOffset && (!double.IsFinite(authoredOffset) || authoredOffset < 0d))
            return Failure("start-offset-invalid", "StartOffset must be finite and nonnegative from the under-head shank start.");
        var rootWidth = 5d * feature.PitchMm / 6d;
        var crestWidth = feature.PitchMm / 8d;
        var depth = (rootWidth - crestWidth) * Math.Sqrt(3d) / 2d;
        var rootRadius = feature.MajorDiameterMm / 2d - depth;
        if (rootRadius <= 0d)
            return Failure("profile-self-intersection", "The 60-degree profile depth consumes the support radius.");
        var supportStart = bolt.Spec.UnderHeadRadius;
        var supportEnd = bolt.Dimensions.TipChamferStartX;
        var grooveWidth = feature.PitchMm - crestWidth;
        var grooveBottomWidth = feature.PitchMm - rootWidth;
        var start = supportStart + (feature.StartOffsetMm ?? grooveWidth / 2d + 1d);
        var end = start + feature.LengthMm;
        // A thread whose footprint reaches the tip chamfer runs out through the tip, as a die-cut thread does, so a
        // nut can start on it.
        var runOut = end + grooveWidth / 2d >= supportEnd - 1e-6d;
        if (start - grooveWidth / 2d <= supportStart + 1e-6d || (runOut && start + grooveWidth / 2d >= supportEnd))
            return Failure("support-bounds", "Thread footprint requires stock margins inside the HexBolt shank, starting before the tip chamfer.");
        var buildStart = Stopwatch.GetTimestamp();
        var rib = HelicalRibGeometry.Create(new HelicalRibParameters(Point3D.Origin,
            Direction3D.Create(new Vector3D(1d, 0d, 0d)), Direction3D.Create(new Vector3D(0d, 1d, 0d)),
            supportStart, runOut ? double.Max(supportEnd, end + grooveWidth) : supportEnd,
            feature.MajorDiameterMm / 2d, rootRadius, feature.PitchMm,
            start, end, grooveWidth, grooveBottomWidth, Intent: HelicalProfileIntent.RemoveGroove));
        if (!rib.IsSuccess) return Failure("geometry-invalid", string.Join(" | ", rib.Diagnostics.Select(d => d.Message)));
        var built = runOut
            ? BrepHelicalRib.CreateWithTipRunOut(rib.Value, new HelicalTipRunOut(supportEnd, bolt.Spec.Length, bolt.Spec.TipDiameter / 2d))
            : BrepHelicalRib.Create(rib.Value, splitStockRims: true);
        if (!built.IsSuccess) return Failure("brep-invalid", string.Join(" | ", built.Diagnostics.Select(d => d.Message)));
        HexBoltThreadComposition.Result stitched;
        try { stitched = HexBoltThreadComposition.Create(bolt, built.Value); }
        catch (InvalidOperationException ex) { return Failure("hexbolt-stitch-invalid", ex.Message); }
        var constructionMs = Stopwatch.GetElapsedTime(buildStart).TotalMilliseconds;
        var featureId = $"{document.Solid.Name}.{feature.Name}";
        var exportStart = Stopwatch.GetTimestamp();
        var step = Step242Exporter.ExportBody(stitched.Body, new Step242ExportOptions
        {
            ProductName = featureId,
            ApplicationName = "Aetheris.Firmament.Thread.External.X1",
            BrepExportPreflightMode = BrepExportPreflightMode.Enforce
        });
        if (!step.IsSuccess) return Failure("step-export-failed", string.Join(" | ", step.Diagnostics.Select(d => d.Message)));
        var exportMs = Stopwatch.GetElapsedTime(exportStart).TotalMilliseconds;
        var descendants = built.Value.FaceRoles
            .Where(pair => stitched.ThreadFaces.ContainsKey(pair.Key))
            .Select(pair => new SemanticTopologyDescendant(
                $"{featureId}.Face[{pair.Key.Value}]", "Face", pair.Value switch
                {
                    var role when role.StartsWith("LeadingFlank", StringComparison.Ordinal) => SemanticTopologyRole.ThreadLeadingFlank,
                    var role when role.StartsWith("TrailingFlank", StringComparison.Ordinal) => SemanticTopologyRole.ThreadTrailingFlank,
                    var role when role.StartsWith("Crest", StringComparison.Ordinal) => SemanticTopologyRole.ThreadRootFace,
                    var role when role.StartsWith("RootCylinderSkin", StringComparison.Ordinal) => SemanticTopologyRole.ThreadCrest,
                    "StartCap" => SemanticTopologyRole.ThreadStartCap,
                    "EndCap" => SemanticTopologyRole.ThreadEndCap,
                    _ => SemanticTopologyRole.ThreadRootFace
                }, featureId, Face: stitched.ThreadFaces[pair.Key], ParentStableId: featureId,
                Addressability: SemanticTopologyAddressability.DerivedStable))
            .Concat(built.Value.EdgeRoles.Where(pair => stitched.ThreadEdges.ContainsKey(pair.Key))
                .Select(pair => new SemanticTopologyDescendant(
                    $"{featureId}.Edge[{pair.Key.Value}]", "Edge", SemanticTopologyRole.ThreadBoundaryEdge,
                    featureId, Edge: stitched.ThreadEdges[pair.Key], ParentStableId: featureId,
                    Addressability: SemanticTopologyAddressability.DerivedStable))).ToArray();
        var correspondence = new SemanticTopologyCorrespondence(featureId, descendants,
            ["Thread", "HelicalRib", "HexBoltThreadComposition"],
            new Dictionary<string, FirmamentV2SourceSpan> { [featureId] = feature.SourceSpan });
        var boltSemantics = bolt.Semantics.Descendants
            .Where(item => !item.StableId.Contains(".ThreadRegion", StringComparison.Ordinal)
                && (item.Face is null || stitched.BoltFaces.ContainsKey(item.Face.Value)))
            .Select(item => new FirmamentStandardPartSemanticReport(item.StableId, item.Kind.ToString(),
                item.ParentStableId, item.Face is { } face ? stitched.BoltFaces[face].Value : null,
                item.Metadata)).ToArray();
        var boltReport = new FirmamentStandardPartReport(authoredPart.Family,
            document.StaticAuthoring?.Templates.SingleOrDefault()?.Name,
            bolt.DeterministicSignature, authoredPart.Parameters, boltSemantics);
        var report = new FirmamentThreadReport(featureId, $"face({document.Solid.Name}.Shank)",
            feature.MajorDiameterMm, 2d * rootRadius, feature.PitchMm, feature.PitchMm, feature.LengthMm,
            start - supportStart, start, feature.Hand, "metric-60-degree-truncated", (int)Math.Round(built.Value.Authority.Turns),
            stitched.Body.Topology.Faces.Count(), stitched.Body.Topology.Edges.Count(),
            stitched.Body.Topology.Vertices.Count(), built.Value.SeamSplits, constructionMs, exportMs,
            Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))))
        { HeadSideLandMm = start - supportStart - grooveWidth / 2d, TipSideLandMm = runOut ? 0d : supportEnd - end - grooveWidth / 2d };
        return ApplyHexBoltMakerMark(new FirmamentStepExportResult(
            step.Value, featureId, 0, "thread-external-hexbolt", "metric-60-degree",
            StandardPart: boltReport, Thread: report)
        { RuntimeBody = stitched.Body, RuntimeCorrespondence = correspondence });
    }

    private static KernelResult<FirmamentStepExportResult> ApplyHexBoltMakerMark(FirmamentStepExportResult result)
    {
        var part = result.StandardPart!;
        if (!part.Parameters.TryGetValue("MakerMark", out var content))
            return KernelResult<FirmamentStepExportResult>.Success(result);
        try
        {
            var top = part.SemanticDescendants.Single(d => d.StableId.EndsWith(".Head.TopFlat", StringComparison.Ordinal)).FaceId!.Value;
            var height = double.Parse(part.Parameters["MakerMarkHeight"].Trim()[..^2], System.Globalization.CultureInfo.InvariantCulture);
            var depth = double.Parse(part.Parameters["MakerMarkDepth"].Trim()[..^2], System.Globalization.CultureInfo.InvariantCulture);
            var mark = PlanarCapEngraving.Engrave(result.RuntimeBody!, new FaceId(top),
                HexBoltParameterBinding.Text(content), height, depth);
            var composition = mark.Composition!;
            var semantics = part.SemanticDescendants.Select(d => d.FaceId is { } id
                ? d with { FaceId = id == top ? composition.ReplacementCap.Value : composition.HostFaces[new FaceId(id)].Value }
                : d).ToArray();
            var correspondence = result.RuntimeCorrespondence;
            if (correspondence is not null)
                correspondence = correspondence with
                {
                    Descendants = correspondence.Descendants.Select(d => d with
                    {
                        Face = d.Face is { } face ? composition.HostFaces[face] : null,
                        Edge = d.Edge is { } edge ? composition.HostEdges[edge] : null
                    }).ToArray()
                };
            var thread = result.Thread is { } t ? t with
            {
                Faces = mark.Body.Topology.Faces.Count(), Edges = mark.Body.Topology.Edges.Count(),
                Vertices = mark.Body.Topology.Vertices.Count(),
                StepSha256 = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(mark.StepText)))
            } : null;
            return KernelResult<FirmamentStepExportResult>.Success(result with
            {
                RuntimeBody = mark.Body, RuntimeCorrespondence = correspondence, StepText = mark.StepText,
                Thread = thread, StandardPart = part with { SemanticDescendants = semantics },
                MakerMark = new(HexBoltParameterBinding.Text(content), height, depth, mark.Text.CounterCount)
            });
        }
        catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
        {
            return KernelResult<FirmamentStepExportResult>.Failure([new KernelDiagnostic(
                KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,
                "hexbolt-maker-mark-invalid: " + ex.Message, "FirmamentV2.StandardPart")]);
        }
    }

    private static KernelResult<FirmamentStepExportResult>? TryExportV2ExactCoaxialPart(FirmamentV2Document document)
    {
        if (document.Solids.Count != 1 || document.Solid.ExactCoaxialPart is not { } authored) return null;
        var recipe = ExactCoaxialPartBuilder.Bind(authored.Parameters);
        if (!recipe.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(recipe.Diagnostics);
        var built = ExactCoaxialPartBuilder.Create(recipe.Value);
        if (!built.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(built.Diagnostics);
        var step = Step242Exporter.ExportBody(built.Value.Body);
        if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        var instantiation = document.ConceptIr?.TemplateInstantiations?.SingleOrDefault();
        var record = instantiation?.RecordArguments?.SingleOrDefault().Value;
        // A nested standards Record is still ordinary static data. Publish its leaf fields
        // alongside instance fields so existing construction reports remain ergonomic.
        var parameters = record is null ? authored.Parameters : record.Members
            .Where(pair => !pair.Key.Contains('.', StringComparison.Ordinal) || pair.Key.StartsWith("Standard.", StringComparison.Ordinal))
            .ToDictionary(pair => pair.Key.StartsWith("Standard.", StringComparison.Ordinal) ? pair.Key["Standard.".Length..] : pair.Key, pair => pair.Value, StringComparer.Ordinal);
        var semantics = built.Value.Semantics.Descendants.Select(descendant => new FirmamentStandardPartSemanticReport(
            descendant.StableId, descendant.Kind.ToString(), descendant.ParentStableId, descendant.Face?.Value, descendant.Metadata)).ToArray();
        var report = new FirmamentStandardPartReport("ExactCoaxialPart", instantiation?.Template, built.Value.DeterministicSignature, parameters, semantics);
        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, built.Value.Semantics.BodyStableId, 0,
            "template-exact-construction", "ExactCoaxialPart", ConceptIr: document.ConceptIr, StandardPart: report));
    }

    /// <summary>Applies a section stack's construction-plane blind drills to an emitted plan and materializes the
    /// result; returns a failure, or null with the drilled emission (unchanged when there are no drills).</summary>
    private static KernelResult<FirmamentStepExportResult>? ApplyConstructionPlaneBlindDrills(
        PrismaticSectionStackConstruction stack, PrismaticSectionStackEmissionResult emitted, out PrismaticSectionStackEmissionResult result)
    {
        result = emitted;
        if ((stack.Feature.ConstructionPlaneBlindDrills?.Count ?? 0) == 0) return null;
        static KernelResult<FirmamentStepExportResult> Failure(IEnumerable<string> codes) => KernelResult<FirmamentStepExportResult>.Failure(codes.Select(x =>
            new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, x, "FirmamentV2.ProfileComposition.BlindDrill")).ToArray());
        var finalPlan = SectionStackBlindDrillComposeBridge.TryApply(stack, emitted.Plan!, out var bridgeDiagnostics, out _);
        if (finalPlan?.TopologyPlan is null) return Failure(bridgeDiagnostics);
        var materialized = PrismaticSectionStackBrepMaterializer.TryMaterialize(finalPlan.TopologyPlan);
        if (materialized.Body is null) return Failure(materialized.Diagnostics);
        result = new PrismaticSectionStackEmissionResult(materialized.Body, finalPlan, emitted.Diagnostics.Concat(bridgeDiagnostics).ToArray(), finalPlan.Correspondence);
        return null;
    }

    private static KernelResult<FirmamentStepExportResult> ExportComposedSemanticTopBoundaryChamfer(
        string source, PrismaticProfileCompositionParseResult parsed, PrismaticSectionStackConstruction stack, PrismaticSectionStackEmissionResult emitted,
        FirmamentV2Document? canonicalDocument)
    {
        var finishSpan = ProfileBoundaryChamferSourceBinder.FinishDeclarations(source).FirstOrDefault()?.Span;
        KernelResult<FirmamentStepExportResult> Fail(string code) => KernelResult<FirmamentStepExportResult>.Failure([
            new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, code, "FirmamentV2.ComposeSemanticSelection")
            { SourceSpan = finishSpan is { } span ? new(span.Start, span.Length) : null }]);
        if (ProfileBoundaryChamferSourceBinder.SequenceDiagnostic(source) is { } sequenceDiagnostic) return Fail(sequenceDiagnostic);
        if (ProfileBoundaryChamferSourceBinder.HasSemanticProfileBoundaryFinish(source)
            || (ProfileBoundaryChamferSourceBinder.HasHostBoundaryFinish(source)
                && (ProfileBoundaryChamferSourceBinder.HasProfileBoundaryFillet(source)
                    || RimSupportProfiles(source, parsed.Profiles, stack).Any(p =>
                        !IsAdmittedPrimitiveBoundary(p.Loops.Single(l => l.IsOuter).Segments.Select(s => s.Geometry).ToArray())))))
        {
            if (ProfileBoundaryChamferSourceBinder.HasProfileBoundaryFillet(source))
            {
                ProfileBoundaryChamferTarget? filletTarget = null; ResolvedProfile2D? filletProfile = null; double radius = 0d; double clearance = 0d; string? filletDiagnostic = null;
                foreach (var candidate in RimSupportProfiles(source, parsed.Profiles, stack))
                    if (ProfileBoundaryChamferSourceBinder.TryBindFillet(source, candidate, stack.Feature.Name, out filletTarget, out radius, out clearance, out filletDiagnostic)) { filletProfile = candidate; break; }
                if (filletProfile is null || filletTarget is null) return Fail(filletDiagnostic ?? "ProfileBoundaryFilletProfileUnknown");
                if (filletTarget.ChainKind != ProfileBoundaryChamferChainKind.ClosedLoop)
                {
                    var filletAdmission = ProfileStraightEdgeFilletAdmissionChecker.Check(stack, filletProfile, filletTarget, radius, clearance);
                    if (!filletAdmission.Disjoint) return Fail(filletAdmission.Diagnostics.FirstOrDefault() ?? "ProfileBoundaryFilletCavityInteractionUnsupported");
                    return Fail("ProfileBoundaryFilletComposeUnsupported: An open-chain composed fillet requires an adapter that retains its existing material intervals and cavities and qualifies endpoint termination. No geometry was emitted.");
                }
                return ExportComposedProfileRim(source, stack, filletProfile, filletTarget, radius, true, clearance, emitted, canonicalDocument);
            }
            ProfileBoundaryChamferTarget? target = null; double distance = 0d; string? bindingDiagnostic = null; ResolvedProfile2D? profile = null;
            foreach (var candidate in RimSupportProfiles(source, parsed.Profiles, stack))
            {
                if (ProfileBoundaryChamferSourceBinder.TryBind(source, candidate, stack.Feature.Name, out target, out distance, out bindingDiagnostic)) { profile = candidate; break; }
            }
            if (profile is null || target is null) return Fail(bindingDiagnostic ?? "ProfileBoundaryChamferProfileUnknown");
            if (target.Side == ProfileBoundaryChamferSide.Bottom || profile.Loops.Any(l => l.Segments.Any(s => s.Geometry is LineArcCircularArc2D)))
                return ExportComposedProfileRim(source, stack, profile, target, distance, false, distance, emitted, canonicalDocument);
            var admission = ComposedProfileBoundaryChamferAdmissionChecker.Check(stack, profile, target, distance);
            if (!admission.Admitted) return Fail(admission.Diagnostics.FirstOrDefault() ?? "ProfileBoundaryChamferCavityInteractionUnsupported");
            var adjusted = ComposedProfileBoundaryChamferStackPlanner.TryApply(stack, profile, target, distance, out var planDiagnostics);
            if (adjusted is null) return Fail(planDiagnostics.FirstOrDefault() ?? "ProfileBoundaryChamferComposeTopologyPlanNotMaterialized");
            var plannedEmission = PrismaticSectionStackEmitter.Emit(adjusted);
            if (plannedEmission.Body is null) return Fail(plannedEmission.Diagnostics.FirstOrDefault() ?? "ProfileBoundaryChamferComposeMaterializationFailed");
            // The chamfer re-emits the adjusted stack, so construction-plane drills apply again to that plan.
            if (ApplyConstructionPlaneBlindDrills(adjusted, plannedEmission, out var drilledEmission) is { } chamferDrillFailure) return chamferDrillFailure;
            plannedEmission = drilledEmission;
            if (!FirmamentManifoldChecker.IsManifold(plannedEmission.Body)) return Fail("ProfileBoundaryChamferNonManifold");
            var semanticPmi = Array.Empty<Step242SemanticPmi>();
            if (canonicalDocument is not null)
            {
                var support = ValidateV2PmiExportSupport(canonicalDocument);
                if (!support.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(support.Diagnostics);
                var features = (stack.Feature.ShaftHoles ?? []).ToDictionary(hole => hole.Name, hole => hole.StableId, StringComparer.Ordinal);
                foreach (var hole in stack.Feature.CounterboreHoles ?? []) features[hole.Name] = hole.StableId;
                foreach (var hole in stack.Feature.CountersinkHoles ?? []) features[hole.Name] = hole.StableId;
                semanticPmi = BuildV2SemanticPmi(canonicalDocument, [], stack.Feature.Name, features, plannedEmission.Correspondence, plannedEmission.Body,
                    ComposeOperationCapFaces(stack.Feature, plannedEmission.Body, plannedEmission.Correspondence), stack.Feature).ToArray();
            }
            var plannedStep = Step242Exporter.ExportBody(plannedEmission.Body, semanticPmi, new Step242ExportOptions { ProductName = target.StableId, ApplicationName = "Aetheris.Firmament.ComposedProfileBoundaryChamfer.M3", BrepExportPreflightMode = BrepExportPreflightMode.Enforce, BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });
            if (!plannedStep.IsSuccess || plannedStep.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(plannedStep.Diagnostics);
            var plannedReimport = Step242Importer.ImportBody(plannedStep.Value);
            if (!plannedReimport.IsSuccess || plannedReimport.Value is null || !FirmamentManifoldChecker.IsManifold(plannedReimport.Value)) return Fail("ProfileBoundaryChamferStepReimportFailed");
            return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(plannedStep.Value, target.StableId, 0, "composed-profile-boundary-chamfer-section-stack", "source-grounded-composed-profile-boundary-chamfer",
                DatumInspection: canonicalDocument?.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.DatumPlane).Select(p => new FirmamentPmiInspectionDatum(p.Name, "planar", p.Target)).ToArray() ?? [],
                DimensionInspection: canonicalDocument?.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.HoleDiameter).Select(p => new FirmamentPmiInspectionDimension("Diameter", p.Target, null, p.Value ?? 0d, "explicit-v2-record-pmi", p.Name)).ToArray() ?? [],
                Features: CompositionHoleReports(stack.Feature, plannedEmission.Body!, plannedEmission.Correspondence),
                EngineeringFeatures: EngineeringFeatureReports(stack.Feature).Append(new FirmamentEngineeringFeatureReport(
                    target.StableId["edgefinish:".Length..],
                    "EdgeFinish",
                    target.StableId,
                    target.HostBodyId,
                    target.Side.ToString(),
                    $"{target.ProfileId}.{target.LoopId}",
                    distance,
                    "Distance",
                    "Remove",
                    PolicySource: "Chamfer",
                    MaterializationRoute: "ComposedProfileBoundaryChamfer")).ToArray()) { MaterializedFeatures = FirmamentFeatureAccounting.Composition(stack, plannedEmission.Correspondence).Concat(FirmamentFeatureAccounting.ProfileFinish(source, target.StableId["edgefinish:".Length..], target.HostBodyId)).ToArray() });
        }
        if (emitted.Body is null || emitted.Correspondence is null) return Fail("MissingCorrespondenceEvidence");
        // The legacy rectangular-face compiler below rebuilds a single stock prism.
        // Additional operations must use the section-stack boundary planner above;
        // its box bridge cannot retain cavities or changes at other height levels.
        if (stack.Feature.Operations.Count != 1 || (stack.Feature.ConstructionPlaneBlindDrills?.Count ?? 0) > 0)
            return Fail("ComposedBoundaryRebuildUnsupported: This boundary selector uses a single-stock prism rebuild. Use an EdgeFinish on Top/Bottom through the section-stack planner to retain Compose operations and holes.");
        var composedCurves = stack.Slabs.MaxBy(s => s.To)!.Region.Outer.Loops.Single().Segments.Select(segment => segment.Geometry).ToArray();
        if (!IsAdmittedPrimitiveBoundary(composedCurves))
            return Fail($"{EdgeFinishProfileComposeBoundaryUnsupported}:host={stack.Feature.Name}:construction=Compose:face=+Z:target=Boundary: EdgeFinish on a Profile-based body is supported on four-sided boundaries; this boundary has curved or extra segments. Use Box stock for a rounded or chamfered rim, or shape the corners in the Profile itself.");
        var selections = SemanticSelectionSourceParser.Parse(source, parsed.Profiles.Values.First(), stack.Feature.Name, out var diagnostics);
        if (diagnostics.Count != 0 || selections.Count != 1) return Fail(diagnostics.FirstOrDefault() ?? "SemanticSourceNotFound");
        var selection = SemanticTopologySelectionResolver.Resolve(emitted.Body, emitted.Correspondence, selections[0]);
        if (!selection.Succeeded) return Fail(string.Join("; ", selection.Diagnostics.Select(diagnostic => $"{diagnostic.Code}: {diagnostic.Message}")));
        if (!selection.IsClosed || selection.Request.Require != SemanticSelectionRequirement.ClosedLoop) return Fail("SelectionConsumerMismatch: EdgeFinish requires a closed semantic boundary loop.");
        var finish = Regex.Match(source, @"\bEdgeFinish\s+(?<name>\w+)\s*\{\s*Target\s*:\s*(?<target>\w+)\s*;?\s*Kind\s*:\s*(?<kind>Chamfer)\s*;?\s*Distance\s*:\s*(?<amount>[-+.\d]+)mm", RegexOptions.Singleline | RegexOptions.CultureInvariant);
        if (!finish.Success || finish.Groups["target"].Value != selection.Request.Label) return Fail("SelectionConsumerMismatch");
        var topSlab = stack.Slabs.MaxBy(s => s.To)!;
        var curves = topSlab.Region.Outer.Loops.Single().Segments.Select(x => x.Geometry).ToArray();
        if (curves.Length < 4 || curves.Any(x => x is not LineArcLineSegment2D)) return Fail("UnsupportedTopologyChange");
        var points = curves.Cast<LineArcLineSegment2D>().SelectMany(x => new[] { x.Start, x.End }).ToArray();
        var minX = points.Min(x => x.X); var maxX = points.Max(x => x.X); var minY = points.Min(x => x.Y); var maxY = points.Max(x => x.Y);
        if (points.Any(p => p.X != minX && p.X != maxX && p.Y != minY && p.Y != maxY)) return Fail("UnsupportedTopologyChange");
        var compiled = AirTopFaceBoundaryChamferCompiler.Compile(new(stack.Feature.Name, $"{stack.Feature.Name}.{finish.Groups["name"].Value}", finish.Groups["name"].Value, maxX - minX, maxY - minY, stack.Feature.CriticalLevels.Max() - stack.Feature.CriticalLevels.Min(), "+Z", "Boundary", "Chamfer", double.Parse(finish.Groups["amount"].Value, System.Globalization.CultureInfo.InvariantCulture), new AirSourceSpan(finish.Index, finish.Length, stack.Feature.Name)));
        if (!compiled.Succeeded || compiled.Body is null || compiled.BRepPlan?.RealizationPlan is null) return Fail(compiled.Diagnostics.FirstOrDefault() ?? "UnsupportedTopologyChange");
        var step = Step242Exporter.ExportBody(compiled.Body, new Step242ExportOptions { ProductName = compiled.Feature.FeatureName, ApplicationName = AirTopFaceBoundaryChamferCompileResult.ProductionRoute, BrepExportPreflightMode = BrepExportPreflightMode.Enforce, BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });
        if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        var reimport = Step242Importer.ImportBody(step.Value);
        if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value)) return Fail("semantic-compose-finish-step-reimport-failed");
        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, compiled.Feature.FeatureId, 0, "semantic-compose-edge-finish", "source-grounded-composed-top-boundary-chamfer") { MaterializedFeatures = FirmamentFeatureAccounting.Composition(stack, emitted.Correspondence).Concat(FirmamentFeatureAccounting.Receipts(stack.Feature.Name, "EdgeFinish", finish.Groups["name"].Value)).ToArray() });
    }

    private static KernelResult<FirmamentStepExportResult> ExportProfileSemanticTopBoundaryChamfer(
        string source,
        ResolvedProfile2D profile,
        double height,
        LineArcProfileExtrudeResult emitted,
        string? diagnosticSource)
    {
        var finishes = ProfileBoundaryChamferSourceBinder.FinishDeclarations(source).ToArray();
        // The legacy materializer transport removes the enclosing Model. Return
        // the corresponding declaration in the frontend's retained source, so
        // the common provenance mapper receives offsets in its own input.
        // A sequence fails at the second requested operation. Recipes are not
        // operations and must not displace a real operation's diagnostic anchor.
        var rejectedFinish = finishes.ElementAtOrDefault(finishes.Length > 1 ? 1 : 0);
        var anchors = diagnosticSource is null ? rejectedFinish is null ? [] : new[] { rejectedFinish }
            : ProfileBoundaryChamferSourceBinder.FinishDeclarations(diagnosticSource)
                .Where(d => rejectedFinish is not null && d.Name?.Text == rejectedFinish.Name?.Text).ToArray();
        var finishSpan = anchors.Length == 1 ? anchors[0].Span : (FirmamentV2SourceSpan?)null;
        KernelResult<FirmamentStepExportResult> Fail(string code) => KernelResult<FirmamentStepExportResult>.Failure([
            new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, code, "FirmamentV2.SemanticSelection")
            { SourceSpan = finishSpan is { } span ? new(span.Start, span.Length) { LocationNote = "EdgeFinish declaration; the planner reports the enclosing operation." } : null }]);
        if (ProfileBoundaryChamferSourceBinder.SequenceDiagnostic(source) is { } sequenceDiagnostic) return Fail(sequenceDiagnostic);
        if (ProfileBoundaryChamferSourceBinder.HasSemanticProfileBoundaryFinish(source)
            || (ProfileBoundaryChamferSourceBinder.HasHostBoundaryFinish(source)
                && (ProfileBoundaryChamferSourceBinder.HasProfileBoundaryFillet(source)
                    || !IsAdmittedPrimitiveBoundary(profile.Loops.First(l => l.IsOuter).Segments.Select(s => s.Geometry).ToArray()))))
        {
            if (ProfileBoundaryChamferSourceBinder.HasProfileBoundaryFillet(source))
            {
                if (!ProfileBoundaryChamferSourceBinder.TryBindFillet(source, profile, profile.Name, out var filletTarget, out var radius, out var clearance, out var filletDiagnostic))
                    return Fail(filletDiagnostic ?? "ProfileBoundaryFilletBindingFailed");
                var fillet = ProfileFilletShellPlanner.TryPlan(profile, filletTarget!, radius, clearance);
                if (!fillet.Succeeded || fillet.Body is null || fillet.Correspondence is null)
                    return Fail(fillet.Diagnostics.FirstOrDefault() ?? "ProfileBoundaryFilletPlanningFailed");
                if (!FirmamentManifoldChecker.IsManifold(fillet.Body)) return Fail("ProfileBoundaryFilletNonManifold");
                var filletStep = Step242Exporter.ExportBody(fillet.Body, new Step242ExportOptions
                {
                    ProductName = filletTarget!.StableId,
                    ApplicationName = fillet.Plan is null
                        ? "Aetheris.Firmament.ProfileStraightEdgeFillet.M1"
                        : fillet.Plan.Junction is ProfileReflexFilletJunctionPlan
                            ? "Aetheris.Firmament.ProfileReflexFilletJunction.M3"
                            : fillet.Plan.Junction is ProfileReflexSphereSeamCompatibilityJunctionPlan
                                ? "Aetheris.Firmament.ProfileReflexSphereSeamCompatibility.M3"
                                : "Aetheris.Firmament.ProfileConvexFilletJunction.M2",
                    BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
                    BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute
                });
                if (!filletStep.IsSuccess || filletStep.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(filletStep.Diagnostics);
                var filletReimport = Step242Importer.ImportBody(filletStep.Value);
                if (!filletReimport.IsSuccess || filletReimport.Value is null || !FirmamentManifoldChecker.IsManifold(filletReimport.Value)) return Fail("ProfileBoundaryFilletStepReimportFailed");
                var route = fillet.Plan is null
                    ? "profile-straight-edge-fillet"
                    : fillet.Plan.Junction is ProfileReflexFilletJunctionPlan
                        ? "profile-reflex-toroidal-fillet-junction"
                        : fillet.Plan.Junction is ProfileReflexSphereSeamCompatibilityJunctionPlan
                            ? "profile-reflex-sphere-seam-compatibility"
                            : "profile-convex-fillet-junction";
                return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(filletStep.Value, filletTarget.StableId, fillet.Correspondence.Descendants.Count, route, "source-grounded-profile-fillet")
                {
                    RuntimeBody = fillet.Body, RuntimeCorrespondence = fillet.Correspondence,
                    EdgeFinishPlanning = fillet.PlanningEvidence,
                    MaterializedFeatures = FirmamentFeatureAccounting.ProfileFinish(source, filletTarget.StableId["edgefinish:".Length..], filletTarget.HostBodyId),
                    EngineeringFeatures = [new(filletTarget.StableId["edgefinish:".Length..], "EdgeFinish", filletTarget.StableId,
                        filletTarget.HostBodyId, filletTarget.Side.ToString(), $"{profile.Name}.{filletTarget.LoopId}", radius,
                        "Radius", "Remove", PolicySource: "Fillet", MaterializationRoute: fillet.PlanningEvidence?.Decision.Strategy ?? route)]
                });
            }
            if (!ProfileBoundaryChamferSourceBinder.TryBind(source, profile, profile.Name, out var target, out var distance, out var bindingDiagnostic))
                return Fail(bindingDiagnostic ?? "ProfileBoundaryChamferBindingFailed");
            var planned = ProfileBoundaryChamferPlanner.TryPlan(profile, target!, distance);
            if (!planned.Succeeded || planned.Body is null || planned.Correspondence is null)
                return Fail(planned.Diagnostics.FirstOrDefault() ?? "ProfileBoundaryChamferPlanningFailed");
            if (!FirmamentManifoldChecker.IsManifold(planned.Body)) return Fail("ProfileBoundaryChamferNonManifold");
            var plannedStep = Step242Exporter.ExportBody(planned.Body, new Step242ExportOptions
            {
                ProductName = target!.StableId,
                ApplicationName = "Aetheris.Firmament.ProfileBoundaryChamfer.M1",
                BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
                BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute
            });
            if (!plannedStep.IsSuccess || plannedStep.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(plannedStep.Diagnostics);
            var plannedReimport = Step242Importer.ImportBody(plannedStep.Value);
            if (!plannedReimport.IsSuccess || plannedReimport.Value is null || !FirmamentManifoldChecker.IsManifold(plannedReimport.Value)) return Fail("ProfileBoundaryChamferStepReimportFailed");
            return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(plannedStep.Value, target.StableId, 0, "profile-boundary-chamfer-section-stack", "source-grounded-profile-boundary-chamfer")
            {
                RuntimeBody = planned.Body, RuntimeCorrespondence = planned.Correspondence,
                EdgeFinishPlanning = planned.PlanningEvidence,
                MaterializedFeatures = FirmamentFeatureAccounting.ProfileFinish(source, target.StableId["edgefinish:".Length..], target.HostBodyId),
                EngineeringFeatures = [new(target.StableId["edgefinish:".Length..], "EdgeFinish", target.StableId,
                    target.HostBodyId, target.Side.ToString(), $"{profile.Name}.{target.LoopId}", distance,
                    "Distance", "Remove", PolicySource: "Chamfer", MaterializationRoute: planned.PlanningEvidence?.Decision.Strategy ?? "ProfileBoundaryChamfer")]
            });
        }
        if (emitted.Body is null || emitted.Correspondence is null) return Fail("NoMaterializedDescendants");
        if (!IsAdmittedPrimitiveBoundary(profile.Loops.Single().Segments.Select(segment => segment.Geometry).ToArray()))
            return Fail($"{EdgeFinishProfileComposeBoundaryUnsupported}:host={profile.Name}:construction=Profile:face=+Z:target=Boundary: EdgeFinish on a Profile-based body is supported on four-sided boundaries; this boundary has curved or extra segments. Use Box stock for a rounded or chamfered rim, or shape the corners in the Profile itself.");
        var selections = SemanticSelectionSourceParser.Parse(source, profile, profile.Name, out var selectionDiagnostics);
        if (selectionDiagnostics.Count > 0 || selections.Count != 1) return Fail(selectionDiagnostics.FirstOrDefault() ?? "SemanticSourceNotFound");
        var selection = SemanticTopologySelectionResolver.Resolve(emitted.Body, emitted.Correspondence, selections[0]);
        if (!selection.Succeeded) return Fail(string.Join("; ", selection.Diagnostics.Select(diagnostic => $"{diagnostic.Code}: {diagnostic.Message}")));
        var finish = Regex.Match(source, @"\bEdgeFinish\s+(?<name>\w+)\s*\{\s*Target\s*:\s*(?<target>\w+)\s*;?\s*Kind\s*:\s*(?<kind>Chamfer|Fillet)\s*;?\s*(?:Distance|Radius)\s*:\s*(?<amount>[-+.\d]+)mm", RegexOptions.Singleline | RegexOptions.CultureInvariant);
        if (!finish.Success || !string.Equals(finish.Groups["target"].Value, selection.Request.Label, StringComparison.Ordinal)) return Fail("SelectionConsumerMismatch");
        if (!string.Equals(finish.Groups["kind"].Value, "Chamfer", StringComparison.Ordinal) || selection.Request.Require != SemanticSelectionRequirement.ClosedLoop || !selection.IsClosed) return Fail("SelectionConsumerMismatch");
        var lines = profile.Loops.Single().Segments.Select(x => x.Geometry).OfType<LineArcLineSegment2D>().ToArray();
        if (lines.Length != 4 || profile.Loops.Single().Segments.Count != 4) return Fail("UnsupportedTopologyChange");
        var points = lines.SelectMany(x => new[] { x.Start, x.End }).ToArray();
        var minX = points.Min(x => x.X); var maxX = points.Max(x => x.X); var minY = points.Min(x => x.Y); var maxY = points.Max(x => x.Y);
        if (lines.Any(x => Math.Abs(x.Start.X - x.End.X) > 1e-9 && Math.Abs(x.Start.Y - x.End.Y) > 1e-9)) return Fail("UnsupportedTopologyChange");
        var compiled = AirTopFaceBoundaryChamferCompiler.Compile(new(
            profile.Name, $"{profile.Name}.{finish.Groups["name"].Value}", finish.Groups["name"].Value,
            maxX - minX, maxY - minY, height, "+Z", "Boundary", "Chamfer",
            double.Parse(finish.Groups["amount"].Value, System.Globalization.CultureInfo.InvariantCulture),
            new AirSourceSpan(finish.Index, finish.Length, profile.Name)));
        if (!compiled.Succeeded || compiled.Body is null || compiled.BRepPlan?.RealizationPlan is null) return Fail(compiled.Diagnostics.FirstOrDefault() ?? "UnsupportedTopologyChange");
        if (!FirmamentManifoldChecker.IsManifold(compiled.Body)) return Fail("semantic-selection-finish-nonmanifold");
        var step = Step242Exporter.ExportBody(compiled.Body, new Step242ExportOptions { ProductName = compiled.Feature.FeatureName, ApplicationName = AirTopFaceBoundaryChamferCompileResult.ProductionRoute, BrepExportPreflightMode = BrepExportPreflightMode.Enforce, BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });
        if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        var reimport = Step242Importer.ImportBody(step.Value);
        if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value)) return Fail("semantic-selection-finish-step-reimport-failed");
        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, compiled.Feature.FeatureId, 0, "semantic-profile-edge-finish", "source-grounded-top-boundary-chamfer") { MaterializedFeatures = FirmamentFeatureAccounting.ProfileFinish(source, finish.Groups["name"].Value, profile.Name) });
    }

    private static bool IsAdmittedPrimitiveBoundary(IReadOnlyList<LineArcProfileCurve2D> curves) =>
        curves.Count == 4
        && curves.All(curve => curve is LineArcLineSegment2D)
        && curves.Cast<LineArcLineSegment2D>().All(line => Math.Abs(line.Start.X - line.End.X) < 1e-9 || Math.Abs(line.Start.Y - line.End.Y) < 1e-9);

    private static KernelResult<FirmamentStepExportResult>? TryExportV2StandaloneCubicLattice(FirmamentV2Document document)
    {
        var fills = document.StandaloneLatticeFills ?? [];
        if (fills.Count == 0) return null;
        if (fills.Count != 1)
        {
            return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, "standalone-fill-multiple-unsupported", "FirmamentV2.CubicLattice")]);
        }

        var fill = fills[0];
        var center = new Point3D(fill.Region.Center[0], fill.Region.Center[1], fill.Region.Center[2]);
        var realization = CubicLatticeBRepPlanner.Create(fill.CellsX, fill.CellsY, fill.CellsZ, fill.CellSize, fill.StrutRadius, fill.NodeRadius, center);
        if (!realization.IsSuccess || realization.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(realization.Diagnostics);
        var body = realization.Value.Body;
        var preflight = BrepExportPreflight.Validate(body);
        if (!preflight.IsValid || !FirmamentManifoldChecker.IsManifold(body))
        {
            return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, "lattice-topology-verification-failed", "FirmamentV2.CubicLattice")]);
        }

        var mass = BrepMassProperties.Evaluate(body);
        if (mass.Status == BrepMassPropertiesStatus.Unavailable || mass.AbsoluteVolume <= 0d || mass.Centroid is null)
        {
            return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, "lattice-topology-verification-failed: BRep mass properties unavailable", "FirmamentV2.CubicLattice")]);
        }

        var step = Step242Exporter.ExportBody(body, new Step242ExportOptions
        {
            ProductName = fill.Name,
            ApplicationName = "Aetheris.Firmament.CubicTruss.M9R",
            BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
            BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
        });
        if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        var reimport = Step242Importer.ImportBody(step.Value);
        if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value))
        {
            return KernelResult<FirmamentStepExportResult>.Failure(reimport.IsSuccess
                ? [new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, "lattice-topology-verification-failed: STEP reimport is not manifold", "FirmamentV2.CubicLattice")]
                : reimport.Diagnostics);
        }

        var template = FirmamentManufacturingPolicyResolver.Resolve(document, "Additive").Single();
        var graph = realization.Value.Plan.Construction;
        var centroid = mass.Centroid.Value;
        var report = new FirmamentStandaloneLatticeReport(
            template.Name, fill.Pattern, [fill.CellsX, fill.CellsY, fill.CellsZ], fill.CellSize, fill.StrutRadius, fill.NodeRadius, fill.Region.Size, fill.Placement,
            graph.Nodes.Count, graph.Members.Count, realization.Value.Plan.SeamCount,
            graph.Nodes.Count(node => node.Valence == 3), graph.Nodes.Count(node => node.Valence == 4), graph.Nodes.Count(node => node.Valence == 5), graph.Nodes.Count(node => node.Valence == 6),
            realization.Value.Plan.IsAuthoritative, realization.Value.Plan.Signature,
            body.Topology.Vertices.Count(), body.Topology.Edges.Count(), body.Topology.Faces.Count(),
            body.Geometry.Surfaces.Count(pair => pair.Value.Kind == SurfaceGeometryKind.Sphere), body.Geometry.Surfaces.Count(pair => pair.Value.Kind == SurfaceGeometryKind.Cylinder),
            realization.Value.AnalyticVolume, mass.AbsoluteVolume, double.Abs(realization.Value.AnalyticVolume - mass.AbsoluteVolume), mass.SurfaceArea,
            [centroid.X, centroid.Y, centroid.Z], Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))).ToLowerInvariant(), true, true);
        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, fill.Name, 0, "standalone-lattice", "cubic-truss", Lattice: report));
    }

    /// <summary>
    /// Converts the historical nullable TryExport routes into one explicit dispatcher
    /// contract.  A null is only a Declined route; a non-null failed result has claimed
    /// the document and is terminal.  This keeps route order from deciding feature
    /// composition policy.
    /// </summary>
    private static KernelResult<FirmamentStepExportResult>? DispatchV2Routes(
        FirmamentV2Document document,
        params (string Name, Func<FirmamentV2Document, KernelResult<FirmamentStepExportResult>?> Execute)[] routes)
    {
        foreach (var route in routes)
        {
            var raw = route.Execute(document);
            var result = raw is null ? ExportRouteResult.Decline(route.Name) : ExportRouteResult.Complete(route.Name, raw);
            if (result.Disposition == ExportRouteDisposition.Declined)
            {
                continue;
            }

            return result.Artifact!;
        }

        return null;
    }

    private static KernelResult<FirmamentStepExportResult>? TryExportV2CombinedHoleEdgeFinishBody(FirmamentV2Document document)
        => ExportV2BoxThroughHoleStock(document, allowUnfinished: false);

    private static KernelResult<FirmamentStepExportResult>? ExportV2BoxThroughHoleStock(FirmamentV2Document document, bool allowUnfinished)
    {
        var modifies = document.ModifyBlocks ?? [];
        var holesDeclared = modifies.SelectMany(m => m.SemanticHoles).ToArray();
        var finishes = modifies.SelectMany(m => (m.EdgeFinishes ?? [])).ToArray();
        if (holesDeclared.Length == 0 || finishes.Length == 0 && !allowUnfinished)
        {
            return null;
        }

        if (modifies.Count != 1 || modifies[0].Regions.Count != 0)
        {
            return CombinedFailure("CombinedFeatureHostUnsupported: Put the holes and one top-boundary finish in one Modify on a Box, without Region operations.", sourceSpan: holesDeclared[0].SourceSpan);
        }

        var modify = modifies[0];
        var solid = document.Solids.SingleOrDefault(s => s.Name == modify.TargetSolid);
        if (solid is not { Primitive: FirmamentV2BoxRecord box } || box.Size.Count != 3)
        {
            return CombinedFailure($"CombinedFeatureHostUnsupported: Modify target '{modify.TargetSolid}' must resolve to an admitted Box for combined holes and a boundary finish.", sourceSpan: solid?.SourceSpan ?? holesDeclared[0].SourceSpan);
        }

        if (finishes.Length > 1 || finishes.Length == 0 && !allowUnfinished)
        {
            return CombinedFailure($"CombinedFeatureThirdFamilyUnsupported: This Box plan admits one top-boundary EdgeFinish (actual={finishes.Length}).", sourceSpan: finishes[1].SourceSpan);
        }

        var finish = finishes.SingleOrDefault();
        var finishSpan = finish?.SourceSpan ?? holesDeclared[0].SourceSpan;
        var finishName = finish?.Name ?? "UnfinishedStock";
        if (finish is not null && (!string.Equals(finish.FaceAxis, "+Z", StringComparison.Ordinal) || !string.Equals(finish.Target, "Boundary", StringComparison.Ordinal)
            || finish.Kind is not ("Chamfer" or "Fillet")))
        {
            return CombinedFailure($"CombinedFeatureSelectionLost: EdgeFinish '{finishName}' must select the +Z outer Boundary with Kind Chamfer or Fillet. Other combined selectors are not admitted.", sourceSpan: finishSpan);
        }

        var holes = FirmamentV2SemanticHoleLowering.LowerSemanticHoles(document);
        if (holes.Count != holesDeclared.Length || holes.Count == 0)
        {
            return CombinedFailure("CombinedFeaturePlanChainInvalid: semantic Hole lowering did not preserve the admitted source hole set.", sourceSpan: holesDeclared[0].SourceSpan);
        }

        // Hole is intentionally the first construction stage.  Existing materialization
        // is used as the semantic/host proof; the bounded final plan below then consumes
        // its same source intent alongside the admitted outer-boundary finish.
        var host = FirmamentStockFrame.ForBox(box.Size[0], box.Size[1], box.Size[2]).CreateHoleHost();
        var holeStages = holes.Select(h => AirHoleSimpleShaftMaterializer.Execute(h, host)).ToArray();
        for (var i = 0; i < holeStages.Length; i++)
        {
            var stage = holeStages[i];
            if (!stage.Succeeded || stage.Plan is null)
                return CombinedFailure($"CombinedFeaturePlanChainInvalid: Hole '{holes[i].FeatureId}' could not materialize its semantic plan.",
                    stage.Diagnostics, holesDeclared[i].SourceSpan);
        }

        var combinedHoles = new List<CombinedTopBoundaryEdgeFinishThroughHole>(holes.Count);
        for (var i = 0; i < holes.Count; i++)
        {
            var hole = holes[i];
            if (hole.EndCondition is not AirHoleEndCondition.ThroughAll || hole.Stack.Kind is not (AirHoleStackKind.SimpleShaft or AirHoleStackKind.Counterbore or AirHoleStackKind.Countersink) || hole.Placement is not AirFaceLocalHolePlacement placement || hole.Axis.Direction.Z < 1d - 1e-9)
            {
                return CombinedFailure($"CombinedFeaturePlanChainInvalid: Hole '{hole.FeatureId}' cannot share this boundary finish. Use a top/+Z ThroughAll shaft, counterbore or countersink; blind and side-entry combined holes are not admitted.", sourceSpan: holesDeclared[i].SourceSpan);
            }
            var counterbore=hole.Stack.Components.OfType<AirHoleCounterboreComponent>().SingleOrDefault();
            var countersink = hole.Stack.Components.OfType<AirHoleCountersinkComponent>().SingleOrDefault();
            combinedHoles.Add(new CombinedTopBoundaryEdgeFinishThroughHole(hole.FeatureId, placement.U, placement.V, hole.Shaft.Radius,
                counterbore?.Radius,counterbore?.Depth,countersink?.EntryDiameter / 2d,countersink?.AngleDegrees));
        }

        // Preserve the existing chamfer admission and realization unchanged. Fillet
        // admission is owned by the same bounded final plan that realizes its cylinders.
        if (finish?.Kind == "Chamfer")
        {
            var compiledFinish = AirTopFaceBoundaryChamferCompiler.Compile(new(
                solid.Name, $"{solid.Name}.{finishName}", finish.Name,
                box.Size[0], box.Size[1], box.Size[2], finish.FaceAxis, finish.Target, finish.Kind, finish.Distance,
                new AirSourceSpan(finishSpan.Start, finishSpan.Length, document.ModelName)));
            if (!compiledFinish.Succeeded || compiledFinish.BRepPlan?.RealizationPlan is null)
                return CombinedFailure("CombinedFeatureSelectionLost: post-Hole outer boundary selection did not admit the exact chamfer planner.", compiledFinish.Diagnostics, finishSpan);
        }

        var parentHolePlan = string.Join(",", holeStages.Select(s => s.Plan!.HoleBRepPlan?.StableId ?? s.Plan!.SemanticFeatureId));
        var finalPlan = new CombinedTopBoundaryEdgeFinishThroughHolePlan(
            $"brep-plan:combined-hole-edgefinish:{solid.Name}:{finishName}",
            $"brep-plan:host:{solid.Name}->[{parentHolePlan}]",
            finish is null ? ["HostBRepPlan", "HoleChangedBRepPlan"] : ["HostBRepPlan", "HoleChangedBRepPlan", "EdgeFinishChangedBRepPlan"],
            box.Size[0], box.Size[1], host.ZMin, host.ZMax, finish?.Distance ?? 0, combinedHoles,
            finish is null ? TopBoundaryEdgeFinishKind.None : finish.Kind == "Fillet" ? TopBoundaryEdgeFinishKind.Fillet : TopBoundaryEdgeFinishKind.Chamfer);
        var materialized = CombinedTopBoundaryEdgeFinishThroughHoleBuilder.Build(finalPlan);
        if (!materialized.IsSuccess || materialized.Value is null)
        {
            return CombinedFailure("CombinedFeatureInteractionUnsupported: the combined Hole and EdgeFinish plan was rejected.", materialized.Diagnostics.Select(d => d.Message), finishSpan);
        }

        var body = materialized.Value;
        if (finish?.Kind == "Fillet")
        {
            var preflight = BrepExportPreflight.Validate(body);
            if (!preflight.IsValid)
                return CombinedFailure("CombinedFeatureMaterializerDiverged: fillet boundary failed analytic export preflight.", preflight.Diagnostics.Select(d => d.Message), finishSpan);
        }
        if (!FirmamentManifoldChecker.IsManifold(body))
        {
            return CombinedFailure("CombinedFeaturePlanChainInvalid: final combined plan did not produce one enclosed manifold body.");
        }
        var pmiSupport = ValidateV2PmiExportSupport(document);
        if (!pmiSupport.IsSuccess)
        {
            return KernelResult<FirmamentStepExportResult>.Failure(pmiSupport.Diagnostics);
        }
        var semanticPmi = BuildV2SemanticPmi(document, holes, solid.Name, body: body);
        var step = Step242Exporter.ExportBody(body, semanticPmi);
        if (!step.IsSuccess || step.Value is null)
        {
            return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        }
        var reimport = Step242Importer.ImportBody(step.Value);
        if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value))
        {
            return CombinedFailure("CombinedFeatureMaterializerDiverged: final STEP reimport did not preserve one enclosed manifold body.", reimport.Diagnostics.Select(d => d.Message));
        }

        var descendants = new List<SemanticTopologyDescendant>();
        var finalTop = body.Topology.Faces.Single(f => f.Id.Value == 2);
        var finalBottom = body.Topology.Faces.Single(f => f.Id.Value == 1);
        // The builder emits the counterbore wall and shoulder before the shaft.
        var wallFaceId = finish is null ? 7 : 11;
        for (var i = 0; i < holes.Count; i++)
        {
            var source = $"hole:{holes[i].FeatureId}";
            descendants.Add(new($"combined:{source}:mouth-loop", "Loop", SemanticTopologyRole.HoleEntryLoop, source, Loop: finalTop.LoopIds[i + 1], ParentStableId: holes[i].FeatureId));
            descendants.Add(new($"combined:{source}:exit-loop", "Loop", SemanticTopologyRole.HoleExitLoop, source, Loop: finalBottom.LoopIds[i + 1], ParentStableId: holes[i].FeatureId));
            if (combinedHoles[i].IsCounterbore)
            {
                descendants.Add(new($"combined:{source}:counterbore-wall", "Face", SemanticTopologyRole.HoleWallFace, source, Face: new FaceId(wallFaceId++), ParentStableId: holes[i].FeatureId));
                wallFaceId++; // annular shoulder, not a shaft wall
            }
            if (combinedHoles[i].IsCountersink)
                descendants.Add(new($"combined:{source}:countersink-wall", "Face", SemanticTopologyRole.HoleWallFace, source, Face: new FaceId(wallFaceId++), ParentStableId: holes[i].FeatureId));
            descendants.Add(new($"combined:{source}:shaft-wall", "Face", SemanticTopologyRole.HoleWallFace, source, Face: new FaceId(wallFaceId++), ParentStableId: holes[i].FeatureId));
        }
        for (var side = 0; finish is not null && side < 4; side++)
            descendants.Add(new($"combined:edgefinish:{finishName}:replacement:{side}", "Face", SemanticTopologyRole.EdgeFinishReplacementFace,
                $"edgefinish:{finishName}", Face: new FaceId(4 + 2 * side), ParentStableId: finishName));
        var correspondence = new SemanticTopologyCorrespondence(solid.Name, descendants, ["HostBRepPlan", "HoleChangedBRepPlan", "EdgeFinishChangedBRepPlan", "AuthoritativeBRepPlan"]);
        if (correspondence.Descendants.Count(d => d.Role == SemanticTopologyRole.HoleEntryLoop) != holes.Count || correspondence.Descendants.Count(d => d.Role == SemanticTopologyRole.HoleExitLoop) != holes.Count)
        {
            return CombinedFailure("CombinedFeaturePlanChainInvalid: final plan lost Hole mouth or exit correspondence.");
        }

        var holeRemoved = combinedHoles.Sum(h => h.RemovedVolume(host.ZMax - host.ZMin));
        var report = new FirmamentCombinedFeaturePlanReport(
            "CombinedHoleEdgeFinish", "Succeeded", finalPlan.ParentHostPlanId!, finalPlan.AppliedFeatureIds, finalPlan.PlanId, "Disjoint",
            descendants.Count(d => d.SourceStableId.StartsWith("hole:", StringComparison.Ordinal)),
            descendants.Count(d => d.Role == SemanticTopologyRole.EdgeFinishReplacementFace),
            box.Size[0] * box.Size[1] * (host.ZMax - host.ZMin), holeRemoved, finalPlan.AnalyticVolume,
            Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), body.Topology.Vertices.Count(), body.Topology.Edges.Count(), body.Topology.Faces.Count(),
            body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Plane), body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Cylinder), true, true);
        var featureReports = holes.Select(h => new FirmamentHoleFeatureReport(h.Name, "Hole", h.FeatureId, h.Shaft.Diameter, h.Placement.U, h.Placement.V, null, null, null, null, "top", null, nameof(AirHoleSimpleShaftMaterializer), "HoleChangedBRepPlan", h.Stack.Kind.ToString(), "CombinedHoleEdgeFinish", h.Stack.Kind==AirHoleStackKind.Counterbore?2:1, h.Stack.Kind==AirHoleStackKind.Countersink?1:0, h.Stack.Kind==AirHoleStackKind.Counterbore?1:0, report.StepSha256, true)).ToArray();
        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(
            step.Value,
            document.ModelName,
            0,
            "combined-hole-edgefinish",
            "CombinedHoleEdgeFinish",
            DatumInspection: document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.DatumPlane).Select(p => new FirmamentPmiInspectionDatum(p.Name, "planar", p.Target)).ToArray() ?? [],
            DimensionInspection: document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.HoleDiameter).Select(p => new FirmamentPmiInspectionDimension("Diameter", p.Target, null, p.Value ?? 0d, "explicit-v2-semantic-pmi", p.Name)).ToArray() ?? [],
            ConceptIr: document.ConceptIr,
            Features: featureReports,
            Combined: report) { RuntimeBody = body, RuntimeCorrespondence = correspondence, MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "Hole", holes.Select(h => h.Name).ToArray()).Concat(finish is null ? [] : new[] { new FirmamentFeatureReceipt(solid.Name, "EdgeFinish", finish.Name) }).ToArray() });
    }

    private static KernelResult<FirmamentStepExportResult> ExportV2TopBoundaryFillet(
        FirmamentV2Document document, FirmamentV2SolidBinding solid, FirmamentV2EdgeFinishDecl finish, FirmamentV2BoxRecord box)
    {
        var frame = FirmamentStockFrame.ForBox(box.Size[0], box.Size[1], box.Size[2]);
        var host = frame.CreateHoleHost();
        var plan = new CombinedTopBoundaryEdgeFinishThroughHolePlan(
            $"brep-plan:top-boundary-fillet:{solid.Name}:{finish.Name}", $"brep-plan:host:{solid.Name}",
            ["HostBRepPlan", "EdgeFinishChangedBRepPlan"], box.Size[0], box.Size[1], host.ZMin, host.ZMax,
            finish.Distance, [], TopBoundaryEdgeFinishKind.Fillet);
        var built = CombinedTopBoundaryEdgeFinishThroughHoleBuilder.Build(plan);
        if (!built.IsSuccess || built.Value is null)
            return CombinedFailure("CombinedFeaturePlanChainInvalid: top-boundary fillet plan was rejected.", built.Diagnostics.Select(d => d.Message), finish.SourceSpan);
        if (!FirmamentManifoldChecker.IsManifold(built.Value))
            return CombinedFailure("CombinedFeaturePlanChainInvalid: top-boundary fillet is not manifold.", sourceSpan: finish.SourceSpan);
        var preflight = BrepExportPreflight.Validate(built.Value);
        if (!preflight.IsValid)
            return CombinedFailure("CombinedFeatureMaterializerDiverged: fillet boundary failed analytic export preflight.", preflight.Diagnostics.Select(d => d.Message), finish.SourceSpan);
        var pmiSupport = ValidateV2PmiExportSupport(document);
        if (!pmiSupport.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(pmiSupport.Diagnostics);
        var step = Step242Exporter.ExportBody(built.Value, BuildV2SemanticPmi(document, [], solid.Name, body: built.Value));
        if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        var imported = Step242Importer.ImportBody(step.Value);
        if (!imported.IsSuccess || imported.Value is null || !FirmamentManifoldChecker.IsManifold(imported.Value))
            return CombinedFailure("CombinedFeatureMaterializerDiverged: top-boundary fillet STEP round trip failed.", imported.Diagnostics.Select(d => d.Message), finish.SourceSpan);
        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(
            step.Value, document.ModelName, 0, "top-boundary-fillet", "TopBoundaryFillet") { RuntimeBody = built.Value, MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", finish.Name) });
    }

    private static KernelResult<FirmamentStepExportResult> CombinedFailure(string message, IEnumerable<string>? details = null, FirmamentV2SourceSpan? sourceSpan = null) =>
        KernelResult<FirmamentStepExportResult>.Failure((new[] { message }).Concat(details ?? []).Distinct().Select(detail => new Kernel.Core.Diagnostics.KernelDiagnostic(
            Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
            Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
            detail,
            "FirmamentV2.CombinedHoleEdgeFinish")
            { SourceSpan = sourceSpan is null ? null : new(sourceSpan.Start, sourceSpan.Length) }).ToArray());

    private static KernelResult<FirmamentStepExportResult>? TryExportV2AirChamferBody(FirmamentV2Document document)
    {
        var finishes = (document.ModifyBlocks ?? []).SelectMany(m => (m.EdgeFinishes ?? []).Select(f => (Modify: m, Finish: f))).ToArray();
        if (finishes.Length == 0 || finishes.Any(f => f.Finish.Target == "AllEdges")) return null;
        // A narrow finish-only route never owns a document that also has semantic holes.
        // CombinedHoleEdgeFinish is the only X1 route permitted to claim that shape.
        if ((document.ModifyBlocks ?? []).Any(m => m.SemanticHoles.Count > 0)) return null;
        if (finishes.Length == 2 && finishes.All(x => string.Equals(x.Finish.Kind, "Chamfer", StringComparison.Ordinal)))
        {
            if (document.Solids.Count != 1 || document.ModifyBlocks!.Count != 1 || document.ModifyBlocks[0].Regions.Count != 0 || document.ModifyBlocks[0].SemanticHoles.Count != 0)
                return AirChamferFailure("localized-junction-production-route-requires-one-box-and-one-modify-block");
            var junctionSolid = document.Solids.SingleOrDefault(s => s.Name == finishes[0].Modify.TargetSolid);
            if (junctionSolid?.Primitive is not FirmamentV2BoxRecord junctionBox || junctionBox.Size.Count != 3)
                return AirChamferFailure("localized-junction-unsupported-history:expected-history-known-box");
            return ExportV2LocalizedEdgeJunctionChamfer(document, junctionSolid, finishes[0].Finish, finishes[1].Finish, junctionBox);
        }
        if (finishes.Length == 2 && finishes.All(x => string.Equals(x.Finish.Kind, "Fillet", StringComparison.Ordinal)))
        {
            if (document.Solids.Count != 1 || document.ModifyBlocks!.Count != 1 || document.ModifyBlocks[0].Regions.Count != 0 || document.ModifyBlocks[0].SemanticHoles.Count != 0)
                return AirChamferFailure("localized-fillet-junction-production-route-requires-one-box-and-one-modify-block");
            var junctionSolid = document.Solids.SingleOrDefault(s => s.Name == finishes[0].Modify.TargetSolid);
            if (junctionSolid?.Primitive is not FirmamentV2BoxRecord junctionBox || junctionBox.Size.Count != 3)
                return AirChamferFailure("localized-fillet-junction-unsupported-history:expected-history-known-box");
            return ExportV2LocalizedEdgeJunctionFillet(document, junctionSolid, finishes[0].Finish, finishes[1].Finish, junctionBox);
        }
        if (finishes.Length == 3 && finishes.All(x => string.Equals(x.Finish.Kind, "Fillet", StringComparison.Ordinal)))
        {
            if (document.Solids.Count != 1 || document.ModifyBlocks!.Count != 1 || document.ModifyBlocks[0].Regions.Count != 0 || document.ModifyBlocks[0].SemanticHoles.Count != 0)
                return AirChamferFailure("localized-trihedral-fillet-production-route-requires-one-box-and-one-modify-block");
            var junctionSolid = document.Solids.SingleOrDefault(s => s.Name == finishes[0].Modify.TargetSolid);
            if (junctionSolid?.Primitive is not FirmamentV2BoxRecord junctionBox || junctionBox.Size.Count != 3)
                return AirChamferFailure("localized-trihedral-fillet-unsupported-history:expected-history-known-box");
            return ExportV2LocalizedTrihedralFillet(document, junctionSolid, finishes.Select(x => x.Finish).ToArray(), junctionBox);
        }
        if (finishes.Length == 3)
            return AirChamferFailure("localized-trihedral-fillet-unsupported-finish-combination:mixed-families");
        if (finishes.Length == 2)
            return AirChamferFailure("localized-junction-unsupported-finish-combination:mixed-families");
        if (finishes.Length > 2)
            return AirChamferFailure("localized-trihedral-fillet-unsupported-valence:three-selected-edges-maximum");
        if (finishes.Length != 1 || document.Solids.Count != 1 || document.ModifyBlocks!.Count != 1
            || document.ModifyBlocks[0].Regions.Count != 0 || document.ModifyBlocks[0].SemanticHoles.Count != 0)
            return AirChamferFailure("air-chamfer-production-route-requires-one-box-and-one-edge-finish");

        var (modify, finish) = finishes[0];
        var solid = document.Solids.SingleOrDefault(s => s.Name == modify.TargetSolid);
        if (solid?.Primitive is FirmamentV2CylinderRecord cylinder)
            return ExportV2CircularRimChamfer(document, solid, finish, cylinder);
        if (solid?.Primitive is not FirmamentV2BoxRecord box || box.Size.Count != 3)
            return AirChamferFailure("chamfer-unsupported-history:expected-history-known-box-or-right-circular-cylinder");

        if (finish.Target == "Boundary" && finish.FaceAxis != "+Z" && finish.Kind is "Chamfer" or "Fillet")
            return ExportV2BoxFaceBoundaryFinish(document, solid, finish, box);

        // AIR-FILLET-LOCALIZED-M1: semantic support-face selection only; emitted BRep IDs never enter Firmament.
        if (string.Equals(finish.Kind, "Fillet", StringComparison.Ordinal))
        {
            if (finish.FaceAxis == "+Z" && finish.Target == "Boundary")
                return ExportV2TopBoundaryFillet(document, solid, finish, box);
            return ExportV2LocalizedTangentBlendSingleEdgeFillet(document, solid, finish, box);
        }

        // AIR-CHAMFER-LOCALIZED-PLAN-A1: a semantic face-pair selector, never an emitted edge id.
        if (string.Equals(finish.FaceAxis, "+X", StringComparison.Ordinal)
            && string.Equals(finish.Target, "SharedEdgePlusZ", StringComparison.Ordinal))
            return ExportV2LocalizedPlanarSingleEdgeChamfer(document, solid, finish, box);

        var compiled = AirTopFaceBoundaryChamferCompiler.Compile(new(
            solid.Name,
            $"{solid.Name}.{finish.Name}",
            finish.Name,
            box.Size[0], box.Size[1], box.Size[2],
            finish.FaceAxis, finish.Target, finish.Kind, finish.Distance,
            new AirSourceSpan(finish.SourceSpan.Start, finish.SourceSpan.Length, document.ModelName)));
        if (!compiled.Succeeded || compiled.Body is null || compiled.Construction is null || compiled.BRepPlan?.RealizationPlan is null || compiled.Topology is null)
            return AirChamferFailure(compiled.Feature.AdmissionReason, compiled.Diagnostics);

        var manifold = FirmamentManifoldChecker.IsManifold(compiled.Body);
        if (!manifold) return AirChamferFailure("air-chamfer-emitted-body-is-not-manifold", compiled.Diagnostics);

        var step = Step242Exporter.ExportBody(compiled.Body, new Step242ExportOptions
        {
            ProductName = compiled.Feature.FeatureName,
            ApplicationName = AirTopFaceBoundaryChamferCompileResult.ProductionRoute,
            BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
            BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
        });
        if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);

        var reimport = Step242Importer.ImportBody(step.Value);
        if (!reimport.IsSuccess || reimport.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(reimport.Diagnostics);
        var reimported = reimport.Value;
        var reimportedManifold = FirmamentManifoldChecker.IsManifold(reimported);
        if (!reimportedManifold) return AirChamferFailure("air-chamfer-step-reimport-is-not-manifold");

        var plan = compiled.BRepPlan.RealizationPlan;
        var top = plan.Vertices.Where(v => v.SectionIndex == 2).Select(v => v.Point).ToArray();
        var sourceBounds = Bounds(compiled.Body);
        var reimportedBounds = Bounds(reimported);
        var featureProvenance = new Dictionary<string, string>(StringComparer.Ordinal);
        if (solid.Provenance?.TryGetValue("Bounds", out var boundsProvenance) == true) featureProvenance["Bounds"] = boundsProvenance;
        if (finish.Provenance?.TryGetValue("Face", out var faceProvenance) == true) featureProvenance["Selection"] = faceProvenance;
        if (finish.Provenance?.TryGetValue("Distance", out var distanceProvenance) == true) featureProvenance["Distance"] = distanceProvenance;
        var report = new FirmamentAirChamferReport(
            new("Chamfer", compiled.Feature.BodyId, compiled.Feature.FeatureId, compiled.Feature.FeatureName, $"FaceBoundary({compiled.Feature.Selection.FaceAxis})", compiled.Feature.Rule.Distance, compiled.Feature.Rule.Unit, $"{compiled.Feature.SourceSpan.Start}:{compiled.Feature.SourceSpan.Length}", compiled.Feature.Admission.ToString(), compiled.Feature.AdmissionReason, featureProvenance),
            new("SectionTransition", compiled.Construction.Profiles.Count, compiled.Construction.Profiles.Select(p => p.Z).ToArray(), compiled.Construction.Transition.Correspondence, compiled.Construction.Transition.SplitPolicy),
            new(compiled.BRepPlan.IsAuthoritative, plan.Vertices.Count, plan.Edges.Count, plan.Faces.Count, plan.ExpectedLoopCount, plan.ExpectedCoedgeCount, compiled.BRepPlan.Summary.ChamferFaceCount, plan.SplitPolicy, plan.DeterministicSignature),
            new(AirTopFaceBoundaryChamferCompileResult.ProductionRoute, false, manifold, compiled.Topology.VertexCount, compiled.Topology.EdgeCount, compiled.Topology.FaceCount, sourceBounds,
                top.Min(p => p.X) - (-box.Size[0] / 2d), top.Min(p => p.Y) - (-box.Size[1] / 2d)),
            new("AP242", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true,
                reimported.Topology.Vertices.Count(), reimported.Topology.Edges.Count(), reimported.Topology.Faces.Count(), reimportedBounds, reimportedManifold));

        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(
            step.Value, compiled.Feature.FeatureId, 0, "air-chamfer", "top-face-boundary-chamfer", Air: report, ConceptIr: document.ConceptIr) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", finish.Name) });
    }

    private static KernelResult<FirmamentStepExportResult> ExportV2LocalizedPlanarSingleEdgeChamfer(
        FirmamentV2Document document,
        FirmamentV2SolidBinding solid,
        FirmamentV2EdgeFinishDecl finish,
        FirmamentV2BoxRecord box)
    {
        var compiled = AirLocalizedPlanarReplacementChamferCompiler.Compile(new(
            solid.Name, $"{solid.Name}.{finish.Name}", finish.Name, box.Size[0], box.Size[1], box.Size[2],
            finish.FaceAxis, "+Z", finish.Kind, finish.Distance,
            new AirSourceSpan(finish.SourceSpan.Start, finish.SourceSpan.Length, document.ModelName)));
        if (!compiled.Succeeded || compiled.Body is null || compiled.Construction is null || compiled.BRepPlan?.LocalizedEdgeReplacementRealizationPlan is null)
            return AirChamferFailure(compiled.Error?.Code ?? compiled.Feature.AdmissionReason, compiled.Diagnostics);

        // AIR builds centered kernel stock; publish in the same bottom-anchored frame as the authored Box.
        var body = FirmamentPrimitiveExecutionTranslation.TranslateBody(compiled.Body,
            new Vector3D(0, 0, FirmamentStockFrame.ForBox(box.Size[0], box.Size[1], box.Size[2]).KernelCenteredToStockZ));
        var preflight = BrepExportPreflight.Validate(body);
        if (!preflight.IsValid) return AirChamferFailure("localized-chamfer-preflight-verification-failed", preflight.Diagnostics.Select(d => d.Code));
        if (!FirmamentManifoldChecker.IsManifold(body)) return AirChamferFailure("localized-chamfer-emitted-body-is-not-manifold");
        var step = Step242Exporter.ExportBody(body, new Step242ExportOptions
        {
            ProductName = compiled.Feature.FeatureName,
            ApplicationName = AirLocalizedPlanarReplacementChamferCompileResult.ProductionRoute,
            BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
            BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
        });
        if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        var reimport = Step242Importer.ImportBody(step.Value);
        if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value))
            return AirChamferFailure("localized-chamfer-step-reimport-verification-failed");

        var plan = compiled.Construction.TopologyPlan;
        var witness = compiled.Construction.Witness;
        var planes = body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Plane);
        var report = new FirmamentAirChamferReport(
            new("Chamfer", compiled.Feature.BodyId, compiled.Feature.FeatureId, compiled.Feature.FeatureName, "SharedEdge(+X,+Z)", finish.Distance, "mm",
                $"{compiled.Feature.SourceSpan.Start}:{compiled.Feature.SourceSpan.Length}", compiled.Feature.Admission.ToString(), compiled.Feature.AdmissionReason,
                new Dictionary<string, string> { ["Selection"] = "semantic Face(+X),Face(+Z)", ["MaterialSide"] = witness.MaterialSide }),
            new("LocalizedPlanarReplacement", 0, [], "ordered-explicit-loops", "ExplicitOwnedEndpoints",
                $"retainedFaces=2;replacementFaces=1;endpointPolicy={witness.EndpointPolicy}", true),
            new(true, plan.ExpectedVertexCount, plan.ExpectedEdgeCount, plan.ExpectedFaceCount, plan.ExpectedLoopCount, plan.ExpectedCoedgeCount, 1,
                "ExplicitOwnedEndpoints", plan.DeterministicSignature, "LocalizedPlanarReplacement"),
            new(AirLocalizedPlanarReplacementChamferCompileResult.ProductionRoute, false, true, body.Topology.Vertices.Count(), body.Topology.Edges.Count(), body.Topology.Faces.Count(), Bounds(body), finish.Distance, finish.Distance, 0, 0, planes),
            new("AP242", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true, reimport.Value.Topology.Vertices.Count(), reimport.Value.Topology.Edges.Count(), reimport.Value.Topology.Faces.Count(), Bounds(reimport.Value), true),
            new("SharedEdge(+X,+Z)", "LocalizedPlanarReplacement", "Direct", 2, 1, "ExplicitOwnedEndpoints", new(true, plan.DeterministicSignature), "valid", false),
            LocalizedEdgeFinish: new("Chamfer", "SharedEdge(+X,+Z)", "EqualDistance", finish.Distance, "LocalizedEdgeReplacement", "PlanarChamfer", "Direct", 2, 1, "ExplicitOwnedEndpoints", new(true, plan.DeterministicSignature), "valid", false));
        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, compiled.Feature.FeatureId, 0, "air-chamfer", "localized-planar-single-edge-chamfer", Air: report, ConceptIr: document.ConceptIr) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", finish.Name) });
    }

    private static KernelResult<FirmamentStepExportResult> ExportV2LocalizedEdgeJunctionChamfer(
        FirmamentV2Document document,
        FirmamentV2SolidBinding solid,
        FirmamentV2EdgeFinishDecl first,
        FirmamentV2EdgeFinishDecl second,
        FirmamentV2BoxRecord box)
    {
        var compiled = AirLocalizedEdgeJunctionChamferCompiler.Compile(new(
            solid.Name, $"{solid.Name}.{first.Name}.{second.Name}", $"{first.Name}+{second.Name}", box.Size[0], box.Size[1], box.Size[2],
            first.FaceAxis, first.Target, second.FaceAxis, second.Target, first.Distance, second.Distance,
            new AirSourceSpan(first.SourceSpan.Start, first.SourceSpan.Length + second.SourceSpan.Length, document.ModelName)));
        if (!compiled.Succeeded || compiled.Body is null || compiled.Construction is null || compiled.BRepPlan?.LocalizedEdgeJunctionRealizationPlan is null)
            return AirChamferFailure(compiled.Error?.Code ?? "localized-junction-construction-witness-required", compiled.Diagnostics);

        var body = compiled.Body;
        var preflight = BrepExportPreflight.Validate(body);
        if (!preflight.IsValid) return AirChamferFailure("localized-junction-chamfer-preflight-verification-failed", preflight.Diagnostics.Select(d => d.Code));
        if (!FirmamentManifoldChecker.IsManifold(body)) return AirChamferFailure("localized-junction-chamfer-emitted-body-is-not-manifold");
        var step = Step242Exporter.ExportBody(body, new Step242ExportOptions
        {
            ProductName = compiled.Construction.ConstructionId,
            ApplicationName = AirLocalizedEdgeJunctionChamferCompileResult.ProductionRoute,
            BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
            BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
        });
        if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        var reimport = Step242Importer.ImportBody(step.Value);
        if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value))
            return AirChamferFailure("localized-junction-chamfer-step-reimport-verification-failed");

        var topology = compiled.Construction.TopologyPlan;
        var planes = body.Geometry.Surfaces.Count(surface => surface.Value.Kind == SurfaceGeometryKind.Plane);
        var report = new FirmamentAirChamferReport(
            new("Chamfer", solid.Name, $"{solid.Name}.{first.Name}.{second.Name}", $"{first.Name}+{second.Name}", "SharedEdge(+X,+Z),SharedEdge(+Y,+Z)", first.Distance, "mm",
                $"{first.SourceSpan.Start}:{first.SourceSpan.Length}|{second.SourceSpan.Start}:{second.SourceSpan.Length}", "Admitted", "localized-junction-direct-single-miter-candidate",
                new Dictionary<string, string> { ["Selection"] = "semantic Face(+X),Face(+Z); Face(+Y),Face(+Z)", ["MaterialSide"] = compiled.Construction.MaterialSide }),
            new("LocalizedEdgeJunction", 0, [], "ordered-explicit-loops", "SharedMiterEdge",
                $"replacementFaces=2;junctionFaces=0;cornerPatch={compiled.Construction.CornerPatch.Kind};boundaryOwnership={compiled.Construction.BoundaryOwnership}", true),
            new(true, topology.ExpectedVertexCount, topology.ExpectedEdgeCount, topology.ExpectedFaceCount, topology.ExpectedLoopCount, topology.ExpectedCoedgeCount, 2,
                "SharedMiterEdge", topology.DeterministicSignature, "LocalizedEdgeJunction"),
            new(AirLocalizedEdgeJunctionChamferCompileResult.ProductionRoute, false, true, body.Topology.Vertices.Count(), body.Topology.Edges.Count(), body.Topology.Faces.Count(), Bounds(body), first.Distance, first.Distance, 0, 0, planes),
            new("AP242", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true, reimport.Value.Topology.Vertices.Count(), reimport.Value.Topology.Edges.Count(), reimport.Value.Topology.Faces.Count(), Bounds(reimport.Value), true),
            LocalizedEdgeJunction: new(["SharedEdge(+X,+Z)", "SharedEdge(+Y,+Z)"], "Chamfer", "EqualDistance", first.Distance, "Direct", "LocalizedEdgeJunction", compiled.Construction.CornerPatch.Kind, 2, 0,
                new(true, topology.DeterministicSignature), "valid", false, 1, 1));
        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, $"{solid.Name}.{first.Name}.{second.Name}", 0, "air-chamfer", "localized-edge-junction-chamfer", Air: report, ConceptIr: document.ConceptIr) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", first.Name, second.Name) });
    }

    private static KernelResult<FirmamentStepExportResult> ExportV2LocalizedEdgeJunctionFillet(
        FirmamentV2Document document,
        FirmamentV2SolidBinding solid,
        FirmamentV2EdgeFinishDecl first,
        FirmamentV2EdgeFinishDecl second,
        FirmamentV2BoxRecord box)
    {
        var compiled = AirLocalizedEdgeJunctionFilletCompiler.Compile(new(
            solid.Name, $"{solid.Name}.{first.Name}.{second.Name}", $"{first.Name}+{second.Name}", box.Size[0], box.Size[1], box.Size[2],
            first.FaceAxis, first.Target, second.FaceAxis, second.Target, first.Distance, second.Distance,
            new AirSourceSpan(first.SourceSpan.Start, first.SourceSpan.Length + second.SourceSpan.Length, document.ModelName)));
        if (!compiled.Succeeded || compiled.Body is null || compiled.Construction is null || compiled.BRepPlan?.LocalizedEdgeJunctionRealizationPlan is null)
            return AirChamferFailure(compiled.Error?.Code ?? "localized-fillet-junction-direct-intersection-required", compiled.Diagnostics);

        var body = compiled.Body;
        var preflight = BrepExportPreflight.Validate(body);
        if (!preflight.IsValid) return AirChamferFailure("localized-fillet-junction-preflight-verification-failed", preflight.Diagnostics.Select(d => d.Code));
        if (!FirmamentManifoldChecker.IsManifold(body)) return AirChamferFailure("localized-fillet-junction-emitted-body-is-not-manifold");
        var step = Step242Exporter.ExportBody(body, new Step242ExportOptions
        {
            ProductName = compiled.Construction.ConstructionId,
            ApplicationName = AirLocalizedEdgeJunctionFilletCompileResult.ProductionRoute,
            BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
            BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
        });
        if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        var reimport = Step242Importer.ImportBody(step.Value);
        if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value))
            return AirChamferFailure("localized-fillet-junction-step-reimport-verification-failed");

        var topology = compiled.Construction.TopologyPlan;
        var cylinders = body.Geometry.Surfaces.Count(surface => surface.Value.Kind == SurfaceGeometryKind.Cylinder);
        var planes = body.Geometry.Surfaces.Count(surface => surface.Value.Kind == SurfaceGeometryKind.Plane);
        var report = new FirmamentAirChamferReport(
            new("Fillet", solid.Name, $"{solid.Name}.{first.Name}.{second.Name}", $"{first.Name}+{second.Name}", "SharedEdge(+X,+Z),SharedEdge(+Y,+Z)", first.Distance, "mm",
                $"{first.SourceSpan.Start}:{first.SourceSpan.Length}|{second.SourceSpan.Start}:{second.SourceSpan.Length}", "Admitted", "localized-fillet-junction-direct-intersection-candidate",
                new Dictionary<string, string> { ["Selection"] = "semantic Face(+X),Face(+Z); Face(+Y),Face(+Z)", ["MaterialSide"] = compiled.Construction.MaterialSide, ["Branch"] = compiled.Construction.Closure.Branch }),
            new("LocalizedEdgeJunction", 0, [], "ordered-explicit-loops", "DirectIntersectionEllipse",
                $"replacementFaces=2;junctionFaces=0;sharedEdges=1;curve=Ellipse;branch={compiled.Construction.Closure.Branch}", true),
            new(true, topology.ExpectedVertexCount, topology.ExpectedEdgeCount, topology.ExpectedFaceCount, topology.ExpectedLoopCount, topology.ExpectedCoedgeCount, 0,
                "DirectIntersectionEllipse", topology.DeterministicSignature, "LocalizedEdgeJunction"),
            new(AirLocalizedEdgeJunctionFilletCompileResult.ProductionRoute, false, true, body.Topology.Vertices.Count(), body.Topology.Edges.Count(), body.Topology.Faces.Count(), Bounds(body), first.Distance, first.Distance, cylinders, 0, planes),
            new("AP242", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true, reimport.Value.Topology.Vertices.Count(), reimport.Value.Topology.Edges.Count(), reimport.Value.Topology.Faces.Count(), Bounds(reimport.Value), true),
            LocalizedEdgeJunction: new(["SharedEdge(+X,+Z)", "SharedEdge(+Y,+Z)"], "Fillet", "ConstantRadius", first.Distance, "Direct", "LocalizedEdgeJunction", "None(DirectIntersection)", 2, 0,
                new(true, topology.DeterministicSignature), "valid", false, 1, 1,
                new("DirectIntersection", "Cylinder", "Cylinder", "Ellipse", true, 1, compiled.Construction.Closure.Branch)));
        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, $"{solid.Name}.{first.Name}.{second.Name}", 0, "air-fillet", "localized-edge-junction-fillet", Air: report, ConceptIr: document.ConceptIr) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", first.Name, second.Name) });
    }

    /// <summary>
    /// <c>Revolve&lt;Hollow&gt;</c>: the Profile becomes a meridian about the axis, the general meridian hollow derives
    /// its constant wall, and the wall turns into a seamless shell of revolution.
    /// </summary>
    private static KernelResult<FirmamentStepExportResult> ExportHollowRevolve(ResolvedRevolve authored, PrismaticHollowIntent hollow)
    {
        KernelResult<FirmamentStepExportResult> Fail(IEnumerable<string> messages) => KernelResult<FirmamentStepExportResult>.Failure(messages.Select(message =>
            new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "FirmamentV2.Revolve")).ToArray());
        var plane = authored.Profile.EffectiveConstructionPlane;
        var origin = new Point3D(authored.Axis.Origin.X, authored.Axis.Origin.Y, authored.Axis.Origin.Z);
        var direction = new Vector3D(authored.Axis.Direction.X, authored.Axis.Direction.Y, authored.Axis.Direction.Z);
        direction = direction * (1d / direction.Length);
        var local = plane.ToLocal(origin);
        var d = (X: direction.Dot(plane.AxisX.ToVector()), Y: direction.Dot(plane.AxisY.ToVector()));
        if (authored.Profile.Loops.Count != 1)
            return Fail(["firmament-v2-hollow-revolve-meridian-invalid: Revolve<Hollow> turns one outer Profile loop."]);
        var curves = authored.Profile.Loops[0].Segments.Select(segment => segment.Geometry).ToArray();
        // The meridian's radius runs away from the axis on the Profile's side.
        var sample = curves.Select(c => Kernel.Core.Geometry.Planar.LineArcInset.StartPoint(ProfileInset2D.ToPlanar(c)))
            .Select(p => (p.X - local.X) * -d.Y + (p.Y - local.Y) * d.X).MaxBy(double.Abs);
        var n = sample >= 0d ? (X: -d.Y, Y: d.X) : (X: d.Y, Y: -d.X);
        (double R, double Z) Map((double X, double Y) p) => ((p.X - local.X) * n.X + (p.Y - local.Y) * n.Y, (p.X - local.X) * d.X + (p.Y - local.Y) * d.Y);
        var reflected = n.X * d.Y - n.Y * d.X < 0d;
        var meridian = new List<Kernel.Core.Geometry.Planar.PlanarSpan>();
        foreach (var curve in curves)
        {
            switch (curve)
            {
                case LineArcLineSegment2D line:
                    meridian.Add(new Kernel.Core.Geometry.Planar.PlanarLine(Map(line.Start), Map(line.End)));
                    break;
                case LineArcCircularArc2D arc:
                {
                    var center = Map(arc.Center);
                    var start = Map((arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians)));
                    meridian.Add(new Kernel.Core.Geometry.Planar.PlanarArc(center, arc.Radius, Math.Atan2(start.Z - center.Z, start.R - center.R),
                        reflected ? -arc.SweepAngleRadians : arc.SweepAngleRadians));
                    break;
                }
                default:
                    return Fail(["hollow-offset-curve-unsupported: Revolve<Hollow> meridians are lines and circular arcs."]);
            }
        }
        var wall = Kernel.Core.Brep.Features.MeridianHollow.Wall(meridian, hollow.WallThickness, hollow.OpenTop, hollow.OpenBottom);
        if (!wall.IsSuccess) return Fail(wall.Diagnostics.Select(x => x.Message));
        var radial = plane.ToWorldVector(n);
        var frame = new Kernel.Core.Brep.Features.RevolutionFrame(origin, Direction3D.Create(direction), Direction3D.Create(radial));
        var shell = Kernel.Core.Brep.Features.BrepRevolvedShell.Build(wall.Value, frame);
        if (!shell.IsSuccess) return Fail(shell.Diagnostics.Select(x => x.Message));
        var body = shell.Value.Body;
        var step = Step242Exporter.ExportBody(body, new Step242ExportOptions { ProductName = authored.Name });
        if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        var reimport = Step242Importer.ImportBody(step.Value);
        if (!reimport.IsSuccess || reimport.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(reimport.Diagnostics);
        if (!FirmamentManifoldChecker.IsManifold(reimport.Value)) return Fail([$"firmament-revolve-step-reimport-not-manifold:{authored.Name}"]);
        var surfaces = body.Topology.Faces.Select(face => body.GetFaceSurface(face.Id).Kind).ToArray();
        var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))).ToLowerInvariant();
        var report = new FirmamentRevolveReport(authored.Profile.Name, authored.AxisName, authored.SweepRadians,
            authored.SweepRadians * 180d / Math.PI, authored.AuthoredAlias, authored.SweepRadians < 0d ? "Negative" : "Positive", "Full", hash,
            surfaces.Select(kind => kind.ToString()).ToArray(), body.Topology.Vertices.Count(), body.Topology.Edges.Count(), body.Topology.Faces.Count(),
            surfaces.Count(kind => kind == SurfaceGeometryKind.Plane), surfaces.Count(kind => kind == SurfaceGeometryKind.Cylinder),
            surfaces.Count(kind => kind == SurfaceGeometryKind.Cone), surfaces.Count(kind => kind == SurfaceGeometryKind.Sphere),
            surfaces.Count(kind => kind == SurfaceGeometryKind.Torus), surfaces.Count(kind => kind == SurfaceGeometryKind.SurfaceOfRevolution), true, hash);
        return KernelResult<FirmamentStepExportResult>.Success(new(step.Value, authored.Name, 0, "hollow-revolve", "revolve", Revolve: report,
            EngineeringFeatures: [new(authored.Name, "Revolve<Hollow>", authored.StableId, authored.Name, authored.Axis.StableId, authored.Profile.Name,
                hollow.WallThickness, "WallThickness", "Base", PolicySource: "MeridianHollow", MaterializationRoute: "BrepRevolvedShell")]) { RuntimeBodySourceName = authored.Name, RuntimeBody = body });
    }

    private static KernelResult<FirmamentStepExportResult>? TryExportV2HollowBody(FirmamentV2Document document)
    {
        if (document.Solids.Count != 1 || document.Solid.ConstructionPolicy != FirmamentV2ConstructionPolicy.Hollow)
            return null;
        // A parsed Perforation must reach its own topology route. Exporting the
        // unmodified Hollow here would silently lose the authored openings.
        if ((document.ModifyBlocks ?? []).Any(block => (block.Perforations?.Count ?? 0) > 0)) return null;
        var solid = document.Solid;
        if (solid.Hollow is null || solid.Hollow.Openings.Count != 1 || solid.Hollow.Openings[0] != "Top")
            return HollowFailure("UnsupportedOpening");

        KernelResult<ThinWalledBodyRealization> realization = solid.Primitive switch
        {
            FirmamentV2RoundedBoxRecord rounded when rounded.Size.Count == 3 => HollowPrimitives.RoundedBox(rounded.Size[0], rounded.Size[1], rounded.Size[2], rounded.CornerRadius, solid.Hollow.WallThickness),
            FirmamentV2FrustumRecord frustum => ThinWalledBodyBRepPlanner.CreateFrustum(frustum.BottomRadius, frustum.TopRadius, frustum.Height, solid.Hollow.WallThickness),
            FirmamentV2CylinderRecord cylinder => ThinWalledBodyBRepPlanner.CreateCylinder(cylinder.Radius, cylinder.Height, solid.Hollow.WallThickness, solid.Hollow.BottomBlendRadius),
            _ => throw new InvalidOperationException("Parser admitted a Hollow policy without a HollowConstructible witness.")
        };
        if (!realization.IsSuccess || realization.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(realization.Diagnostics);
        var body = realization.Value.Body;
        var preflight = BrepExportPreflight.Validate(body);
        if (!preflight.IsValid) return HollowFailure("VerificationFailure");
        if (!FirmamentManifoldChecker.IsManifold(body)) return HollowFailure("VerificationFailure: vessel boundary is not a closed manifold");
        var step = Step242Exporter.ExportBody(body, new Step242ExportOptions
        {
            ProductName = solid.Name,
            ApplicationName = "Aetheris.Firmament.Primitive<Hollow>",
            BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
            BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
        });
        if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        var reimport = Step242Importer.ImportBody(step.Value);
        if (!reimport.IsSuccess || reimport.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(reimport.Diagnostics);
        var reimportedManifold = FirmamentManifoldChecker.IsManifold(reimport.Value);
        if (!reimportedManifold) return HollowFailure("VerificationFailure: STEP reimport vessel boundary is not manifold");
        var surfaces = body.Geometry.Surfaces.Select(x => x.Value.Kind).ToArray();
        var r = realization.Value;
        var volume = solid.Primitive switch
        {
            FirmamentV2RoundedBoxRecord rounded => RoundedHollowVolume(rounded, r.Feature.WallThickness),
            FirmamentV2FrustumRecord frustum => FrustumHollowVolume(frustum, r.Feature.WallThickness),
            FirmamentV2CylinderRecord cylinder => CylinderHollowVolume(cylinder, r.Feature.WallThickness, solid.Hollow.BottomBlendRadius),
            _ => throw new InvalidOperationException("Unsupported Hollow volume witness.")
        };
        var report = new FirmamentHollowBodyReport(r.Feature.PrimitiveKind, "Hollow", r.Feature.WallThickness, r.Feature.Openings, r.Feature.Witness.Kind, r.Feature.Witness.Exact,
            r.Feature.ThicknessPolicy, r.Construction.ThicknessWitnesses.All(w => w.Exact && double.Abs(w.Distance - r.Feature.WallThickness) <= 1e-9), r.Plan.Kind, r.Plan.IsAuthoritative, r.Plan.DeterministicSignature,
            body.Topology.Vertices.Count(), body.Topology.Edges.Count(), body.Topology.Faces.Count(), surfaces.Count(x => x == SurfaceGeometryKind.Plane), surfaces.Count(x => x == SurfaceGeometryKind.Cylinder), surfaces.Count(x => x == SurfaceGeometryKind.Cone), r.Plan.RimFaces.Count,
            volume, Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true, reimportedManifold);
        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, solid.Name, 0, "air-hollow", "thin-walled-body", Hollow: report));
    }

    private static string RoundedHollowVolume(FirmamentV2RoundedBoxRecord rounded, double t)
    {
        var outerArea = RoundedRectangleArea(rounded.Size[0], rounded.Size[1], rounded.CornerRadius);
        var innerArea = RoundedRectangleArea(rounded.Size[0] - 2d * t, rounded.Size[1] - 2d * t, rounded.CornerRadius - t);
        var analytic = outerArea * rounded.Size[2] - innerArea * (rounded.Size[2] - t);
        var numerical = RoundedRectangleAreaNumerical(rounded.Size[0], rounded.Size[1], rounded.CornerRadius) * rounded.Size[2]
            - RoundedRectangleAreaNumerical(rounded.Size[0] - 2d * t, rounded.Size[1] - 2d * t, rounded.CornerRadius - t) * (rounded.Size[2] - t);
        return FormattableString.Invariant($"analytic={analytic:R};numericalSimpson={numerical:R};delta={double.Abs(analytic - numerical):R}");
    }

    private static string CylinderHollowVolume(FirmamentV2CylinderRecord cylinder, double t, double blendRadius)
    {
        var innerRadius = cylinder.Radius - t;
        var analytic = blendRadius == 0
            ? double.Pi * (cylinder.Radius * cylinder.Radius * cylinder.Height - innerRadius * innerRadius * (cylinder.Height - t))
            : BlendedCylinderVolume(cylinder.Radius, innerRadius, cylinder.Height, t, blendRadius);
        return FormattableString.Invariant($"analytic={analytic:R}");
    }

    private static double BlendedCylinderVolume(double outerRadius, double innerRadius, double height, double thickness, double blendRadius)
    {
        var major = outerRadius - blendRadius;
        static double QuarterProfileIntegral(double majorRadius, double minorRadius) =>
            majorRadius * majorRadius * minorRadius + majorRadius * double.Pi * minorRadius * minorRadius / 2d +
            2d * minorRadius * minorRadius * minorRadius / 3d;
        return double.Pi * (QuarterProfileIntegral(major, blendRadius) - QuarterProfileIntegral(major, blendRadius - thickness) +
            (outerRadius * outerRadius - innerRadius * innerRadius) * (height - blendRadius));
    }

    private static string FrustumHollowVolume(FirmamentV2FrustumRecord frustum, double t)
    {
        var k = (frustum.TopRadius - frustum.BottomRadius) / frustum.Height;
        var q = t * double.Sqrt(1d + k * k);
        var ib = frustum.BottomRadius + k * t - q; var it = frustum.TopRadius - q;
        var outer = double.Pi * frustum.Height * (frustum.BottomRadius * frustum.BottomRadius + frustum.BottomRadius * frustum.TopRadius + frustum.TopRadius * frustum.TopRadius) / 3d;
        var innerHeight = frustum.Height - t;
        var inner = double.Pi * innerHeight * (ib * ib + ib * it + it * it) / 3d;
        var analytic = outer - inner;
        var numerical = Simpson(0d, frustum.Height, z => double.Pi * double.Pow(frustum.BottomRadius + k * z, 2d))
            - Simpson(t, frustum.Height, z => double.Pi * double.Pow(frustum.BottomRadius + k * z - q, 2d));
        return FormattableString.Invariant($"analytic={analytic:R};numericalSimpson={numerical:R};delta={double.Abs(analytic - numerical):R}");
    }

    private static double RoundedRectangleArea(double width, double depth, double radius) => width * depth - (4d - double.Pi) * radius * radius;

    private static double RoundedRectangleAreaNumerical(double width, double depth, double radius)
    {
        // Parameterizing each quarter-circle by theta avoids the square-root endpoint singularity
        // of direct Cartesian sampling, while still providing an independent numerical integral.
        var straight = (width - 2d * radius) * depth;
        var cornerBands = 4d * radius * (depth / 2d - radius);
        var quarterCircleIntegral = Simpson(0d, double.Pi / 2d, theta => double.Cos(theta) * double.Cos(theta));
        return straight + cornerBands + 4d * radius * radius * quarterCircleIntegral;
    }

    private static double Simpson(double start, double end, Func<double, double> f)
    {
        const int segments = 16384; // even; deterministic numerical evidence, independent of closed-form volume.
        var step = (end - start) / segments; var sum = f(start) + f(end);
        for (var i = 1; i < segments; i++) sum += (i % 2 == 0 ? 2d : 4d) * f(start + i * step);
        return sum * step / 3d;
    }

    private static KernelResult<FirmamentStepExportResult> HollowFailure(string message) =>
        KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "FirmamentV2.Hollow")]);

    private static KernelResult<FirmamentStepExportResult>? TryExportV2RoundedBoxBody(FirmamentV2Document document)
    {
        if (document.Solids.Count != 1 || document.Solids[0].Primitive is not FirmamentV2RoundedBoxRecord rounded || rounded.Size.Count != 3)
            return null;
        var solid = document.Solids[0];
        var finishes = (document.ModifyBlocks ?? []).SelectMany(m => m.EdgeFinishes ?? []).ToArray();
        if (finishes.Length > 1) return RoundedBoxFailure("unsupported top/whole-body or mixed edge-finish request");
        double? fillet = null;
        if (finishes.Length == 1)
        {
            var finish = finishes[0];
            if (!string.Equals(finish.FaceAxis, "+Z", StringComparison.Ordinal) || !string.Equals(finish.Target, "Boundary", StringComparison.Ordinal) || !string.Equals(finish.Kind, "Fillet", StringComparison.Ordinal))
                return RoundedBoxFailure("UnsupportedSupportPair");
            fillet = finish.Distance;
        }
        var realization = RoundedBoxBRepPlanner.Create(rounded.Size[0], rounded.Size[1], rounded.Size[2], rounded.CornerRadius, fillet);
        if (!realization.IsSuccess || realization.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(realization.Diagnostics);
        var body = realization.Value.Body; var plan = realization.Value.Plan;
        if (!FirmamentManifoldChecker.IsManifold(body)) return RoundedBoxFailure("VerificationFailure: rounded-box body is not manifold");
        var step = Step242Exporter.ExportBody(body, new Step242ExportOptions
        {
            ProductName = solid.Name,
            ApplicationName = "AIR-ROUNDED-BOX-M6",
            BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
            BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
        });
        if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        var imported = Step242Importer.ImportBody(step.Value);
        if (!imported.IsSuccess || imported.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(imported.Diagnostics);
        if (!FirmamentManifoldChecker.IsManifold(imported.Value)) return RoundedBoxFailure("VerificationFailure: STEP reimport is not manifold");
        var surfaces = body.Geometry.Surfaces.Select(x => x.Value.Kind).ToArray();
        var preflight = BrepExportPreflight.Validate(body);
        var report = new FirmamentRoundedBoxReport(
            new("RoundedBoxFeature", "RoundedRectangleProfile -> LinearSweep", rounded.Size[0], rounded.Size[1], rounded.Size[2], rounded.CornerRadius,
                4, surfaces.Count(x => x == SurfaceGeometryKind.Cylinder) - (fillet is null ? 0 : 4), false),
            fillet is null ? null : new("TopBoundary", "Fillet", fillet.Value, 4, 4, rounded.CornerRadius - fillet.Value, fillet.Value,
                $"torus axis=+Z; center is each corner cylinder axis at z=top-{fillet.Value:R}; major=Rc-Rf={rounded.CornerRadius - fillet.Value:R}; minor=Rf={fillet.Value:R}; v=pi/2 is the top-plane trim and v=0 is the retained corner-cylinder trim."),
            new(plan.IsAuthoritative, plan.DeterministicSignature, plan.ExpectedVertexCount, plan.ExpectedEdgeCount, plan.ExpectedFaceCount, plan.ExpectedLoopCount, plan.ExpectedCoedgeCount, plan.FaceRoles),
            new(Bounds(body), true, surfaces.Count(x => x == SurfaceGeometryKind.Plane), surfaces.Count(x => x == SurfaceGeometryKind.Cylinder), surfaces.Count(x => x == SurfaceGeometryKind.Torus), RoundedBoxAnalyticVolume(rounded.Size[0], rounded.Size[1], rounded.Size[2], rounded.CornerRadius, fillet), preflight.IsValid ? "valid" : "invalid"),
            new(Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true, true, imported.Value.Topology.Faces.Count(), Bounds(imported.Value)));
        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, solid.Name, 0, "air-rounded-box", fillet is null ? "rounded-box-primitive" : "rounded-box-top-boundary-fillet", RoundedBox: report) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", finishes.Select(f => f.Name).ToArray()) });
    }

    private static KernelResult<FirmamentStepExportResult> RoundedBoxFailure(string message) =>
        KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "FirmamentV2.RoundedBox")]);

    // Exact volume of the admitted family.  Each straight finish removes a
    // square-minus-quarter-circle section; each corner is that section swept
    // through a quadrant about the corner-cylinder axis.
    private static double RoundedBoxAnalyticVolume(double width, double depth, double height, double cornerRadius, double? topFilletRadius)
    {
        var primitive = (width * depth - ((4d - double.Pi) * cornerRadius * cornerRadius)) * height;
        if (topFilletRadius is not double r) return primitive;
        var section = r * r * (1d - double.Pi / 4d);
        var straightRemoval = section * (2d * ((width - 2d * cornerRadius) + (depth - 2d * cornerRadius)));
        var cornerFirstMoment = r * r * r * (5d / 6d - double.Pi / 4d);
        var cornerRemoval = 2d * double.Pi * ((cornerRadius * section) - cornerFirstMoment);
        return primitive - straightRemoval - cornerRemoval;
    }

    private static KernelResult<FirmamentStepExportResult> ExportV2LocalizedTrihedralFillet(
        FirmamentV2Document document,
        FirmamentV2SolidBinding solid,
        IReadOnlyList<FirmamentV2EdgeFinishDecl> finishes,
        FirmamentV2BoxRecord box)
    {
        // The compiler owns canonical classification; source order carries no topology meaning.
        var xz = finishes.SingleOrDefault(f => string.Equals(f.FaceAxis, "+X", StringComparison.Ordinal) && string.Equals(f.Target, "SharedEdgePlusZ", StringComparison.Ordinal));
        var yz = finishes.SingleOrDefault(f => string.Equals(f.FaceAxis, "+Y", StringComparison.Ordinal) && string.Equals(f.Target, "SharedEdgePlusZ", StringComparison.Ordinal));
        var xy = finishes.SingleOrDefault(f => string.Equals(f.FaceAxis, "+X", StringComparison.Ordinal) && string.Equals(f.Target, "SharedEdgePlusY", StringComparison.Ordinal));
        if (xz is null || yz is null || xy is null)
            return AirChamferFailure("localized-trihedral-fillet-edges-do-not-share-canonical-vertex");
        var compiled = AirLocalizedTrihedralFilletCompiler.Compile(new(
            solid.Name, $"{solid.Name}.{xz.Name}.{yz.Name}.{xy.Name}", $"{xz.Name}+{yz.Name}+{xy.Name}", box.Size[0], box.Size[1], box.Size[2],
            xz.FaceAxis, xz.Target, yz.FaceAxis, yz.Target, xy.FaceAxis, xy.Target, xz.Distance, yz.Distance, xy.Distance,
            new AirSourceSpan(xz.SourceSpan.Start, xz.SourceSpan.Length + yz.SourceSpan.Length + xy.SourceSpan.Length, document.ModelName)));
        if (!compiled.Succeeded || compiled.Body is null || compiled.Construction is null || compiled.BRepPlan?.LocalizedEdgeJunctionRealizationPlan is null)
            return AirChamferFailure(compiled.Error?.Code ?? "localized-trihedral-fillet-spherical-octant-required", compiled.Diagnostics);

        var body = compiled.Body;
        var preflight = BrepExportPreflight.Validate(body);
        if (!preflight.IsValid) return AirChamferFailure("localized-trihedral-fillet-preflight-verification-failed", preflight.Diagnostics.Select(d => d.Code));
        if (!FirmamentManifoldChecker.IsManifold(body)) return AirChamferFailure("localized-trihedral-fillet-emitted-body-is-not-manifold");
        var step = Step242Exporter.ExportBody(body, new Step242ExportOptions
        {
            ProductName = compiled.Construction.ConstructionId,
            ApplicationName = AirLocalizedTrihedralFilletCompileResult.ProductionRoute,
            BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
            BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
        });
        if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        var reimport = Step242Importer.ImportBody(step.Value);
        if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value))
            return AirChamferFailure("localized-trihedral-fillet-step-reimport-verification-failed", reimport.Diagnostics.Select(d => d.Message));

        var topology = compiled.Construction.TopologyPlan;
        var cylinders = body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Cylinder);
        var spheres = body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Sphere);
        var planes = body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Plane);
        var report = new FirmamentAirChamferReport(
            new("Fillet", solid.Name, $"{solid.Name}.{xz.Name}.{yz.Name}.{xy.Name}", $"{xz.Name}+{yz.Name}+{xy.Name}", "SharedEdge(+X,+Z),SharedEdge(+Y,+Z),SharedEdge(+X,+Y)", xz.Distance, "mm",
                $"{xz.SourceSpan.Start}:{xz.SourceSpan.Length}|{yz.SourceSpan.Start}:{yz.SourceSpan.Length}|{xy.SourceSpan.Start}:{xy.SourceSpan.Length}", "Admitted", "localized-trihedral-fillet-spherical-octant-candidate",
                new Dictionary<string, string> { ["Selection"] = "semantic Face(+X),Face(+Z); Face(+Y),Face(+Z); Face(+X),Face(+Y)", ["MaterialSide"] = compiled.Construction.MaterialSide, ["SphereCenter"] = $"({compiled.Construction.SphericalCornerPatch.Center.X:R},{compiled.Construction.SphericalCornerPatch.Center.Y:R},{compiled.Construction.SphericalCornerPatch.Center.Z:R})", ["Continuity"] = "G0=Exact;G1=normal-deviation:0" }),
            new("LocalizedTrihedralFillet", 0, [], "ordered-explicit-loops", "SphereCylinderSharedSeams",
                "replacementFaces=3;junctionFaces=1;sharedEdges=3;patch=SphericalOctant;G0=Exact;G1=WithinTolerance", true),
            new(true, topology.ExpectedVertexCount, topology.ExpectedEdgeCount, topology.ExpectedFaceCount, topology.ExpectedLoopCount, topology.ExpectedCoedgeCount, 0,
                "SphereCylinderSharedSeams", topology.DeterministicSignature, "LocalizedEdgeJunction"),
            new(AirLocalizedTrihedralFilletCompileResult.ProductionRoute, false, true, body.Topology.Vertices.Count(), body.Topology.Edges.Count(), body.Topology.Faces.Count(), Bounds(body), xz.Distance, xz.Distance, cylinders, 0, planes, spheres),
            new("AP242", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true, reimport.Value.Topology.Vertices.Count(), reimport.Value.Topology.Edges.Count(), reimport.Value.Topology.Faces.Count(), Bounds(reimport.Value), true),
            LocalizedEdgeJunction: new(["SharedEdge(+X,+Z)", "SharedEdge(+Y,+Z)", "SharedEdge(+X,+Y)"], "Fillet", "EqualConstantRadius", xz.Distance, "Direct", "LocalizedTrihedralFillet", "SphericalOctant", 3, 1,
                new(true, topology.DeterministicSignature), "valid", false, 1, 1,
                new("SphericalOctant", "Sphere", "Cylinder", "Circle", true, 3, "+X,+Y,+Z octant")));
        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, $"{solid.Name}.{xz.Name}.{yz.Name}.{xy.Name}", 0, "air-fillet", "localized-trihedral-fillet", Air: report, ConceptIr: document.ConceptIr) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", finishes.Select(f => f.Name).ToArray()) });
    }

    private static KernelResult<FirmamentStepExportResult> ExportV2LocalizedTangentBlendSingleEdgeFillet(
        FirmamentV2Document document,
        FirmamentV2SolidBinding solid,
        FirmamentV2EdgeFinishDecl finish,
        FirmamentV2BoxRecord box)
    {
        var compiled = AirLocalizedTangentBlendFilletCompiler.Compile(new(
            solid.Name, $"{solid.Name}.{finish.Name}", finish.Name, box.Size[0], box.Size[1], box.Size[2],
            finish.FaceAxis, finish.Target switch { "SharedEdgePlusZ" => "+Z", "SharedEdgePlusY" => "+Y", _ => finish.Target }, finish.Kind, finish.Distance,
            new AirSourceSpan(finish.SourceSpan.Start, finish.SourceSpan.Length, document.ModelName)));
        if (!compiled.Succeeded || compiled.Body is null || compiled.Construction is null || compiled.BRepPlan?.LocalizedEdgeReplacementRealizationPlan is null)
            return AirChamferFailure(compiled.Error?.Code ?? compiled.Feature.AdmissionReason, compiled.Diagnostics);

        // AIR builds centered kernel stock; publish in the same bottom-anchored frame as the authored Box.
        var body = FirmamentPrimitiveExecutionTranslation.TranslateBody(compiled.Body,
            new Vector3D(0, 0, FirmamentStockFrame.ForBox(box.Size[0], box.Size[1], box.Size[2]).KernelCenteredToStockZ));
        var preflight = BrepExportPreflight.Validate(body);
        if (!preflight.IsValid) return AirChamferFailure("localized-fillet-preflight-verification-failed", preflight.Diagnostics.Select(d => d.Code));
        if (!FirmamentManifoldChecker.IsManifold(body)) return AirChamferFailure("localized-fillet-emitted-body-is-not-manifold");
        var step = Step242Exporter.ExportBody(body, new Step242ExportOptions
        {
            ProductName = compiled.Feature.FeatureName,
            ApplicationName = AirLocalizedTangentBlendFilletCompileResult.ProductionRoute,
            BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
            BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
        });
        if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        var reimport = Step242Importer.ImportBody(step.Value);
        if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value))
            return AirChamferFailure("localized-fillet-step-reimport-verification-failed");

        var plan = compiled.Construction.TopologyPlan;
        var witness = compiled.Construction.Witness;
        var cylinders = body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Cylinder);
        var planes = body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Plane);
        var report = new FirmamentAirChamferReport(
            new("Fillet", compiled.Feature.BodyId, compiled.Feature.FeatureId, compiled.Feature.FeatureName, "SharedEdge(+X,+Z)", finish.Distance, "mm",
                $"{compiled.Feature.SourceSpan.Start}:{compiled.Feature.SourceSpan.Length}", compiled.Feature.Admission.ToString(), compiled.Feature.AdmissionReason,
                new Dictionary<string, string> { ["Selection"] = "semantic Face(+X),Face(+Z)", ["MaterialSide"] = witness.MaterialSide, ["History"] = witness.Provenance }),
            new("LocalizedTangentBlend", 0, [], "ordered-explicit-loops", "ExplicitOwnedEndpoints",
                $"profile=QuarterCircle;sweep=Linear;radius={witness.Radius:R};axis=+Y;retainedFaces=2;replacementFaces=1", true),
            new(true, plan.ExpectedVertexCount, plan.ExpectedEdgeCount, plan.ExpectedFaceCount, plan.ExpectedLoopCount, plan.ExpectedCoedgeCount, 0,
                "ExplicitOwnedEndpoints", plan.DeterministicSignature, "LocalizedTangentBlend"),
            new(AirLocalizedTangentBlendFilletCompileResult.ProductionRoute, false, true, body.Topology.Vertices.Count(), body.Topology.Edges.Count(), body.Topology.Faces.Count(), Bounds(body), finish.Distance, finish.Distance, cylinders, 0, planes),
            new("AP242", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true, reimport.Value.Topology.Vertices.Count(), reimport.Value.Topology.Edges.Count(), reimport.Value.Topology.Faces.Count(), Bounds(reimport.Value), true),
            LocalizedFillet: new("SharedEdge(+X,+Z)", "ConstantRadius", finish.Distance, "LocalizedTangentBlend", "QuarterCircle", "Linear", "Direct", 2, 1, "ExplicitOwnedEndpoints", new(true, plan.DeterministicSignature), "valid", false),
            LocalizedEdgeFinish: new("Fillet", "SharedEdge(+X,+Z)", "ConstantRadius", finish.Distance, "LocalizedEdgeReplacement", "CylindricalFillet", "Direct", 2, 1, "ExplicitOwnedEndpoints", new(true, plan.DeterministicSignature), "valid", false));
        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, compiled.Feature.FeatureId, 0, "air-fillet", "localized-tangent-blend-single-edge-fillet", Air: report, ConceptIr: document.ConceptIr) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", finish.Name) });
    }

    private static KernelResult<FirmamentStepExportResult> ExportV2CircularRimChamfer(
        FirmamentV2Document document,
        FirmamentV2SolidBinding solid,
        FirmamentV2EdgeFinishDecl finish,
        FirmamentV2CylinderRecord cylinder)
    {
        var compiled = AirCylinderTopRimChamferCompiler.Compile(new(
            solid.Name,
            $"{solid.Name}.{finish.Name}",
            finish.Name,
            cylinder.Radius,
            cylinder.Height,
            finish.FaceAxis,
            finish.Target,
            finish.Kind,
            finish.Distance,
            new AirSourceSpan(finish.SourceSpan.Start, finish.SourceSpan.Length, document.ModelName)));
        if (!compiled.Succeeded || compiled.Body is null || compiled.Construction is null || compiled.BRepPlan?.RevolvedRealizationPlan is null)
            return AirChamferFailure(compiled.Error?.Code ?? compiled.Feature.AdmissionReason, compiled.Diagnostics);

        var manifold = FirmamentManifoldChecker.IsManifold(compiled.Body);
        if (!manifold) return AirChamferFailure("chamfer-backend-circular-rim-body-is-not-manifold", compiled.Diagnostics);
        var step = Step242Exporter.ExportBody(compiled.Body, new Step242ExportOptions
        {
            ProductName = compiled.Feature.FeatureName,
            ApplicationName = AirCylinderTopRimChamferCompileResult.ProductionRoute,
            BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
            BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
        });
        if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        var reimport = Step242Importer.ImportBody(step.Value);
        if (!reimport.IsSuccess || reimport.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(reimport.Diagnostics);
        var reimportedManifold = FirmamentManifoldChecker.IsManifold(reimport.Value);
        if (!reimportedManifold) return AirChamferFailure("chamfer-verification-circular-rim-step-reimport-is-not-manifold");

        var topology = compiled.Construction.TopologyPlan;
        var surfaces = compiled.Body.Geometry.Surfaces.Select(s => s.Value.Kind).ToArray();
        var sharp = compiled.Construction.Witness.SharpProfile.Select(p => (IReadOnlyList<double>)new[] { p.X, p.Y }).ToArray();
        var replacement = compiled.Construction.Witness.ReplacementProfile.Select(p => (IReadOnlyList<double>)new[] { p.X, p.Y }).ToArray();
        var featureProvenance = new Dictionary<string, string>(StringComparer.Ordinal);
        if (solid.Provenance?.TryGetValue("Bounds", out var boundsProvenance) == true) featureProvenance["Bounds"] = boundsProvenance;
        if (finish.Provenance?.TryGetValue("Face", out var faceProvenance) == true) featureProvenance["Selection"] = faceProvenance;
        if (finish.Provenance?.TryGetValue("Distance", out var distanceProvenance) == true) featureProvenance["Distance"] = distanceProvenance;
        var report = new FirmamentAirChamferReport(
            new("Chamfer", compiled.Feature.BodyId, compiled.Feature.FeatureId, compiled.Feature.FeatureName, "FaceBoundary(+Z,circular,outer,complete)", compiled.Feature.Rule.Distance, compiled.Feature.Rule.Unit,
                $"{compiled.Feature.SourceSpan.Start}:{compiled.Feature.SourceSpan.Length}", compiled.Feature.Admission.ToString(), compiled.Feature.AdmissionReason, featureProvenance),
            new("RevolutionProfileRewrite", 0, [], "ordered-radial-profile", "preserve-profile-corners",
                $"axis={compiled.Construction.Witness.Axis};materialSide={compiled.Construction.Witness.MaterialSide}", compiled.Construction.Witness.CompilerGenerated, sharp, replacement),
            new(true, topology.ExpectedVertexCount, topology.ExpectedEdgeCount, topology.ExpectedFaceCount, topology.ExpectedLoopCount, topology.ExpectedCoedgeCount, 1,
                "preserve-profile-corners", topology.DeterministicSignature, "RevolvedProfile"),
            new(AirCylinderTopRimChamferCompileResult.ProductionRoute, false, manifold,
                compiled.Body.Topology.Vertices.Count(), compiled.Body.Topology.Edges.Count(), compiled.Body.Topology.Faces.Count(), CircularBounds(cylinder.Radius, cylinder.Height), finish.Distance, finish.Distance,
                surfaces.Count(k => k == SurfaceGeometryKind.Cylinder), surfaces.Count(k => k == SurfaceGeometryKind.Cone), surfaces.Count(k => k == SurfaceGeometryKind.Plane)),
            new("AP242", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true,
                reimport.Value.Topology.Vertices.Count(), reimport.Value.Topology.Edges.Count(), reimport.Value.Topology.Faces.Count(), CircularBounds(cylinder.Radius, cylinder.Height), reimportedManifold));
        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(
            step.Value, compiled.Feature.FeatureId, 0, "air-chamfer", "circular-top-rim-chamfer", Air: report, ConceptIr: document.ConceptIr) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", finish.Name) });
    }

    private static string CircularBounds(double radius, double height) =>
        FormattableString.Invariant($"[{-radius:0.###},{-radius:0.###},{-height / 2d:0.###}]..[{radius:0.###},{radius:0.###},{height / 2d:0.###}]");

    private static string Bounds(BrepBody body)
    {
        var points = body.Topology.Vertices.Select(v => body.TryGetVertexPoint(v.Id, out var point) ? point : throw new InvalidOperationException($"Missing point for vertex {v.Id}.")).ToArray();
        return FormattableString.Invariant($"[{points.Min(p => p.X):0.###},{points.Min(p => p.Y):0.###},{points.Min(p => p.Z):0.###}]..[{points.Max(p => p.X):0.###},{points.Max(p => p.Y):0.###},{points.Max(p => p.Z):0.###}]");
    }

    private static KernelResult<FirmamentStepExportResult> AirChamferFailure(string primary, IEnumerable<string>? details = null) =>
        KernelResult<FirmamentStepExportResult>.Failure((new[] { primary }).Concat(details ?? []).Distinct().Select(message => new Kernel.Core.Diagnostics.KernelDiagnostic(
            Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
            Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,
            message,
            "FirmamentV2.AirChamfer")).ToArray());

    private static KernelResult<FirmamentStepExportResult>? TryExportV2InlineStepReplacementBody(FirmamentV2Document document)
    {
        if (document.Replacements is { Count: > 1 })
            return KernelResult<FirmamentStepExportResult>.Failure([new(KernelDiagnosticCode.ValidationFailed,KernelDiagnosticSeverity.Error,
                "firmament-imported-hole-count-unsupported: One imported hole revision per Model is admitted.","FirmamentV2.ImportedHoleRevision")]);
        if (document.Replacements is not { Count: 1 } replacements || document.Solids.Count != 1)
        {
            return null;
        }

        var replacement = replacements[0];
        var solid = document.Solids.SingleOrDefault(s => string.Equals(s.Name, replacement.ImportedBodyName, StringComparison.Ordinal));
        if (solid?.InlineStep is null || replacement.ReplacementKind != "holeShaft" || replacement.EndCondition != "throughAll")
        {
            return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, FirmamentV2Parser.ReplacementVerificationFailed, "FirmamentV2.InlineStepReplacement")]);
        }

        var stepText = solid.InlineStep.SourceText ?? File.ReadAllText(solid.InlineStep.NormalizedPath, Encoding.UTF8);
        if (replacement.Within is not null) return ExportImportedHoleRevision(document, solid, replacement);
        var import = Step242Importer.ImportBody(stepText);
        if (!import.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(import.Diagnostics);

        var cylFaceCount = import.Value.Geometry.Surfaces.Count(entry => entry.Value.Kind == SurfaceGeometryKind.Cylinder && Math.Abs((entry.Value.Cylinder?.Radius ?? 0d) - replacement.Radius) <= 1e-6);
        if (cylFaceCount != 1)
        {
            return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, FirmamentV2Parser.ReplacementVerificationFailed, "FirmamentV2.InlineStepReplacement")]);
        }

        var size = replacement.HostSize;
        var syntheticDocument = new FirmamentV2Document(
            document.ModelName,
            document.Units,
            [new FirmamentV2SolidBinding("replacementHost", "Box", new FirmamentV2BoxRecord(size, []))],
            [new FirmamentV2ModifyBlock("replacementHost", [], [new FirmamentV2SemanticHoleDecl(replacement.ReplacementFeatureName, FirmamentV2SemanticHoleVariant.Shaft, FirmamentV2FaceTarget.Direct("+Z"), replacement.Center with { Convention = FirmamentV2FaceLocalPoint2D.PlusZConvention }, replacement.Radius * 2d, new FirmamentV2SemanticHoleEnd(FirmamentV2SemanticHoleEndKind.ThroughAll))])],
            [],
            document.Pmi,
            document.RecognizedRegions,
            document.Replacements);

        var semanticHoles = FirmamentV2SemanticHoleLowering.LowerSemanticHoles(syntheticDocument);
        var feature = semanticHoles[0];
        var host = FirmamentStockFrame.ForBox(size[0], size[1], size[2]).CreateHoleHost();
        var materialized = AirHoleSimpleShaftMaterializer.Execute(feature, host);
        if (!materialized.Succeeded || materialized.Body is null) return SemanticHoleFailure(materialized.Diagnostics);

        var expectedVolume = size[0] * size[1] * size[2] - Math.PI * replacement.Radius * replacement.Radius * size[2];
        var rebuiltVolume = EstimateBoundingBoxVolume(materialized.Body) - Math.PI * replacement.Radius * replacement.Radius * size[2];
        if (Math.Abs(expectedVolume - rebuiltVolume) > 1e-6)
        {
            return KernelResult<FirmamentStepExportResult>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, FirmamentV2Parser.ReplacementVerificationFailed, "FirmamentV2.InlineStepReplacement")]);
        }

        var step = Step242Exporter.ExportBody(materialized.Body, new Step242ExportOptions { ProductName = replacement.ReplacementFeatureName, ApplicationName = "Aetheris.Firmament.InlineStepReplacement" });
        if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);

        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, replacement.ReplacementFeatureName, 0, "inline-step-replacement", "holeShaft-bounded-rebuild", DatumInspection: [], DimensionInspection: [], InlineStepMigration: InlineStepMigrationReportBuilder.Build(document, solid, replacementsVerified: true, replacementsEmitted: true, emissionStrategy: "holeShaft-bounded-rebuild", residualSurgery: false),
                InlineStepReplacementAssist: InlineStepReplacementAssistReportBuilder.Build(document)));
    }

    private static double EstimateBoundingBoxVolume(BrepBody body)
    {
        var points = body.Topology.Vertices.Select(v => body.TryGetVertexPoint(v.Id, out var p) ? p : new Point3D(0, 0, 0)).ToArray();
        return (points.Max(p => p.X) - points.Min(p => p.X)) * (points.Max(p => p.Y) - points.Min(p => p.Y)) * (points.Max(p => p.Z) - points.Min(p => p.Z));
    }

    private static KernelResult<FirmamentStepExportResult>? TryExportV2InlineStepBody(FirmamentV2Document document)
    {
        if (document.Solids.Count != 1)
        {
            return null;
        }

        var solid = document.Solids[0];
        if (solid.Primitive is not FirmamentV2InlineStepRecord inlineStep)
        {
            return null;
        }

        var stepText = inlineStep.SourceText ?? File.ReadAllText(inlineStep.NormalizedPath, Encoding.UTF8);
        var import = inlineStep.RuntimeBody is { } admitted ? KernelResult<BrepBody>.Success(admitted.Clone())
            : Step242Importer.ImportBody(stepText, new Aetheris.Kernel.Core.Import.ImportPolicy(PreferredLane: Aetheris.Kernel.Core.Import.ImportLaneKind.ExactBRep));
        if (!import.IsSuccess)
        {
            return KernelResult<FirmamentStepExportResult>.Failure(import.Diagnostics);
        }

        // A source pin proves identity, not complete UV reconstruction. Unchanged
        // annotation/re-export is admitted by strict output preflight below.
        // Topology edits retain their operation-specific qualified-trim guards.
        var semanticPmiValidation = ValidateV2PmiExportSupport(document);
        if (!semanticPmiValidation.IsSuccess)
        {
            return KernelResult<FirmamentStepExportResult>.Failure(semanticPmiValidation.Diagnostics);
        }

        var semanticPmi = BuildV2SemanticPmi(document, [], solid.Name, body: import.Value);
        Step242PmiTransfer? importedPmi = null;
        if (!inlineStep.GeometryOnly && ImportedStepSemantics.HasAnnotations(stepText))
        {
            var original = Step242SemanticPmiInspector.Inspect(stepText);
            var declared = (document.Pmi ?? []).Select(p => p.Name).ToHashSet(StringComparer.Ordinal);
            if (original.Items.Any(item => declared.Contains(item.AuthoredName ?? item.Name)))
                return KernelResult<FirmamentStepExportResult>.Failure([new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,
                    "firmament-v2-pmi-source-name-conflict: Authored PMI names must be distinct from retained source annotation names.", "FirmamentV2.Pmi")]);
            var transfer = Step242PmiTransfer.Read(stepText, import.Value);
            if (!transfer.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(transfer.Diagnostics);
            importedPmi = transfer.Value;
        }
        var targetValidation = ValidateImportedPmiTargets(semanticPmi, import.Value);
        if (!targetValidation.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(targetValidation.Diagnostics);
        var export = Step242Exporter.ExportBody(import.Value, semanticPmi, new Step242ExportOptions
        {
            ProductName = solid.Name,
            ApplicationName = "Aetheris.Firmament.InlineStep",
            ImportedPmi = importedPmi,
            BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
            BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
            ImportedRecoveryToleranceMillimetres = double.Min(.1, inlineStep.ImportToleranceMillimetres ?? .001)
        });
        if (!export.IsSuccess)
        {
            return KernelResult<FirmamentStepExportResult>.Failure(export.Diagnostics);
        }

        return KernelResult<FirmamentStepExportResult>.Success(
            new FirmamentStepExportResult(
                export.Value,
                solid.Name,
                0,
                "inline-step",
                inlineStep.CanonicalInput ? "aetheris-canonical-ap242" : "qualified-import-ap242",
                DatumInspection: document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.DatumPlane).Select(p => new FirmamentPmiInspectionDatum(p.Name, "planar", p.Target)).ToArray() ?? [],
                DimensionInspection: document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.HoleDiameter).Select(p => new FirmamentPmiInspectionDimension("Diameter", p.Target, null, p.Value ?? 0d, "explicit-v2-record-pmi", p.Name)).ToArray() ?? [],
                InlineStepMigration: InlineStepMigrationReportBuilder.Build(document, solid, emissionStrategy: inlineStep.CanonicalInput ? "canonical-reexport" : "strict-import-reexport", residualSurgery: false),
                InlineStepReplacementAssist: InlineStepReplacementAssistReportBuilder.Build(document))
                { RuntimeBody = import.Value, RuntimeBodySourceName = solid.Name, RuntimeAdmissionDocument = document },
            export.Diagnostics.Concat(inlineStep.GeometryOnly ? [new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Warning,
                "firmament-inline-step-source-semantics-excluded: geometryOnly explicitly excludes source annotations; geometry remains unchanged.", "FirmamentV2.InlineStep")] : []).ToArray());
    }

    private static KernelResult<FirmamentStepExportResult>? TryExportV2ControlledSideHoleBody(FirmamentV2Document document)
    {
        if ((document.ModifyBlocks ?? []).Any(m => (m.EdgeFinishes?.Count ?? 0) > 0)) return null;
        var intent = document.SideHoleIntent;
        if (intent is null)
        {
            return null;
        }

        if (document.ModifyBlocks is not { Count: 1 }
            || document.ModifyBlocks[0].Regions.Count != 1
            || document.ModifyBlocks[0].SemanticHoles.Count != 0)
        {
            return null;
        }

        if (!string.Equals(intent.Tool, "Cylinder", StringComparison.Ordinal)
            || !string.Equals(intent.AttachFace, "+X", StringComparison.Ordinal)
            || !string.Equals(intent.ThroughFace, "-X", StringComparison.Ordinal))
        {
            return null;
        }

        var targetSolid = document.Solids.SingleOrDefault(s => string.Equals(s.Name, intent.TargetSolid, StringComparison.Ordinal));
        if (targetSolid?.Primitive is not FirmamentV2BoxRecord box || box.Size.Count != 3)
        {
            return null;
        }

        var sizeX = box.Size[0];
        var sizeY = box.Size[1];
        var sizeZ = box.Size[2];
        var zAxis = Direction3D.Create(new Vector3D(0, 0, 1));
        var xAxis = Direction3D.Create(new Vector3D(1, 0, 0));
        var extents = new AxisAlignedBoxExtents(-sizeY / 2d, sizeY / 2d, -sizeZ / 2d, sizeZ / 2d, -sizeX / 2d, sizeX / 2d);
        var cylinder = new RecognizedCylinder(new Point3D(intent.CenterU, intent.CenterV, 0), zAxis, intent.Radius, -sizeX / 2d, sizeX / 2d);
        var hole = new SupportedBooleanHole(
            intent.RegionName,
            new AnalyticSurface(AnalyticSurfaceKind.Cylinder, Cylinder: cylinder),
            intent.CenterU,
            intent.CenterV,
            new Point3D(intent.CenterU, intent.CenterV, -sizeX / 2d),
            new Point3D(intent.CenterU, intent.CenterV, sizeX / 2d),
            zAxis,
            xAxis,
            intent.Radius,
            intent.Radius,
            SupportedBooleanHoleSpanKind.Through,
            -sizeX / 2d,
            sizeX / 2d);
        var composition = new SafeBooleanComposition(extents, [hole], SafeBooleanRootDescriptor.FromBox(extents));
        var built = BrepBooleanBoxCylinderHoleBuilder.BuildComposition(composition, ToleranceContext.Default);
        if (!built.IsSuccess || built.Value is null)
        {
            return KernelResult<FirmamentStepExportResult>.Failure(built.Diagnostics);
        }

        var body = ReorientCanonicalSideHoleBodyFromZToX(built.Value);
        var step = Step242Exporter.ExportBody(body, new Step242ExportOptions { ProductName = "firmament-v2-controlled-side-hole" });
        if (!step.IsSuccess)
        {
            return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        }

        return KernelResult<FirmamentStepExportResult>.Success(
            new FirmamentStepExportResult(
                step.Value,
                intent.RegionName,
                0,
                "boolean",
                "side-hole-controlled-x",
                DatumInspection: [],
                DimensionInspection: []) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(intent.TargetSolid, "Region", intent.RegionName) });
    }

    private static BrepBody ReorientCanonicalSideHoleBodyFromZToX(BrepBody body)
    {
        static Point3D P(Point3D p) => new(p.Z, p.X, p.Y);
        static Direction3D D(Direction3D d)
        {
            var v = d.ToVector();
            return Direction3D.Create(new Vector3D(v.Z, v.X, v.Y));
        }

        var geometry = new BrepGeometryStore();
        foreach (var entry in body.Geometry.Curves)
        {
            geometry.AddCurve(entry.Key, entry.Value.Kind switch
            {
                CurveGeometryKind.Line3 => CurveGeometry.FromLine(new Line3Curve(P(entry.Value.Line3!.Value.Origin), D(entry.Value.Line3.Value.Direction))),
                CurveGeometryKind.Circle3 => CurveGeometry.FromCircle(new Circle3Curve(P(entry.Value.Circle3!.Value.Center), D(entry.Value.Circle3.Value.Normal), entry.Value.Circle3.Value.Radius, D(entry.Value.Circle3.Value.XAxis))),
                CurveGeometryKind.Ellipse3 => CurveGeometry.FromEllipse(new Ellipse3Curve(P(entry.Value.Ellipse3!.Value.Center), D(entry.Value.Ellipse3.Value.Normal), entry.Value.Ellipse3.Value.MajorRadius, entry.Value.Ellipse3.Value.MinorRadius, D(entry.Value.Ellipse3.Value.XAxis))),
                _ => entry.Value
            });
        }

        foreach (var entry in body.Geometry.Surfaces)
        {
            geometry.AddSurface(entry.Key, entry.Value.Kind switch
            {
                SurfaceGeometryKind.Plane => SurfaceGeometry.FromPlane(new PlaneSurface(P(entry.Value.Plane!.Value.Origin), D(entry.Value.Plane.Value.Normal), D(entry.Value.Plane.Value.UAxis))),
                SurfaceGeometryKind.Cylinder => SurfaceGeometry.FromCylinder(new CylinderSurface(P(entry.Value.Cylinder!.Value.Origin), D(entry.Value.Cylinder.Value.Axis), entry.Value.Cylinder.Value.Radius, D(entry.Value.Cylinder.Value.XAxis))),
                _ => entry.Value
            });
        }

        var vertexPoints = new Dictionary<VertexId, Point3D>();
        foreach (var vertex in body.Topology.Vertices)
        {
            if (body.TryGetVertexPoint(vertex.Id, out var point))
            {
                vertexPoints[vertex.Id] = P(point);
            }
        }

        return new BrepBody(body.Topology, geometry, body.Bindings, vertexPoints, safeBooleanComposition: null, body.ShellRepresentation);
    }

    private static KernelResult<FirmamentStepExportResult>? TryExportV2PerforationBody(FirmamentV2Document document)
    {
        var features = (document.ModifyBlocks ?? []).SelectMany(block => (block.Perforations ?? []).Select(feature => (block.TargetSolid, Feature: feature))).ToArray();
        if (features.Length == 0) return null;
        KernelResult<FirmamentStepExportResult> Failure(string diagnostic) =>
            KernelResult<FirmamentStepExportResult>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, diagnostic, "FirmamentV2.Perforation")]);
        if (features.Length != 1 || document.Solids.Count != 1 || document.ModifyBlocks!.Any(block => block.SemanticHoles.Count > 0 || (block.EdgeFinishes?.Count ?? 0) > 0))
            return Failure("perforation-composition-unsupported: X0 admits one Perforation on one Box without other Modify features");
        var (target, feature) = features[0];
        if (document.Solid.Name == target && document.Solid.ConstructionPolicy == FirmamentV2ConstructionPolicy.Hollow &&
            document.Solid.Cylinder is { } cylinder && document.Solid.Hollow is { } hollow)
        {
            var cylindrical = FirmamentCylindricalPerforationPlanner.Plan(cylinder.Radius, cylinder.Height,
                hollow.WallThickness, feature);
            if (!cylindrical.Succeeded) return Failure(cylindrical.Diagnostic!);
            var patternBuildStart = Stopwatch.GetTimestamp();
            var hollowBody = ThinWalledBodyBRepPlanner.CreateCylinder(cylinder.Radius, cylinder.Height, hollow.WallThickness, hollow.BottomBlendRadius);
            if (!hollowBody.IsSuccess || hollowBody.Value is null)
                return Failure("perforation-cylindrical-host-invalid: " + string.Join(" | ", hollowBody.Diagnostics.Select(d => d.Message)));
            var cylindricalFeatureId = $"{target}.{feature.Name}";
            var placements = cylindrical.Instances.Select(instance => new HollowRadialCutPlacement(
                instance.StableId(cylindricalFeatureId), feature.Diameter / 2, instance.Z, instance.AngleRadians)).ToArray();
            var cut = BrepHollowRadialCutPattern.Build(hollowBody.Value, placements);
            if (!cut.IsSuccess || cut.Value is null)
                return Failure("perforation-cylindrical-brep-failed: " + string.Join(" | ", cut.Diagnostics.Select(d => $"{d.Source}: {d.Message}")));
            var patternBuildMilliseconds = Stopwatch.GetElapsedTime(patternBuildStart).TotalMilliseconds;
            var cylindricalBody = cut.Value.Body;
            if (!FirmamentManifoldChecker.IsManifold(cylindricalBody))
                return Failure("perforation-cylindrical-topology-invalid: the composed shell is not manifold");
            var stepExportStart = Stopwatch.GetTimestamp();
            var cylindricalStep = Step242Exporter.ExportBody(cylindricalBody, new Step242ExportOptions
            {
                ProductName = cylindricalFeatureId,
                ApplicationName = "Aetheris.Firmament.Perforation.Cylindrical",
                BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
                BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
            });
            if (!cylindricalStep.IsSuccess || cylindricalStep.Value is null)
                return Failure("perforation-cylindrical-step-export-failed: " + string.Join(" | ", cylindricalStep.Diagnostics.Select(d => d.Message)));
            var stepExportMilliseconds = Stopwatch.GetElapsedTime(stepExportStart).TotalMilliseconds;
            // The reimport proves that the STEP text faithfully encodes the body validated above. Openings of a
            // pattern are congruent (one realization moved rigidly) and proven disjoint at compile time, so a
            // one- and a two-opening specimen prove the encoding of an opening, alone and sharing host faces; the
            // full file must then hold exactly the entities N congruent openings add. Re-importing every opening
            // would re-prove the same opening N times.
            string? Verify(string stepText, int openings)
            {
                var imported = Step242Importer.ImportBody(stepText);
                if (!imported.IsSuccess || imported.Value is null || !FirmamentManifoldChecker.IsManifold(imported.Value))
                    return "perforation-cylindrical-step-reimport-invalid: " + string.Join(" | ", imported.Diagnostics.Select(d => d.Message));
                var importedCylinders = imported.Value.Geometry.Surfaces
                    .Where(pair => pair.Value.Kind == SurfaceGeometryKind.Cylinder)
                    .Select(pair => pair.Value.Cylinder!.Value.Radius).ToArray();
                var importedPlanes = imported.Value.Geometry.Surfaces
                    .Where(pair => pair.Value.Kind == SurfaceGeometryKind.Plane)
                    .Select(pair => pair.Value.Plane!.Value.Origin.Z).ToArray();
                var importedTori = imported.Value.Geometry.Surfaces
                    .Where(pair => pair.Value.Kind == SurfaceGeometryKind.Torus)
                    .Select(pair => pair.Value.Torus!.Value).ToArray();
                if (imported.Value.Topology.Faces.Count() != openings + (hollow.BottomBlendRadius > 0 ? 7 : 5) ||
                    importedCylinders.Length != openings + 2 ||
                    importedPlanes.Length != 3 ||
                    importedTori.Length != (hollow.BottomBlendRadius > 0 ? 2 : 0) ||
                    (hollow.BottomBlendRadius > 0 &&
                     (importedTori.Any(torus => System.Math.Abs(torus.MajorRadius - (cylinder.Radius - hollow.BottomBlendRadius)) > 1e-6) ||
                      !importedTori.Any(torus => System.Math.Abs(torus.MinorRadius - hollow.BottomBlendRadius) < 1e-6) ||
                      !importedTori.Any(torus => System.Math.Abs(torus.MinorRadius - (hollow.BottomBlendRadius - hollow.WallThickness)) < 1e-6))) ||
                    !new[] { 0d, hollow.WallThickness, cylinder.Height }.All(z => importedPlanes.Any(p => System.Math.Abs(p - z) < 1e-6)) ||
                    importedCylinders.Count(r => System.Math.Abs(r - feature.Diameter / 2) < 1e-6) != openings ||
                    importedCylinders.Count(r => System.Math.Abs(r - cylinder.Radius) < 1e-6) != 1 ||
                    importedCylinders.Count(r => System.Math.Abs(r - (cylinder.Radius - hollow.WallThickness)) < 1e-6) != 1)
                    return "perforation-cylindrical-step-reimport-invalid: opening count or analytic radii changed";
                return null;
            }
            var stepReimportStart = Stopwatch.GetTimestamp();
            string verificationBasis;
            if (placements.Length <= 2)
            {
                if (Verify(cylindricalStep.Value, placements.Length) is { } reimportFailure) return Failure(reimportFailure);
                verificationBasis = "full-reimport";
            }
            else
            {
                var specimenCounts = new List<IReadOnlyDictionary<string, int>>();
                foreach (var openings in new[] { 1, 2 })
                {
                    var specimen = BrepHollowRadialCutPattern.Build(hollowBody.Value, placements[..openings]);
                    var specimenStep = specimen.IsSuccess && specimen.Value is not null
                        ? Step242Exporter.ExportBody(specimen.Value.Body, new Step242ExportOptions
                        {
                            ProductName = cylindricalFeatureId, ApplicationName = "Aetheris.Firmament.Perforation.Cylindrical",
                            BrepExportPreflightMode = BrepExportPreflightMode.Enforce, BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
                        })
                        : null;
                    if (specimenStep is not { IsSuccess: true, Value: { } specimenText })
                        return Failure($"perforation-cylindrical-specimen-invalid: the {openings}-opening specimen did not build and export");
                    if (Verify(specimenText, openings) is { } specimenFailure) return Failure(specimenFailure);
                    specimenCounts.Add(Step242EntityCensus.Count(specimenText));
                }
                var full = Step242EntityCensus.Count(cylindricalStep.Value);
                if (Step242EntityCensus.LinearMismatch(specimenCounts[0], specimenCounts[1], full, placements.Length) is { } mismatch)
                    return Failure($"perforation-cylindrical-step-congruence-invalid: {mismatch}");
                verificationBasis = "congruent-specimens";
            }
            var stepReimportMilliseconds = Stopwatch.GetElapsedTime(stepReimportStart).TotalMilliseconds;
            var cylindricalDescendants = placements.SelectMany(placement => new[]
            {
                new SemanticTopologyDescendant($"material:perforation:{placement.StableId}:wall", "Face", SemanticTopologyRole.HoleWallFace,
                    $"perforation:{placement.StableId}", Face: cut.Value.TopologyMap.Faces[$"{placement.StableId}.Wall"],
                    ParentStableId: cylindricalFeatureId, Addressability: SemanticTopologyAddressability.DerivedStable),
                new SemanticTopologyDescendant($"material:perforation:{placement.StableId}:outer-opening", "Loop", SemanticTopologyRole.HoleEntryLoop,
                    $"perforation:{placement.StableId}", Loop: cut.Value.TopologyMap.Loops[$"{placement.StableId}.OuterOpening"],
                    ParentStableId: cylindricalFeatureId, Addressability: SemanticTopologyAddressability.DerivedStable),
                new SemanticTopologyDescendant($"material:perforation:{placement.StableId}:inner-opening", "Loop", SemanticTopologyRole.HoleExitLoop,
                    $"perforation:{placement.StableId}", Loop: cut.Value.TopologyMap.Loops[$"{placement.StableId}.InnerOpening"],
                    ParentStableId: cylindricalFeatureId, Addressability: SemanticTopologyAddressability.DerivedStable),
            }).ToArray();
            var cylindricalCorrespondence = new SemanticTopologyCorrespondence(cylindricalFeatureId, cylindricalDescendants,
                ["Perforation", "BrepHollowRadialCutPattern"])
            {
                SourceSpans = new Dictionary<string, FirmamentV2SourceSpan> { [cylindricalFeatureId] = feature.SourceSpan }
            };
            var cylindricalHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(cylindricalStep.Value)));
            var realizedPitch = 2 * System.Math.PI * (cylinder.Radius - hollow.WallThickness / 2) / cylindrical.Columns;
            var cylindricalReport = new FirmamentPerforationReport(cylindricalFeatureId, feature.SupportFace, feature.Layout,
                feature.Diameter, feature.Pitch, feature.Margin, feature.MinimumLigament, placements.Length,
                placements.Select(p => p.StableId).ToArray(), cylindricalBody.Topology.Vertices.Count(),
                cylindricalBody.Topology.Edges.Count(), cylindricalBody.Topology.Faces.Count(), true, true, cylindricalHash)
            {
                Rows = cylindrical.Rows, Columns = cylindrical.Columns,
                AngularPitchRadians = cylindrical.AngularPitchRadians,
                RealizedCircumferentialPitch = realizedPitch,
                MarginTop = feature.MarginTop ?? feature.Margin, MarginBottom = feature.MarginBottom ?? feature.Margin,
                MaximumCurveBoundMm = cut.Value.Certificates.Values.Max(c => System.Math.Max(c.OuterCurveBoundMm, c.InnerCurveBoundMm)),
                MaximumPcurveBoundMm = cut.Value.Certificates.Values.Max(c => new[] { c.OuterHostPcurveBoundMm, c.OuterToolPcurveBoundMm,
                    c.InnerHostPcurveBoundMm, c.InnerToolPcurveBoundMm }.Max()),
                PatternBuildMilliseconds = patternBuildMilliseconds,
                StepExportMilliseconds = stepExportMilliseconds,
                StepReimportMilliseconds = stepReimportMilliseconds,
                VerificationBasis = verificationBasis
            };
            return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(cylindricalStep.Value,
                cylindricalFeatureId, 0, "perforation-cylindrical", "local-radial-through-wall", Perforation: cylindricalReport)
            { RuntimeBody = cylindricalBody, RuntimeCorrespondence = cylindricalCorrespondence, MaterializedFeatures = FirmamentFeatureAccounting.Receipts(target, "Perforation", feature.Name) });
        }
        if (document.Solid.Name != target || document.Solid.Box is not { Size.Count: 3 } box)
            return Failure("perforation-cylindrical-topology-unavailable: the piping authority constructs constant-thickness annular stock, but the current BRep Boolean route does not materialize radial cylinder-to-cylinder intersections on its wall");
        var plan = FirmamentPerforationPlanner.Plan(box.Size[0], box.Size[1], feature);
        if (!plan.Succeeded) return Failure(plan.Diagnostic!);
        var featureId = $"{target}.{feature.Name}";
        var axis = Direction3D.Create(new Vector3D(0, 0, 1));
        var reference = Direction3D.Create(new Vector3D(1, 0, 0));
        var extents = new AxisAlignedBoxExtents(-box.Size[0] / 2, box.Size[0] / 2, -box.Size[1] / 2, box.Size[1] / 2, 0, box.Size[2]);
        var holes = plan.Instances.Select(instance =>
        {
            var center = new Point3D(instance.X, instance.Y, 0);
            var cylinder = new RecognizedCylinder(center, axis, feature.Diameter / 2, 0, box.Size[2]);
            return new SupportedBooleanHole(instance.StableId(featureId), new AnalyticSurface(AnalyticSurfaceKind.Cylinder, Cylinder: cylinder),
                instance.X, instance.Y, center, new Point3D(instance.X, instance.Y, box.Size[2]), axis, reference,
                feature.Diameter / 2, feature.Diameter / 2, SupportedBooleanHoleSpanKind.Through, 0, box.Size[2]);
        }).ToArray();
        var wallFaces = new Dictionary<string, FaceId>(StringComparer.Ordinal);
        var duplicate = false;
        // The regular layout planner proves non-interference and full edge clearance before this single topology build.
        var built = BrepBooleanBoxCylinderHoleBuilder.BuildComposition(new SafeBooleanComposition(extents, holes), ToleranceContext.Default,
            (id, face) => { if (!wallFaces.TryAdd(id, face)) duplicate = true; });
        if (!built.IsSuccess || built.Value is null)
            return Failure("perforation-brep-failed: " + string.Join(" | ", built.Diagnostics.Select(d => d.Message)));
        var body = built.Value;
        if (duplicate || wallFaces.Count != holes.Length || !FirmamentManifoldChecker.IsManifold(body))
            return Failure("perforation-topology-invalid: wall provenance or manifold check failed");
        var preflight = BrepExportPreflight.Validate(body);
        if (!preflight.IsValid) return Failure("perforation-export-preflight-failed: " + string.Join(" | ", preflight.Diagnostics.Take(4).Select(d => $"{d.Code}: {d.Context}")));
        var step = Step242Exporter.ExportBody(body);
        if (!step.IsSuccess || step.Value is null) return Failure("perforation-step-export-failed: " + string.Join(" | ", step.Diagnostics.Select(d => d.Message)));
        var reimport = Step242Importer.ImportBody(step.Value);
        if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value))
            return Failure("perforation-step-reimport-invalid: production STEP did not reimport as a manifold");
        var descendants = holes.Select(hole => new SemanticTopologyDescendant(
            $"material:perforation:{hole.FeatureId}:wall", "Face", SemanticTopologyRole.HoleWallFace,
            $"perforation:{hole.FeatureId}", Face: wallFaces[hole.FeatureId!], ParentStableId: featureId,
            Addressability: SemanticTopologyAddressability.DerivedStable)).ToArray();
        var correspondence = new SemanticTopologyCorrespondence(featureId, descendants, ["Perforation", "BrepBooleanBoxCylinderHoleBuilder"])
        {
            SourceSpans = new Dictionary<string, FirmamentV2SourceSpan> { [featureId] = feature.SourceSpan }
        };
        var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value)));
        var report = new FirmamentPerforationReport(featureId, feature.SupportFace, feature.Layout, feature.Diameter, feature.Pitch,
            feature.Margin, feature.MinimumLigament, plan.Instances.Count, holes.Select(hole => hole.FeatureId!).ToArray(),
            body.Topology.Vertices.Count(), body.Topology.Edges.Count(), body.Topology.Faces.Count(), true, true, hash);
        return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, featureId, 0,
            "perforation", "circular-through", Perforation: report) { RuntimeBody = body, RuntimeCorrespondence = correspondence, MaterializedFeatures = FirmamentFeatureAccounting.Receipts(target, "Perforation", feature.Name) });
    }

    private static KernelResult<FirmamentStepExportResult>? TryExportV2SemanticHoleBody(FirmamentV2Document document)
    {
        if ((document.ModifyBlocks ?? []).Any(m => (m.EdgeFinishes?.Count ?? 0) > 0)) return null;
        if (document.ModifyBlocks is not { Count: > 0 })
        {
            return null;
        }

        var modifyTargets = document.ModifyBlocks.Select(m => m.TargetSolid).Distinct(StringComparer.Ordinal).ToArray();
        if (modifyTargets.Length != 1)
        {
            return null;
        }

        var targetSolid = document.Solids.SingleOrDefault(s => string.Equals(s.Name, modifyTargets[0], StringComparison.Ordinal));
        if (targetSolid?.Primitive is not FirmamentV2BoxRecord box || box.Size.Count != 3)
        {
            return null;
        }

        var semanticHoles = FirmamentV2SemanticHoleLowering.LowerSemanticHoles(document);
        if (semanticHoles.Count == 0)
        {
            return null;
        }

        var feature = semanticHoles[0];
        // The stock frame is authored by the Box, never inferred from ConceptIr presence.
        var host = FirmamentStockFrame.ForBox(box.Size[0], box.Size[1], box.Size[2]).CreateHoleHost();
        Aetheris.Kernel.Core.Brep.BrepBody? body;
        SemanticTopologyCorrespondence? runtimeCorrespondence = null;
        IReadOnlyList<string> diagnostics;
        if (semanticHoles.Count == 1)
        {
            var materialized = AirHoleSimpleShaftMaterializer.Execute(feature, host);
            body = materialized.Body;
            runtimeCorrespondence = materialized.Correspondence;
            diagnostics = materialized.Diagnostics;
            if (!materialized.Succeeded || body is null)
            {
                return SemanticHoleFailure(diagnostics);
            }
        }
        else
        {
            var materialized = AirHoleCompositeMaterializer.Execute(semanticHoles, host);
            body = materialized.Body;
            runtimeCorrespondence = materialized.Correspondence;
            diagnostics = materialized.Diagnostics;
            if (!materialized.Succeeded || body is null)
            {
                return SemanticHoleFailure(diagnostics);
            }
        }

        if (runtimeCorrespondence is not null)
        {
            var sourceSpans = new Dictionary<string, FirmamentV2SourceSpan>(StringComparer.Ordinal);
            if (targetSolid.SourceSpan is { } bodySpan) sourceSpans[modifyTargets[0]] = bodySpan;
            foreach (var modify in document.ModifyBlocks)
                foreach (var hole in modify.SemanticHoles)
                    if (hole.SourceSpan is { } holeSpan) sourceSpans[$"{modify.TargetSolid}.{hole.Name}"] = holeSpan;
            runtimeCorrespondence = runtimeCorrespondence with
            {
                SourceSpans = sourceSpans,
                Descendants = runtimeCorrespondence.Descendants.Select(descendant =>
                {
                    var owner = semanticHoles.FirstOrDefault(hole => descendant.SourceStableId == $"hole:{hole.FeatureId}");
                    return descendant with
                    {
                        FirmamentSelector = owner is null ? descendant.FirmamentSelector
                            : FirmamentV2HoleWallSelector.Format(descendant, owner.Name, owner.FeatureId) ?? descendant.FirmamentSelector
                    };
                }).ToArray()
            };
        }
        foreach (var pmi in document.BoundPmi?.Dimensions ?? [])
        {
            if (pmi.HoleWallTarget is not { } selector) continue;
            if (runtimeCorrespondence is null || body is null || selector.BodyName != runtimeCorrespondence.BodyStableId)
                return SemanticHoleFailure([$"firmament-v2-hole-wall-role-unavailable:{selector.HoleName}"]);
            var selectedFeature = semanticHoles.SingleOrDefault(hole => hole.Name == selector.HoleName);
            if (selectedFeature is null) return SemanticHoleFailure([$"firmament-v2-hole-wall-unknown-hole:{selector.HoleName}"]);
            var request = new SemanticSelectionRequest($"pmi:{pmi.Name}", pmi.Name, selector.BodyName,
                [$"hole:{selectedFeature.FeatureId}"], SemanticTopologyRole.HoleWallFace,
                SemanticSelectionRequirement.NonEmptyFaceSet, $"offset:{pmi.SourceSpan.Start}", "HoleDiameter");
            var resolution = SemanticTopologySelectionResolver.Resolve(body, runtimeCorrespondence, request);
            if (!resolution.Succeeded)
                return SemanticHoleFailure([$"firmament-v2-hole-wall-role-unavailable:{selector.HoleName}:{resolution.Failure}"]);
        }
        var semanticPmi = BuildV2SemanticPmi(document, semanticHoles, modifyTargets[0], correspondence: runtimeCorrespondence, body: body);
        // Semantic-hole/profile-stack and bounded-Boolean routes remain Audit until their
        // historical coincident/seam topology is remediated producer-by-producer.
        var step = Step242Exporter.ExportBody(body, semanticPmi);
        if (!step.IsSuccess)
        {
            return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
        }

        var reimport = Step242Importer.ImportBody(step.Value);
        if (!reimport.IsSuccess || reimport.Value is null)
            return KernelResult<FirmamentStepExportResult>.Failure(reimport.Diagnostics);
        var stepHash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value)));
        var surfaceKinds = body.Geometry.Surfaces.Select(s => s.Value.Kind).ToArray();

        var featureReports = semanticHoles.Select(h =>
        {
            var legacyPlacement = h.Placement as AirFaceLocalHolePlacement;
            var constructionPlacement = h.ConstructionPlanePlacement;
            return new FirmamentHoleFeatureReport(
            h.Name,
            "Hole",
            h.FeatureId,
            h.Shaft.Diameter,
            h.Placement.U,
            h.Placement.V,
            legacyPlacement?.ResolvedPoint3 is { } p ? new[] { p.X, p.Y, p.Z } : constructionPlacement is { } cp ? new[] { cp.WorldMouthCenter.X, cp.WorldMouthCenter.Y, cp.WorldMouthCenter.Z } : null,
            legacyPlacement?.ResolvedPoint3 is { } sourcePoint ? sourcePoint.Ordinal is { } ordinal ? $"{sourcePoint.SourceMember}[{ordinal}]" : sourcePoint.SourceMember : constructionPlacement?.SourceConceptPlaneId,
            legacyPlacement?.ResolvedPoint3?.StableId ?? constructionPlacement?.SourceConceptPlaneId,
            legacyPlacement?.ResolvedPoint3?.Ordinal,
            legacyPlacement?.ResolvedPoint3?.PlacementFace ?? constructionPlacement?.ConstructionPlaneId ?? legacyPlacement?.EntryFaceName ?? "unplaced",
            legacyPlacement?.ResolvedPoint3?.SourceSpan ?? constructionPlacement?.SourceSpan,
            semanticHoles.Count == 1 ? nameof(AirHoleSimpleShaftMaterializer) : nameof(AirHoleCompositeMaterializer),
            "HoleProfileStack",
            h.Stack.Kind.ToString(),
            string.Join(" -> ", h.Stack.Components.Select(component => component switch
            {
                AirHoleCountersinkComponent countersink => $"conical-entry(entryRadius={countersink.EntryRadius:R},angle={countersink.AngleDegrees:R})",
                AirHoleCounterboreComponent counterbore => $"counterbore(radius={counterbore.Radius:R},depth={counterbore.Depth:R})",
                AirHoleShaftComponent shaft => $"cylindrical-shaft(radius={shaft.Radius:R},{shaft.EndCondition.Kind})",
                _ => component.Kind.ToString(),
            })),
            surfaceKinds.Count(k => k == SurfaceGeometryKind.Cylinder),
            surfaceKinds.Count(k => k == SurfaceGeometryKind.Cone),
            surfaceKinds.Count(k => k == SurfaceGeometryKind.Plane),
            stepHash,
            true);
        }).ToArray();
        return KernelResult<FirmamentStepExportResult>.Success(
            new FirmamentStepExportResult(
                step.Value,
                feature.FeatureId,
                0,
                semanticHoles.Count == 1 ? nameof(AirHoleSimpleShaftMaterializer) : nameof(AirHoleCompositeMaterializer),
                semanticHoles.Count == 1 ? feature.Stack.Kind.ToString() : "CompositeSimpleShaft",
                DatumInspection: document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.DatumPlane).Select(p => new FirmamentPmiInspectionDatum(p.Name, "planar", p.Target)).ToArray() ?? [],
                DimensionInspection: document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.HoleDiameter).Select(p => new FirmamentPmiInspectionDimension("Diameter", p.Target, null, p.Value ?? 0d, "explicit-v2-semantic-pmi", p.Name)).ToArray() ?? [],
                ConceptIr: document.ConceptIr,
                Features: featureReports)
            {
                RuntimeBody = runtimeCorrespondence is null ? null : body,
                RuntimeCorrespondence = runtimeCorrespondence,
                MaterializedFeatures = FirmamentFeatureAccounting.Receipts(modifyTargets[0], "Hole", semanticHoles.Select(h => h.Name).ToArray())
            });
    }

    private static KernelResult<bool> ValidateV2PmiExportSupport(FirmamentV2Document document)
    {
        var bound = (document.BoundPmi?.Datums ?? []).Concat(document.BoundPmi?.Dimensions ?? [])
            .Concat(document.BoundPmi?.Controls ?? []).ToDictionary(r => r.Name, StringComparer.Ordinal);
        var unsupported = (document.PmiBlock?.Records ?? []).Select(r => V2PmiExportRejection(r.Kind, r.Name, bound.GetValueOrDefault(r.Name)))
            .OfType<KernelDiagnostic>().ToArray();
        return unsupported.Length == 0 ? KernelResult<bool>.Success(true) : KernelResult<bool>.Failure(unsupported);
    }

    // The validation report and the actual exporter consult this same admission
    // owner. A supported record kind does not imply every requested field exports.
    internal static KernelDiagnostic? V2PmiExportRejection(FirmamentV2PmiKind kind, string name, FirmamentV2BoundPmiRecord? bound)
    {
        var message = kind is not (FirmamentV2PmiKind.DatumPlane or FirmamentV2PmiKind.HoleDiameter or FirmamentV2PmiKind.Note or FirmamentV2PmiKind.Dimension or FirmamentV2PmiKind.Location)
            && kind != FirmamentV2PmiKind.Location && Step242GeometricToleranceKinds.Find(kind.ToString()) is null
            ? $"firmament-v2-pmi-export-deferred: AP242 export for PMI record '{name}' ({kind.ToString().ToLowerInvariant()}) is deferred; use Datum, HoleDiameter or an admitted geometric control."
            : kind == FirmamentV2PmiKind.HoleDiameter && bound?.DatumRefs.Count > 0
                ? $"firmament-v2-pmi-datum-reference-export-unsupported: HoleDiameter '{name}' requests datum references that native size export cannot preserve. Export Datum separately; datum-referenced geometric controls require a qualified PMI capability."
                : null;
        return message is null ? null : new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, "FirmamentV2.PmiExport");
    }

    private static IReadOnlyList<Step242SemanticPmi> BuildV2SemanticPmi(
        FirmamentV2Document document,
        IReadOnlyList<Core.Air.AirHoleFeature> semanticHoles,
        string targetSolid,
        IReadOnlyDictionary<string, string>? explicitFeatureIds = null,
        SemanticTopologyCorrespondence? correspondence = null,
        BrepBody? body = null,
        IReadOnlyDictionary<string, int[]>? namedFaces = null,
        PrismaticProfileCompositionFeature? composeFeature = null)
    {
        if (document.Pmi is null || document.Pmi.Count == 0)
        {
            return [];
        }

        var holeByName = semanticHoles.SelectMany(h => new[] { new KeyValuePair<string, Core.Air.AirHoleFeature>(h.FeatureId, h), new KeyValuePair<string, Core.Air.AirHoleFeature>(h.Name, h) }).ToDictionary(kvp => kvp.Key, kvp => kvp.Value, StringComparer.Ordinal);
        var boundPmiByName = (document.BoundPmi?.Datums ?? []).Concat(document.BoundPmi?.Dimensions ?? []).Concat(document.BoundPmi?.Controls ?? []).ToDictionary(p => p.Name, StringComparer.Ordinal);
        var targetBinding = document.Solids.Single(s => string.Equals(s.Name, targetSolid, StringComparison.Ordinal));
        var result = new List<Step242SemanticPmi>();
        var importedFaces = new Dictionary<string, IReadOnlyList<int>>(StringComparer.Ordinal);
        foreach (var pmi in document.Pmi)
        {
            if (targetBinding.InlineStep is not null && body is not null)
            {
                var references = ImportedPmiFaceReferences(document, targetBinding, pmi.Target);
                if (references.Count > 0)
                    // The admitted map includes source-to-successor correspondence. Fresh
                    // replacement walls deliberately have no original STEP entity identity.
                    importedFaces[pmi.Name] = references.Select(entity =>
                        targetBinding.InlineStep.TopologyMap.TryResolveFaceEntity(entity, out var mapped)
                        && mapped.StartsWith("face-", StringComparison.Ordinal)
                        && int.TryParse(mapped.AsSpan(5), out var id) ? id : 0)
                        .Where(id => body.Topology.Faces.Any(face => face.Id.Value == id)).Distinct().Order().ToArray();
            }
            if (pmi.Kind == FirmamentV2PmiKind.HoleDiameter && pmi.Value.HasValue)
            {
                boundPmiByName.TryGetValue(pmi.Name, out var boundPmi);
                var tolerancePlus = boundPmi?.DimensionTolerance?.Plus;
                var toleranceMinus = boundPmi?.DimensionTolerance?.Minus;
                if (boundPmi?.HoleWallTarget is { } wallTarget && holeByName.TryGetValue(wallTarget.HoleName, out var wallHole))
                {
                    result.Add(new Step242SemanticPmiHole(wallHole.FeatureId, pmi.Value.Value, null, "explicit_v2_hole_wall_diameter", tolerancePlus, toleranceMinus) { Name = pmi.Name });
                }
                else if (holeByName.TryGetValue(pmi.Target, out var pmiHole))
                {
                    result.Add(new Step242SemanticPmiHole(pmiHole.FeatureId, pmi.Value.Value, null, "explicit_v2_semantic_hole_diameter", tolerancePlus, toleranceMinus) { Name = pmi.Name });
                }
                else if (explicitFeatureIds is not null && explicitFeatureIds.TryGetValue(pmi.Target, out var featureId))
                {
                    result.Add(new Step242SemanticPmiHole(featureId, pmi.Value.Value, null, "explicit_v2_semantic_hole_diameter", tolerancePlus, toleranceMinus) { Name = pmi.Name });
                    if (boundPmi?.Callout == true) result.AddRange(CounterboreCallout(pmi.Name, boundPmi.Targets, composeFeature, correspondence));
                }
                else if (TryResolveV2RecognizedRegionTarget(document, targetBinding, pmi.Target, out var importedTarget) || TryResolveV2ImportedFaceTarget(targetBinding, pmi.Target, out importedTarget))
                {
                    result.Add(new Step242SemanticPmiHole($"{targetSolid}.{pmi.Name}", pmi.Value.Value, null, $"imported_canonical_face:{importedTarget}", tolerancePlus, toleranceMinus) { Name = pmi.Name });
                }
            }
            else if (pmi.Kind == FirmamentV2PmiKind.Dimension && boundPmiByName.TryGetValue(pmi.Name, out var projectedRecord))
            {
                // Values are measured from the built body; every listed feature must agree.
                var projections = composeFeature is null || body is null ? []
                    : projectedRecord.Targets.Select(t => ProjectComposeParameter(composeFeature, body, correspondence, t)).ToArray();
                var resolved = projections.Length == projectedRecord.Targets.Count && projections.All(p => p is not null)
                    && projections.Select(p => (p!.Kind, Math.Round(p.Value, 9))).Distinct().Count() == 1;
                var first = resolved ? projections[0]! : null;
                var tolerance = projectedRecord.DimensionTolerance;
                // One aspect per record: the feature, then the record name (features carry several dimensions).
                result.Add(new Step242SemanticPmiDimension("compose:" + string.Join("+", projectedRecord.Targets.Select(t => t[..t.LastIndexOf('.')])) + "#" + pmi.Name,
                    pmi.Name, first?.Kind ?? "unresolved", first?.Value ?? 0, tolerance?.Plus, tolerance?.Minus,
                    resolved && projections.Sum(p => p!.Count) > 1 ? projections.Sum(p => p!.Count) : null)
                {
                    StandardKind = first?.Kind switch { "diameter" => "diameter", "radius" => "radius", null => "unresolved",
                        _ => projections.Length == 1 && first.Ends is not null ? "linear distance" : null },
                    GeometricFaceIds = resolved ? projections.SelectMany(p => p!.Faces).Distinct().Order().ToArray() : [-1],
                    LocationFaces = resolved && projections.Length == 1 && first!.Ends is { } ends ? ends : null
                });
            }
            else if (pmi.Kind == FirmamentV2PmiKind.Location && boundPmiByName.TryGetValue(pmi.Name, out var locationRecord) && locationRecord.From is { } fromFace)
            {
                var location = composeFeature is null || body is null ? null
                    : ProjectComposeLocation(composeFeature, body, correspondence, explicitFeatureIds ?? new Dictionary<string, string>(), targetSolid, fromFace, locationRecord.Targets[0], locationRecord.Basic);
                var tolerance = locationRecord.DimensionTolerance;
                result.Add(new Step242SemanticPmiDimension("compose:" + locationRecord.Targets[0] + "#" + pmi.Name, pmi.Name, location?.Kind ?? "unresolved", location?.Value ?? 0, tolerance?.Plus, tolerance?.Minus)
                {
                    StandardKind = "linear distance",
                    GeometricFaceIds = location?.Faces ?? [-1],
                    LocationFaces = location?.Ends
                });
            }
            else if (pmi.Kind == FirmamentV2PmiKind.Note && boundPmiByName.TryGetValue(pmi.Name, out var note) && note.Text is { } text)
            {
                result.Add(new Step242SemanticPmiNote(pmi.Name, targetSolid, text));
            }
            else if (pmi.Kind == FirmamentV2PmiKind.DatumPlane)
            {
                var selector = TryResolveV2RecognizedRegionTarget(document, targetBinding, pmi.Target, out var recognizedDatumTarget) ? recognizedDatumTarget : ResolveV2DatumTarget(targetBinding, pmi.Target);
                result.Add(new Step242SemanticPmiDatum(targetSolid, "plane", pmi.Name, selector)
                    { GeometricFaceIds = namedFaces?.GetValueOrDefault(pmi.Target) ?? [], RequiresFaceAssociation = true });
            }
            else if (Step242GeometricToleranceKinds.Find(pmi.Kind.ToString()) is { } control && boundPmiByName.TryGetValue(pmi.Name, out var boundControl))
            {
                var feature = holeByName.TryGetValue(pmi.Target, out var hole) ? hole.FeatureId
                    : boundControl.HoleWallTarget is { } wall && holeByName.TryGetValue(wall.HoleName, out var wallFeature) ? wallFeature.FeatureId
                    : explicitFeatureIds?.GetValueOrDefault(pmi.Target) ?? $"{targetSolid}.{pmi.Name}";
                var faces = namedFaces?.GetValueOrDefault(pmi.Target) is { } named ? named
                    : body is not null && FirmamentSelectorResolver.ResolveSupportPlaneFaces(body, ResolveV2DatumTarget(targetBinding, pmi.Target)) is { Count: > 0 } planarFaces
                    ? planarFaces.Select(id => id.Value).ToArray() : Array.Empty<int>();
                result.Add(new Step242SemanticPmiGeometricTolerance(feature, pmi.Name, control.Name, boundControl.ControlTolerance!.NumericValue!.Value, boundControl.DatumRefs)
                    { Modifiers = boundControl.Modifiers, ZoneForm = boundControl.ZoneForm, GeometricFaceIds = faces });
            }
        }

        // A hole-list target associates one requirement with the shaft walls of every listed hole.
        int[] ShaftFaces(string featureId) => (correspondence?.Descendants ?? [])
            .Where(d => d.Face.HasValue && (d.SourceStableId == featureId || d.ParentStableId == featureId)
                && d.Role is not (SemanticTopologyRole.HoleCounterboreWallFace or SemanticTopologyRole.HoleCountersinkWallFace))
            .Select(d => d.Face!.Value.Value).ToArray();
        var holeSets = boundPmiByName.Values.Where(b => b.Targets.Count > 1 && b.Kind != FirmamentV2PmiKind.Distance)
            .ToDictionary(b => b.Name, b =>
            {
                var ids = b.Targets.Select(t => holeByName.TryGetValue(t, out var h) ? h.FeatureId : explicitFeatureIds?.GetValueOrDefault(t)).ToArray();
                return ids.Any(id => id is null) ? [-1] : ids.SelectMany(id => ShaftFaces(id!)).Distinct().Order().ToArray();
            }, StringComparer.Ordinal);
        return result.Select(item => holeSets.TryGetValue(item switch { Step242SemanticPmiHole h => h.Name ?? "", Step242SemanticPmiGeometricTolerance g => g.Name, _ => "" }, out var setFaces)
            ? item switch
            {
                Step242SemanticPmiHole h => h with { GeometricFaceIds = setFaces, Quantity = boundPmiByName[h.Name!].Targets.Count },
                Step242SemanticPmiGeometricTolerance g => g with { GeometricFaceIds = setFaces, Quantity = boundPmiByName[g.Name].Targets.Count },
                _ => item
            } : item).Select(item => item with
        {
            // Imported entity numbers are provenance, not emitted entity numbers or face ordinals.
            // The importer owns the source-entity -> BRep mapping; the exporter owns the inverse
            // BRep -> emitted-entity mapping. Preserve both boundaries.
            GeometricFaceIds = importedFaces.TryGetValue(item switch
                { Step242SemanticPmiDatum d => d.Label, Step242SemanticPmiHole h => h.Name ?? "", Step242SemanticPmiGeometricTolerance g => g.Name, _ => "" }, out var faces)
                ? faces : item.GeometricFaceIds.Count > 0 ? item.GeometricFaceIds : item is Step242SemanticPmiDatum datum && body is not null
                ? FirmamentSelectorResolver.ResolveSupportPlaneFaces(body, datum.Target).Select(id => id.Value).ToArray()
                : (correspondence?.Descendants ?? [])
                .Where(descendant => descendant.Face.HasValue
                    && (string.Equals(descendant.SourceStableId, item.FeatureId, StringComparison.Ordinal)
                        || string.Equals(descendant.ParentStableId, item.FeatureId, StringComparison.Ordinal)))
                // Shaft dimensions follow semantic wall ownership, not the
                // asserted PMI number: contradictory PMI must keep its target
                // so downstream geometry/requirement checks can diagnose it.
                // A hole's size and geometric controls apply to its shaft; counterbore
                // and countersink walls are separate features with their own sizes.
                .Where(descendant => descendant.Role is not (SemanticTopologyRole.HoleCounterboreWallFace or SemanticTopologyRole.HoleCountersinkWallFace))
                .Select(descendant => descendant.Face!.Value.Value)
                .Distinct()
                .Order()
                .ToArray()
        }).ToArray();
    }

    /// <summary>A hole callout's counterbore, projected from construction: diameter and depth on the counterbore walls.</summary>
    private static IEnumerable<Step242SemanticPmi> CounterboreCallout(string name, IReadOnlyList<string> holes,
        PrismaticProfileCompositionFeature? feature, SemanticTopologyCorrespondence? correspondence)
    {
        var counterbores = holes.Select(h => (feature?.CounterboreHoles ?? []).FirstOrDefault(c => c.Name == h)).ToArray();
        if (counterbores.All(c => c is null)) yield break; // a plain shaft callout has nothing more to say
        var alike = counterbores.All(c => c is not null)
            && counterbores.Select(c => (Math.Round(c!.CounterboreDiameter, 9), Math.Round(c.CounterboreDepth, 9))).Distinct().Count() == 1;
        var faces = alike ? (correspondence?.Descendants ?? []).Where(d => d.Face.HasValue && d.Role == SemanticTopologyRole.HoleCounterboreWallFace
                && counterbores.Any(c => d.SourceStableId == c!.StableId || d.ParentStableId == c!.StableId))
            .Select(d => d.Face!.Value.Value).Distinct().Order().ToArray() : [];
        int[] attached = faces.Length > 0 ? faces : [-1];
        var quantity = holes.Count > 1 ? holes.Count : (int?)null;
        var first = counterbores[0];
        var target = "compose:" + string.Join("+", holes) + "#" + name;
        yield return new Step242SemanticPmiDimension(target + ".CounterboreDiameter", name + ".CounterboreDiameter", "counterbore diameter", first?.CounterboreDiameter ?? 0, null, null, quantity)
            { StandardKind = "diameter", GeometricFaceIds = attached };
        yield return new Step242SemanticPmiDimension(target + ".CounterboreDepth", name + ".CounterboreDepth", "counterbore depth", first?.CounterboreDepth ?? 0, null, null, quantity)
            { StandardKind = null, GeometricFaceIds = attached };
    }

    private static KernelResult<bool> ValidateImportedPmiTargets(IReadOnlyList<Step242SemanticPmi> items, BrepBody body)
    {
        foreach (var item in items)
        {
            if (item is Step242SemanticPmiGeometricTolerance)
            {
                if (item.GeometricFaceIds.Count > 0 && item.GeometricFaceIds.All(id => body.Topology.Faces.Any(face => face.Id.Value == id))) continue;
                return KernelResult<bool>.Failure([new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,
                    $"firmament-v2-imported-pmi-target-unresolved: '{item.FeatureId}' requires a proved imported face association.", "FirmamentV2.Pmi")]);
            }
            var required = item is Step242SemanticPmiDatum ? SurfaceGeometryKind.Plane : SurfaceGeometryKind.Cylinder;
            if (item.GeometricFaceIds.Count == 0 || item.GeometricFaceIds.Any(id =>
                !body.TryGetFaceSurface(new FaceId(id), out var surface) || surface?.Kind != required))
                return KernelResult<bool>.Failure([new(KernelDiagnosticCode.ValidationFailed,
                    KernelDiagnosticSeverity.Error, $"firmament-v2-imported-pmi-target-kind: '{item.FeatureId}' requires a resolved {required} face. Choose a compatible admitted face.", "FirmamentV2.Pmi")]);
        }
        return KernelResult<bool>.Success(true);
    }

    private static IReadOnlyList<string> ImportedPmiFaceReferences(FirmamentV2Document document, FirmamentV2SolidBinding solid, string target)
    {
        var prefix = solid.Name + ".face(\"";
        if (target.StartsWith(prefix, StringComparison.Ordinal) && target.EndsWith("\")", StringComparison.Ordinal))
            return [target[prefix.Length..^2]];
        prefix = solid.Name + ".region(\"";
        if (!target.StartsWith(prefix, StringComparison.Ordinal) || !target.EndsWith("\")", StringComparison.Ordinal)) return [];
        var name = target[prefix.Length..^2];
        return document.RecognizedRegions?.SingleOrDefault(r => r.BodyName == solid.Name && r.RegionName == name)?.FaceRefs ?? [];
    }


    private static bool TryResolveV2RecognizedRegionTarget(FirmamentV2Document document, FirmamentV2SolidBinding solid, string target, out string resolved)
    {
        resolved = string.Empty;
        const string marker = ".region(\"";
        if (solid.InlineStep is null || !target.StartsWith(solid.Name + marker, StringComparison.Ordinal) || !target.EndsWith("\")", StringComparison.Ordinal))
        {
            return false;
        }

        var regionName = target[(solid.Name.Length + marker.Length)..^2];
        var region = document.RecognizedRegions?.FirstOrDefault(r => string.Equals(r.BodyName, solid.Name, StringComparison.Ordinal) && string.Equals(r.RegionName, regionName, StringComparison.Ordinal));
        if (region is null || region.FaceRefs.Count == 0 || !solid.InlineStep.TopologyMap.TryResolveFaceEntity(region.FaceRefs[0], out var faceId))
        {
            return false;
        }

        resolved = $"{solid.Name}.{region.RegionName}.{faceId}:{region.FaceRefs[0]}";
        return true;
    }

    private static bool TryResolveV2ImportedFaceTarget(FirmamentV2SolidBinding solid, string target, out string resolved)
    {
        resolved = string.Empty;
        const string marker = ".face(\"";
        if (solid.InlineStep is null || !target.StartsWith(solid.Name + marker, StringComparison.Ordinal) || !target.EndsWith("\")", StringComparison.Ordinal))
        {
            return false;
        }

        var entity = target[(solid.Name.Length + marker.Length)..^2];
        if (!solid.InlineStep.TopologyMap.TryResolveFaceEntity(entity, out var faceId))
        {
            return false;
        }

        resolved = $"{solid.Name}.{faceId}:{entity}";
        return true;
    }

    private static string ResolveV2DatumTarget(FirmamentV2SolidBinding solid, string target)
    {
        if (TryResolveV2ImportedFaceTarget(solid, target, out var importedTarget))
        {
            return importedTarget;
        }

        if (target.StartsWith("face(", StringComparison.Ordinal))
        {
            return $"{solid.Name}.{FaceAxisToPort(target)}";
        }

        var exposure = solid.Box?.Exposures.FirstOrDefault(e => string.Equals(e.Alias, target, StringComparison.Ordinal));
        return exposure is null ? $"{solid.Name}.{target}" : $"{solid.Name}.{FaceAxisToPort(exposure.Selector)}";
    }

    private static string FaceAxisToPort(string selector) => selector switch
    {
        "face(+Z)" => "top_face",
        "face(-Z)" => "bottom_face",
        "face(+X)" => "plus_x_face",
        "face(-X)" => "minus_x_face",
        "face(+Y)" => "plus_y_face",
        "face(-Y)" => "minus_y_face",
        _ => selector
    };

    private static IReadOnlyList<FirmamentEngineeringFeatureReport> EngineeringFeatureReports(PrismaticProfileCompositionFeature feature) =>
        (feature.Bosses ?? []).Select(item => new FirmamentEngineeringFeatureReport(
            item.Name, "Boss", item.StableId, item.Host, item.SupportFace, item.ProfileReference,
            item.Height, "Height", "Add", MaterializationRoute: "PrismaticSectionStack/Add",
            SupportSpan: item.SupportSpan, ParentSupport: item.ParentSupport))
        .Concat((feature.Pockets ?? []).Select(item => new FirmamentEngineeringFeatureReport(
            item.Name, "Pocket", item.StableId, item.Host, item.SupportFace, item.ProfileReference,
            item.Depth, "Depth", "Remove", item.RemainingFloor, item.MinimumFloorThickness,
            item.MinimumFloorPolicySource, "PrismaticSectionStack/Remove", item.SupportSpan, item.ParentSupport)))
        .Concat((feature.MaterialOffsets ?? []).Select(item => new FirmamentEngineeringFeatureReport(
            item.Name, $"{item.OperationKind}Offset<{item.ToolFamily}>", item.StableId, item.Target, item.Support,
            item.ProfileReference, item.Extent, item.Termination, item.OperationKind,
            PolicySource: "BoundedMaterialOffsetX1",
            MaterializationRoute: $"MaterialOffsetAir/{item.ToolFamily}->PrismaticSectionStack/{item.OperationKind}",
            SupportSpan: item.SupportSpan, ParentSupport: item.ParentSupport,
            ToolFamily: item.ToolFamily, Direction: item.Direction, Termination: item.Termination,
            AuthorizedRegion: item.AuthorizedRegion)))
        .OrderBy(item => item.FeatureId, StringComparer.Ordinal)
        .ToArray();

    private static IReadOnlyList<FirmamentHoleFeatureReport> CompositionHoleReports(PrismaticProfileCompositionFeature feature, BrepBody body, SemanticTopologyCorrespondence? correspondence) =>
        (feature.ShaftHoles ?? []).Select(item => new FirmamentHoleFeatureReport(
            item.Name, "Hole<Shaft>", item.StableId, item.Diameter, item.CenterX, item.CenterY,
            null, "ProfileCompose.Center", null, null, "+Z", item.SourceSpan,
            "PrismaticSectionStack/Remove", "SemanticShaftProfile", "SimpleShaft",
            SupportSpan: item.SupportSpan, ParentSupport: item.ParentSupport, SupportBoundaryMargin: item.SupportBoundaryMargin))
        .Concat((feature.CounterboreHoles ?? []).Select(item => new FirmamentHoleFeatureReport(
            item.Name, "Hole<Counterbore>", item.StableId, item.Diameter, item.CenterX, item.CenterY,
            null, "ProfileCompose.Center", null, null, "+Z", item.SourceSpan,
            "PrismaticSectionStack/Remove", "SemanticCounterboreProfiles", "Counterbore",
            SupportSpan: item.SupportSpan, ParentSupport: item.ParentSupport, SupportBoundaryMargin: item.SupportBoundaryMargin)))
        .Concat((feature.CountersinkHoles ?? []).Select(item => new FirmamentHoleFeatureReport(
            item.Name, "Hole<Countersink>", item.StableId, item.Diameter, item.CenterX, item.CenterY,
            null, "ProfileCompose.Center", null, null, "+Z", item.SourceSpan,
            "PrismaticSectionStack/VariableCircularCavity", "SemanticCountersinkProfile", "Countersink",
            SupportSpan: item.SupportSpan, ParentSupport: item.ParentSupport, SupportBoundaryMargin: item.SupportBoundaryMargin)))
        .Concat(feature.FaceHoles.Select(item => new FirmamentHoleFeatureReport(
            item.Name, $"Hole<{item.Variant}>", item.StableId, item.Diameter, item.X, item.Y,
            null, "PlanarFace.Center", null, null, $"face({feature.Name}.Side({System.Text.Json.JsonSerializer.Serialize(item.SupportSource)}))", null,
            "PlanarFaceThroughHole", "ConstructionSideSelector", item.Variant,
            SupportBoundaryMargin: PlanarFaceThroughHole.MinimumClearance)))
        .Select(report =>
        {
            var surfaces = (correspondence?.Descendants ?? []).Where(d => d.SourceStableId == report.FeatureId && d.Face.HasValue)
                .Select(d => d.Face!.Value).Distinct().Select(body.GetFaceSurface).ToArray();
            return report with
            {
                CylindricalFaces = surfaces.Count(s => s.Kind == SurfaceGeometryKind.Cylinder),
                ConicalFaces = surfaces.Count(s => s.Kind == SurfaceGeometryKind.Cone),
                PlanarFaces = surfaces.Count(s => s.Kind == SurfaceGeometryKind.Plane)
            };
        })
        .OrderBy(item => item.FeatureId, StringComparer.Ordinal)
        .ToArray();

    /// <summary>
    /// The hole planners narrate their route as they go ("planner started", "plan created", "execution route: ...")
    /// and then state the one thing that stopped them. Reporting every line as an error buried that cause under the
    /// narration, so only lines that state a cause are errors; the narration is kept, as information, for provenance.
    /// </summary>
    private static KernelResult<FirmamentStepExportResult> SemanticHoleFailure(IEnumerable<string> diagnostics)
    {
        var lines = diagnostics.ToArray();
        var anyCause = lines.Any(IsSemanticHoleFailureCause);
        return KernelResult<FirmamentStepExportResult>.Failure(lines.Select(d => new Kernel.Core.Diagnostics.KernelDiagnostic(
            Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,
            !anyCause || IsSemanticHoleFailureCause(d) ? Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error : Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Info,
            d,
            "FirmamentV2.SemanticHoleBuild")).ToArray());
    }

    private static bool IsSemanticHoleFailureCause(string line) =>
        line.Contains("rejected", StringComparison.Ordinal)
        || line.Contains("failed", StringComparison.Ordinal)
        || line.Contains("Unsupported", StringComparison.Ordinal)
        || line.StartsWith("semantic diagnostic", StringComparison.Ordinal)
        || line.StartsWith("firmament-", StringComparison.Ordinal);

    private static string ResolveDefaultOutputPath(string fullSourcePath)
    {
        // A source file is the only project boundary Preview 1 needs. Keeping the
        // generated artifact adjacent to it is deterministic, discoverable, and
        // works identically from a checkout, a package, or a user directory.
        return Path.ChangeExtension(fullSourcePath, ".step");
    }

}