Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

117 KB
Raw Blame
using System.Globalization;
using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
using System.Text.RegularExpressions;
using Aetheris.Kernel.Firmament.Materializer;

namespace Aetheris.Kernel.Firmament.FirmamentV2;

/// <summary>
/// Binds the small, static Profile authoring language into the single resolved-profile
/// representation used by extrusion.  Construction paths are deliberately only another
/// producer of named points and guides; no path-specific materialization exists.
/// </summary>
public static class ProfileAuthoringParser
{
    // IntelliDraft projects the same bound guides consumed by Profile, including open Paths.
    // This is a query over the existing owner, not another geometry evaluator.
    internal static (Dictionary<string, (double X, double Y)> Points,
        Dictionary<string, LineArcProfileCurve2D> Guides, IReadOnlyList<string> Diagnostics)
        InspectConstruction(string source, FirmamentCompileTimeValues values)
    {
        var diagnostics = new List<string>();
        source = FirmamentSourceSpelling.Normalize(source);
        var boundaries = ClosedBoundary2Authoring.Expand(source, diagnostics, values);
        source = boundaries?.Source ?? source;
        var points = new Dictionary<string, (double X, double Y)>(StringComparer.Ordinal);
        var guides = new Dictionary<string, LineArcProfileCurve2D>(StringComparer.Ordinal);
        AddOrdinaryGuides(source, points, guides, diagnostics, applySpans: false, bind: values.NominalExpression);
        BindPaths(source, points, guides, diagnostics);
        // Use the lowerer's own public member map; do not guess generated-name ownership.
        if (boundaries is not null)
        {
            var generated = boundaries.GeneratedDeclarationNames.ToHashSet(StringComparer.Ordinal);
            foreach (var (owner, members) in boundaries.AuthoringMembers)
                foreach (var (member, lowered) in members)
                {
                    if (generated.Contains(lowered) && points.Remove(lowered, out var point)) points[owner + "." + member] = point;
                    if (lowered != owner && guides.Remove(lowered, out var curve)) guides[owner + "." + member] = curve;
                    if (lowered.LastIndexOf('.') is var dot && dot > 0 && lowered[..dot] != owner)
                        foreach (var key in points.Keys.Where(k => k.StartsWith(lowered[..dot] + ".", StringComparison.Ordinal)).ToArray()) points.Remove(key);
                }
        }
        return (points, guides, diagnostics);
    }
    public const string SegmentEndpointMustReferenceNamedPoint = "ProfileSegmentEndpointMustReferenceNamedPoint";
    private const double Tolerance = 1e-9;
    private static readonly Regex Segment = new(@"\bSegment\s+(?<n>\w+)\s*\{\s*Trace\s*:\s*(?<trace>[\w.]+)\s*;?\s*From\s*:\s*(?<from>[\w.]+)\s*;?\s*To\s*:\s*(?<to>[\w.]+)(?:\s*;?\s*Sweep\s*:\s*(?<sweep>Clockwise|CounterClockwise))?", RegexOptions.Singleline | RegexOptions.CultureInvariant);
    private static readonly Regex SpanHeader = new(@"\bSpan\s*<\s*(?<type>[A-Za-z_]\w*)\s*>\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant);

    public static bool IsProfileSource(string source) => Regex.IsMatch(source, @"\bProfile\s+[A-Za-z_]\w*", RegexOptions.CultureInvariant);

    /// <summary>Inspects first-class geometric views without materializing independent guides.</summary>
    public static GeometricSpanInspection InspectGeometricSpans(string source)
    {
        ArgumentNullException.ThrowIfNull(source);
        var diagnostics = new List<string>();
        source = ExpandBuiltInPolygons(source, diagnostics);
        var expansion = FirmamentV2TemplateExpansion.Expand(source, diagnostics);
        if (expansion is not null) source = expansion.Source;
        var staticExpansion = CanonicalStaticAuthoring.Expand(source, diagnostics);
        if (staticExpansion is not null) source = staticExpansion.Source;
        var points = new Dictionary<string, (double X, double Y)>(StringComparer.Ordinal);
        var guides = new Dictionary<string, LineArcProfileCurve2D>(StringComparer.Ordinal);
        AddOrdinaryGuides(source, points, guides, diagnostics, applySpans: false);
        var spans = ApplyGeometricSpans(source, points, guides, diagnostics, addGuides: false);
        return new(spans, diagnostics.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray());
    }

    /// <summary>Resolves one named Profile without requiring an Extrude consumer.</summary>
    internal static FirmamentV2ValidationDiagnostic? LocateDiagnostic(string source, string diagnostic)
    {
        var parts = diagnostic.Split(':');
        if (parts.Length < 3 || parts[0] != SegmentEndpointMustReferenceNamedPoint) return null;
        var syntax = FirmamentSyntaxParser.Parse(FirmamentSourceSpelling.Normalize(source)).Document;
        var segments = FirmamentSyntaxTraversal.Declarations(syntax).Where(d => d.Type.Name.Text == "Segment" && d.Name?.Text == parts[1]).ToArray();
        if (segments.Length != 1) return null;
        return new(parts[0], "fatal", $"Segment '{parts[1]}' endpoint '{parts[2]}' must reference a named Point2; declare the point and use its name.")
            { SourceSpan = segments[0].Span, Target = parts[1], Stage = "Profile binding", IsOriginalSource = true };
    }

    public static ResolvedProfile2D? ResolveNamedProfile(string source, string profileName, out IReadOnlyList<string> reportedDiagnostics)
        => ResolveNamedProfileCore(source, profileName, new(StringComparer.Ordinal), out reportedDiagnostics, new FirmamentCompileTimeValues(source));

    internal static ResolvedProfile2D? ResolveNamedProfileCore(string source, string profileName, HashSet<string> visiting, out IReadOnlyList<string> reportedDiagnostics,
        FirmamentCompileTimeValues? scalars=null)
    {
        ArgumentNullException.ThrowIfNull(source);
        ArgumentException.ThrowIfNullOrWhiteSpace(profileName);
        var diagnostics = new List<string>();
        if (!visiting.Add(profileName)) { reportedDiagnostics = [$"concept-profile-dependency-cycle:{profileName}"]; return null; }
        source = ProfileModificationTemplateLibrary.ResolveImports(source);
        foreach (var authored in SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements)
            .Where(d => d.Type.Name.Text == "Profile" && d.Name?.Text == profileName))
            ValidateProfileBody(authored, diagnostics);
        source = ExpandBuiltInPolygons(source, diagnostics,scalars);
        var expansion = FirmamentV2TemplateExpansion.Expand(source, diagnostics,scalars);
        if (expansion is not null) source = expansion.Source;
        if (ProfileBoundaryAuthoring.TryResolve(source, profileName, visiting, diagnostics, out var derived,scalars)
            || ConceptProfileDerivation.TryResolve(source, profileName, visiting, diagnostics, out derived,scalars))
        {
            visiting.Remove(profileName);
            reportedDiagnostics = diagnostics.Distinct(StringComparer.Ordinal).ToArray();
            return diagnostics.Count == 0 ? derived : null;
        }
        var declaration = FindProfiles(source).FirstOrDefault(profile => profile.Name == profileName);
        if (declaration is null) { reportedDiagnostics = [$"profile-source-missing-profile:{profileName}"]; return null; }
        var points = new Dictionary<string, (double X, double Y)>(StringComparer.Ordinal);
        var guides = new Dictionary<string, LineArcProfileCurve2D>(StringComparer.Ordinal);
        AddOrdinaryGuides(source, points, guides, diagnostics, applySpans: false,bind:scalars is null?null:scalars.NominalExpression);
        var paths = BindPaths(source, points, guides, diagnostics);
        var plane = ResolveConstructionPlane(source, declaration.Frame, diagnostics);
        var loops = BindProfileLoops(declaration, paths, points, guides, diagnostics);
        var profile = plane is null || loops.Count == 0 ? null : new ResolvedProfile2D(declaration.Name, declaration.Frame ?? "XY", loops, plane);
        if (profile is not null)
        {
            var validation = ResolvedProfile2DValidator.Validate(profile);
            diagnostics.AddRange(validation.Diagnostics);
            if (!validation.IsValid) profile = null;
        }
        reportedDiagnostics = diagnostics.Distinct(StringComparer.Ordinal).ToArray();
        visiting.Remove(profileName);
        return profile;
    }

    internal static IReadOnlyList<string> ValidatePipelineContexts(string source)
    {
        var syntax = FirmamentSyntaxParser.Parse(source).Document;
        var allowed = FirmamentSyntaxTraversal.Declarations(syntax).Where(d => d.Type.Name.Text == "Profile"
            || d.Type.Name.Text == "Path")
            .Select(d => d.Body?.Span).OfType<FirmamentV2SourceSpan>().ToArray();
        return FirmamentSyntaxTraversal.Expressions(syntax).OfType<BinarySyntax>().Where(e => e.Operator == BinaryOperator.Pipeline)
            .Where(e => !allowed.Any(span => e.Span.Start >= span.Start && e.Span.Start + e.Span.Length <= span.Start + span.Length))
            .Select(e => $"firmament-pipeline-context-type:{ParsePipelineStages(e)[0].Reference}")
            .Distinct(StringComparer.Ordinal).ToArray();
    }

    /// <summary>
    /// Resolves one domain-neutral Concept Path without converting it into a closed Profile.
    /// Sweep and other ordered-path consumers use this boundary so authored line/arc identity
    /// and provenance survive independently of the profile-extrusion frontend.
    /// </summary>
    public static ResolvedConceptPath2D? ResolveConceptPath(string source, string pathName, out IReadOnlyList<string> reportedDiagnostics)
    {
        ArgumentNullException.ThrowIfNull(source);
        ArgumentException.ThrowIfNullOrWhiteSpace(pathName);
        var diagnostics = new List<string>();
        source = ExpandBuiltInPolygons(source, diagnostics);
        var points = new Dictionary<string, (double X, double Y)>(StringComparer.Ordinal);
        var guides = new Dictionary<string, LineArcProfileCurve2D>(StringComparer.Ordinal);
        AddOrdinaryGuides(source, points, guides, diagnostics);
        var paths = BindPaths(source, points, guides, diagnostics);
        if (!paths.TryGetValue(pathName, out var path))
            diagnostics.Add($"concept-path-missing:{pathName}");
        reportedDiagnostics = diagnostics;
        return path is null ? null : new ResolvedConceptPath2D(
            path.Name,
            path.Steps.SelectMany(step => step.Curves.Select((curve, ordinal) => new ResolvedConceptPathSegment2D(
                step.Curves.Count == 1 ? step.Name : $"{step.Name}.curve{ordinal:D2}",
                step.Kind,
                curve,
                $"concept-path:{path.Name}.{step.Name}",
                step.SourceReference,
                step.WasReversed,
                step.PipelineIndex,
                step.SourceRange))).ToArray(),
            $"concept-path:{path.Name}");
    }

    public static IReadOnlyList<ConceptPathInspection> InspectConceptPaths(string source)
    {
        var diagnostics = new List<string>();
        source = ExpandBuiltInPolygons(source, diagnostics);
        var expansion = FirmamentV2TemplateExpansion.Expand(source, diagnostics);
        if (expansion is not null) source = expansion.Source;
        var points = new Dictionary<string, (double X, double Y)>(StringComparer.Ordinal);
        var guides = new Dictionary<string, LineArcProfileCurve2D>(StringComparer.Ordinal);
        AddOrdinaryGuides(source, points, guides, diagnostics);
        var profiles = FindProfiles(source).Where(profile => profile.FromPath is not null).ToArray();
        var operations = Regex.Matches(source, @"\b(?:Base|Add|Remove)\s+(?<name>[A-Za-z_]\w*)\s*\{[\s\S]*?\bProfile\s*:\s*(?<profile>[A-Za-z_]\w*)", RegexOptions.CultureInvariant)
            .Cast<Match>().Select(match => (Name: match.Groups["name"].Value, Profile: match.Groups["profile"].Value, Offset: match.Index)).ToArray();
        return BindPaths(source, points, guides, diagnostics).Values.Select(path =>
        {
            var pathProfiles = profiles.Where(profile => profile.FromPath == path.Name).ToArray();
            var profileNames = pathProfiles.Select(profile => profile.Name).ToHashSet(StringComparer.Ordinal);
            var composeOperations = operations.Where(operation => profileNames.Contains(operation.Profile)).ToArray();
            var capabilities = new List<string> { "OrderedPlanarGeometry" };
            if (pathProfiles.Length > 0) capabilities.Add("ProfileSource");
            if (composeOperations.Length > 0) capabilities.Add("ComposeProfileOperand");
            var exposed = new List<ConceptPathExposedMemberInspection>
            {
                new("Start", "Point2", "ProfileEndpoint", $"{path.Name}.Start")
            };
            exposed.AddRange(path.Steps.SelectMany(step => new[]
            {
                new ConceptPathExposedMemberInspection(step.Name, step.Kind, "ProfileGuide", step.GuideName),
                new ConceptPathExposedMemberInspection(step.Name + ".End", "Point2", "ProfileEndpoint", step.EndpointName)
            }));
            var consumers = pathProfiles.Select(profile => new ConceptPathConsumerInspection("Profile", profile.Name, "ProfileSource", profile.SourceSpan))
                .Concat(composeOperations.Select(operation => new ConceptPathConsumerInspection("ComposeOperation", operation.Name, "ComposeProfileOperand", $"offset:{operation.Offset}")))
                .ToArray();
            return new ConceptPathInspection(
                path.Name, path.Start.X, path.Start.Y, path.InitialHeading,
                path.Steps.Select(step => new ConceptPathEntryInspection(step.Name, step.Curves.Count == 1 && step.Curves[0] is LineArcCircularArc2D ? "Arc" : step.Curves.All(curve => curve is LineArcLineSegment2D) ? "LineChain" : "CurveChain", step.Start.X, step.Start.Y, step.End.X, step.End.Y, step.Heading,
                    step.Curves.Count == 1 && step.Curves[0] is LineArcCircularArc2D arc ? arc.Radius : null, step.Curves.Count == 1 && step.Curves[0] is LineArcCircularArc2D arc2 ? arc2.SweepAngleRadians * 180d / Math.PI : null, step.GuideName, step.EndpointName, step.Curves.Count, step.Kind)).ToArray(),
                capabilities, exposed, consumers, $"concept-path:{path.Name}");
        }).ToArray();
    }

    public static (ResolvedProfile2D? Profile, double Height, IReadOnlyList<string> Diagnostics) Parse(string source)
        => Parse(source, null);

    internal static (ResolvedProfile2D? Profile, double Height, IReadOnlyList<string> Diagnostics) Parse(string source, FirmamentCompileTimeValues? values)
    {
        var diagnostics = new List<string>();
        values ??= new FirmamentCompileTimeValues(source);
        var expanded = FirmamentV2TemplateExpansion.Expand(source, diagnostics, values);
        if (expanded is not null) source = expanded.Source;
        source = ExpandBuiltInPolygons(source, diagnostics, values);
        var authoredProfiles = FindProfiles(source).ToArray();
        var extrusion = FindBlocks(source, @"\bExtrude\s+\w+\s*\{").FirstOrDefault();
        var extrudeProfile = extrusion is null ? null : Property(extrusion.Body, "Profile");
        var profile = authoredProfiles.FirstOrDefault(candidate => candidate.Name == extrudeProfile) ?? authoredProfiles.FirstOrDefault();
        if (profile is null)
            return (null, 0, ["profile-source-missing-profile"]);

        if (ProfileBoundaryAuthoring.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out var conceptProfile, values)
            || ConceptProfileDerivation.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out conceptProfile, values))
        {
            var depths = ResolveExtrude(source, profile.Name, diagnostics, values.NominalExpression);
            return (conceptProfile is null ? null : conceptProfile with { LocalStartDepth = depths.Start, LocalEndDepth = depths.End }, depths.Height, diagnostics);
        }

        var points = new Dictionary<string, (double X, double Y)>(StringComparer.Ordinal);
        var guides = new Dictionary<string, LineArcProfileCurve2D>(StringComparer.Ordinal);
        AddOrdinaryGuides(source, points, guides, diagnostics, bind: values.NominalExpression);
        var paths = BindPaths(source, points, guides, diagnostics);

        ConstructionPlane? plane = ResolveConstructionPlane(source, profile.Frame, diagnostics);
        var loops = BindProfileLoops(profile, paths, points, guides, diagnostics);
        var (start, end, height) = ResolveExtrude(source, profile.Name, diagnostics, values.NominalExpression);
        if (diagnostics.Count != 0)
            return (null, height, diagnostics);
        return (new ResolvedProfile2D(profile.Name, profile.Frame ?? "XY", loops, plane ?? ConstructionPlane.WorldXY, start, end), height, diagnostics);
    }

    /// <summary>
    /// Resolves every Profile whose source is a Concept Path into the ordinary
    /// resolved-profile representation consumed by extrusion and composition.
    /// Concept Path syntax is intentionally erased at this boundary; segment
    /// provenance retains the authored path and step identities.
    /// </summary>
    internal static IReadOnlyDictionary<string, ResolvedProfile2D> BindPathDerivedProfiles(string source, List<string> diagnostics, FirmamentCompileTimeValues? values = null)
    {
        // This is the canonical semantic-profile adapter used by Compose and SectionChain.
        // Its historical name remains source-compatible; pipeline syntax is erased here too.
        source = ProfileModificationTemplateLibrary.ResolveImports(source);
        values ??= new FirmamentCompileTimeValues(source);
        foreach (var authored in SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).Where(d => d.Type.Name.Text == "Profile"))
            ValidateProfileBody(authored, diagnostics);
        source = ExpandBuiltInPolygons(source, diagnostics, values);
        var templates = FirmamentV2TemplateExpansion.Expand(source, diagnostics, values);
        if (templates is not null) source = templates.Source;
        var authoredProfiles = FindProfiles(source).Where(candidate => candidate.FromPath is not null || candidate.Body?.Contains("|>", StringComparison.Ordinal) == true || ProfileBoundaryAuthoring.IsDerived(candidate.Body)).ToArray();
        if (authoredProfiles.Length == 0) return new Dictionary<string, ResolvedProfile2D>();
        var points = new Dictionary<string, (double X, double Y)>(StringComparer.Ordinal);
        var guides = new Dictionary<string, LineArcProfileCurve2D>(StringComparer.Ordinal);
        AddOrdinaryGuides(source, points, guides, diagnostics, bind: values.NominalExpression);
        var paths = BindPaths(source, points, guides, diagnostics);
        var profiles = new Dictionary<string, ResolvedProfile2D>(StringComparer.Ordinal);
        foreach (var profile in authoredProfiles)
        {
            if (ProfileBoundaryAuthoring.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out var derived, values)
                || ConceptProfileDerivation.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out derived, values))
            {
                if (derived is not null && !profiles.TryAdd(profile.Name, derived)) diagnostics.Add($"profile-duplicate:{profile.Name}");
                continue;
            }
            var plane = ResolveConstructionPlane(source, profile.Frame, diagnostics);
            var loops = BindProfileLoops(profile, paths, points, guides, diagnostics);
            if (plane is null || loops.Count == 0) continue;
            var resolved = new ResolvedProfile2D(profile.Name, profile.Frame ?? "XY", loops, plane);
            var validation = ResolvedProfile2DValidator.Validate(resolved);
            diagnostics.AddRange(validation.Diagnostics);
            if (validation.IsValid && !profiles.TryAdd(profile.Name, resolved))
                diagnostics.Add($"profile-duplicate:{profile.Name}");
        }
        return profiles;
    }

    private static string ExpandBuiltInPolygons(string source, List<string> diagnostics,FirmamentCompileTimeValues? scalars=null)
    {
        // Direct profile/path API consumers use the same AST-position aliases as
        // whole-document compilation, including remaining compatibility adapters.
        source = FirmamentSourceSpelling.Normalize(source);
        return ClosedBoundary2Authoring.Expand(source, diagnostics,scalars)?.Source ?? source;
    }

    internal static ConstructionPlane? ResolveNamedConstructionPlane(string source, string frame, List<string> diagnostics)
        => ResolveConstructionPlane(source, frame, diagnostics);

    internal static bool OwnsConstructionGuide(string type) => type is "Point2" or "Rect2" or "Line2" or "Arc2" or "CubicBezier2" or "Circle2" or "Ellipse2Guide";
    internal static bool OwnsDeclaration(DeclarationSyntax declaration) => OwnsConstructionGuide(declaration.Type.Name.Text)
        || ClosedBoundary2Authoring.IsBoundaryType(declaration.Type.Name.Text)
        || declaration.Type.Name.Text is "Profile" or "Path" or "Span" or "Curve2"
        || declaration.Type.Name.Text=="Plane" && declaration.Modifiers.Any(m=>m.Name.Text=="Construction");

    private static void AddOrdinaryGuides(string source, Dictionary<string, (double X, double Y)> points, Dictionary<string, LineArcProfileCurve2D> guides, List<string> diagnostics, bool applySpans = true,
        Func<ExpressionSyntax,ExpressionSyntax>? bind=null)
    {
        var declarations = SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).Where(d => d.Name is not null && d.Body is not null).ToArray();
        foreach (var d in declarations.Where(d => d.Type.Name.Text == "Point2"))
        {
            var fields = new FirmamentSyntaxFields(d, diagnostics,bind:bind);
            if (fields.Vector("Position", "mm", out var xy) && xy.Length == 2) points[d.Name!.Text] = (xy[0], xy[1]);
            else diagnostics.Add($"profile-layout-point-invalid:{d.Name!.Text}:expected-two-finite-lengths");
            fields.Complete();
        }
        foreach (var d in declarations.Where(d => d.Type.Name.Text == "Rect2"))
        {
            var fields = new FirmamentSyntaxFields(d, diagnostics,bind:bind); var name = d.Name!.Text;
            fields.Word("Role");
            if (!fields.Vector("Center", "mm", out var center) || center.Length != 2 || !fields.Vector("Size", "mm", out var size) || size.Length != 2 || size.Any(n => n <= 0))
            { diagnostics.Add($"rect2-invalid-size:{name}"); continue; }
            fields.Complete();
            var x = center[0]; var y = center[1]; var width = size[0]; var height = size[1];
            points[$"{name}.BottomLeft"] = (x - width / 2, y - height / 2);
            points[$"{name}.BottomRight"] = (x + width / 2, y - height / 2);
            points[$"{name}.TopRight"] = (x + width / 2, y + height / 2);
            points[$"{name}.TopLeft"] = (x - width / 2, y + height / 2);
            var bl = points[$"{name}.BottomLeft"]; var br = points[$"{name}.BottomRight"]; var tr = points[$"{name}.TopRight"]; var tl = points[$"{name}.TopLeft"];
            guides[$"{name}.Bottom"] = new LineArcLineSegment2D(bl, br); guides[$"{name}.Right"] = new LineArcLineSegment2D(br, tr);
            guides[$"{name}.Top"] = new LineArcLineSegment2D(tr, tl); guides[$"{name}.Left"] = new LineArcLineSegment2D(tl, bl);
        }
        foreach (var d in declarations.Where(d => d.Type.Name.Text is "Line2" or "CubicBezier2"))
        {
            var fields = new FirmamentSyntaxFields(d, diagnostics,bind:bind); var name = d.Name!.Text;
            var a = fields.Word("From"); var b = fields.Word("To");
            var c1 = d.Type.Name.Text == "CubicBezier2" ? fields.Word("Control1") : null;
            var c2 = d.Type.Name.Text == "CubicBezier2" ? fields.Word("Control2") : null;
            fields.Complete();
            if (a is null || b is null || !points.TryGetValue(a, out var from) || !points.TryGetValue(b, out var to))
            { diagnostics.Add($"profile-layout-unresolved-line:{name}"); continue; }
            if (d.Type.Name.Text == "Line2") guides[name] = new LineArcLineSegment2D(from, to);
            else if (c1 is not null && c2 is not null && points.TryGetValue(c1, out var control1) && points.TryGetValue(c2, out var control2))
                guides[name] = new LineArcCubicBezier2D(from, control1, control2, to);
            else diagnostics.Add($"profile-layout-unresolved-cubic-bezier:{name}");
        }
        foreach (var d in declarations.Where(d => d.Type.Name.Text is "Circle2" or "Ellipse2Guide"))
        {
            var fields = new FirmamentSyntaxFields(d, diagnostics,bind:bind); var name = d.Name!.Text;
            var centerName = fields.Word("Center");
            if (centerName is null || !points.TryGetValue(centerName, out var center)) { diagnostics.Add($"profile-layout-unresolved-circle:{name}"); continue; }
            if (d.Type.Name.Text == "Circle2")
            {
                var radius = fields.Number("Radius", "mm");
                if (radius > 0) guides[name] = new LineArcFullCircle2D(center, radius);
                else diagnostics.Add($"profile-layout-unresolved-circle:{name}");
            }
            else
            {
                var rotation = fields.Number("Rotation", "deg");
                if (fields.Vector("SemiAxes", "mm", out var axes) && axes.Length == 2 && axes[0] >= axes[1] && axes[1] > 0 && double.IsFinite(rotation))
                    guides[name] = new LineArcFullEllipse2D(center, axes[0], axes[1], rotation * Math.PI / 180d);
                else diagnostics.Add($"profile-layout-unresolved-ellipse:{name}");
            }
            fields.Complete();
        }
        // Arc2: the counter-clockwise arc around a named centre from one named point to another on the same circle.
        foreach (var d in declarations.Where(d => d.Type.Name.Text == "Arc2"))
        {
            var fields = new FirmamentSyntaxFields(d, diagnostics,bind:bind); var name = d.Name!.Text;
            var c = fields.Word("Center"); var a = fields.Word("From"); var b = fields.Word("To");
            fields.Complete();
            if (c is null || a is null || b is null || !points.TryGetValue(c, out var center) || !points.TryGetValue(a, out var from) || !points.TryGetValue(b, out var to))
            { diagnostics.Add($"profile-layout-unresolved-arc:{name}"); continue; }
            var radius = Distance(center, from);
            if (radius <= Tolerance || Distance(from, to) <= Tolerance) { diagnostics.Add($"profile-layout-arc-degenerate:{name}"); continue; }
            if (!OnCircle(to, center, radius)) { diagnostics.Add($"profile-layout-arc-radius-mismatch:{name}:{a}:{b}"); continue; }
            var start = Math.Atan2(from.Y - center.Y, from.X - center.X);
            var sweep = Math.Atan2(to.Y - center.Y, to.X - center.X) - start;
            while (sweep <= 0) sweep += 2 * Math.PI;
            while (sweep > 2 * Math.PI) sweep -= 2 * Math.PI;
            guides[name] = new LineArcCircularArc2D(center, radius, start, sweep);
        }
        foreach (var guide in ClosedBoundary2Authoring.SmoothGuides(source, diagnostics)) guides[guide.Key] = guide.Value;
        if (applySpans) ApplyGeometricSpans(source, points, guides, diagnostics, addGuides: true);
    }

    internal static IReadOnlyList<string> ValidateConstructionGuides(string source,Func<ExpressionSyntax,ExpressionSyntax>? bind=null)
    {
        var diagnostics = new List<string>();
        AddOrdinaryGuides(source, new(StringComparer.Ordinal), new(StringComparer.Ordinal), diagnostics, applySpans: false,bind:bind);
        foreach (var layout in SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements)
            .Where(d => d.Type.Name.Text == "Struct" && d.Modifiers.Any(m => m.Name.Text == "Concept") && d.Clauses.Count > 0 && d.Name is not null))
            _ = ResolveConstructionPlane(source, layout.Name!.Text, diagnostics);
        return diagnostics;
    }

    internal static void ValidateProfileBody(DeclarationSyntax profile, List<string> diagnostics)
    {
        if (profile.Body is null) return;
        var fields = new FirmamentSyntaxFields(profile, diagnostics);
        fields.Take("From");
        fields.Complete(profile.Body.Statements.Where(s => s is ExpressionStatementSyntax
            || s is DeclarationSyntax d && (d.Type.Name.Text is "Loop" or "Segment" or "Replace" or "Apply"
                || ClosedBoundary2Authoring.IsBoundaryType(d.Type.Name.Text))).ToHashSet(), admitPlacement: true);
        foreach (var loop in profile.Body.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Loop"))
        {
            var loopFields = new FirmamentSyntaxFields(loop, diagnostics);
            loopFields.Take("From");
            loopFields.Complete((loop.Body?.Statements.Where(s => s is ExpressionStatementSyntax
                || s is DeclarationSyntax d && d.Type.Name.Text == "Segment") ?? []).ToHashSet(), admitPlacement: true);
        }
    }

    private static IEnumerable<DeclarationSyntax> SourceDeclarations(IEnumerable<StatementSyntax> statements)
    {
        foreach (var d in statements.OfType<DeclarationSyntax>())
        {
            if (d.Type.Name.Text == "Template" || d.Modifiers.Any(m => m.Name.Text == "Template")) continue;
            yield return d;
            if (d.Body is not null)
                foreach (var child in SourceDeclarations(d.Body.Statements)) yield return child;
        }
    }

    private static IReadOnlyList<GeometricSpanView> ApplyGeometricSpans(
        string source,
        IReadOnlyDictionary<string, (double X, double Y)> points,
        IDictionary<string, LineArcProfileCurve2D> guides,
        List<string> diagnostics,
        bool addGuides)
    {
        var result = new List<GeometricSpanView>();
        var names = new HashSet<string>(StringComparer.Ordinal);
        foreach (Match header in SpanHeader.Matches(source))
        {
            var open = source.IndexOf('{', header.Index, header.Length);
            var close = FindMatchingBrace(source, open);
            var name = header.Groups["name"].Value;
            var type = header.Groups["type"].Value;
            if (close < 0) { diagnostics.Add($"firmament-span-domain-invalid:{name}"); continue; }
            if (!names.Add(name) || guides.ContainsKey(name)) { diagnostics.Add($"firmament-span-duplicate:{name}"); continue; }
            var body = source[(open + 1)..close];
            var spanSyntax = FirmamentSyntaxParser.Parse("Span " + name + " {" + body + "}").Document.Statements.OfType<DeclarationSyntax>().Single();
            var spanFields = new FirmamentSyntaxFields(spanSyntax, diagnostics);
            string? SpanField(string field) => spanFields.Take(field) is { } expression ? FirmamentSyntaxWriter.Expression(expression) : null;
            var parent = SpanField("On");
            if (parent is null) { diagnostics.Add($"firmament-span-parent-not-found:{name}"); continue; }

            // Plane spans are semantic surface views only in X1: a named, already-authored
            // Profile is their boundary authority. They intentionally do not create a face.
            if (type == "Plane")
            {
                var boundary = SpanField("Boundary");
                var orientation = SpanField("Orientation") ?? "Forward";
                spanFields.Complete();
                var planeDiagnostics = new List<string>();
                var parentPlane = ResolveConstructionPlane(source, parent, planeDiagnostics);
                if (!ConstructionPlanes(source).Any(plane => plane.Name?.Text == parent) || parentPlane is null)
                { diagnostics.Add($"firmament-span-parent-not-found:{name}"); continue; }
                if (boundary is null) { diagnostics.Add($"firmament-span-surface-boundary-open:{name}"); continue; }
                var boundaryProfile = ResolveNamedProfile(source, boundary, out var boundaryDiagnostics);
                if (boundaryProfile is null)
                {
                    diagnostics.Add(boundaryDiagnostics.Any(item => item.Contains("self-intersection", StringComparison.Ordinal))
                        ? $"firmament-span-surface-self-intersection:{name}"
                        : $"firmament-span-surface-boundary-open:{name}");
                    continue;
                }
                // An unqualified XY Profile is interpreted in the parent-local 2D frame by
                // the Span declaration. An explicitly qualified different frame is invalid.
                if (!string.Equals(boundaryProfile.PlaneFrame, "XY", StringComparison.Ordinal)
                    && !string.Equals(boundaryProfile.PlaneFrame, parent, StringComparison.Ordinal)
                    && !IsWorldXyLayout(source, boundaryProfile.PlaneFrame))
                { diagnostics.Add($"firmament-span-surface-boundary-off-parent:{name}"); continue; }
                var area = boundaryProfile.Loops.Sum(loop =>
                    (loop.IsOuter ? 1d : -1d) * Math.Abs(PrismaticSectionStackCompiler.ProfileArea(boundaryProfile with { Loops = [loop] })));
                if (!double.IsFinite(area) || area <= Tolerance) { diagnostics.Add($"firmament-span-surface-domain-invalid:{name}"); continue; }
                var normal = parentPlane.AxisZ.ToVector();
                var consumers = FindSpanConsumers(source, name);
                result.Add(new(name, type, parent, "Plane", $"Boundary:{boundary}", orientation, null, null, boundary, null,
                    $"span:{name};parent:{parent};boundary:{boundary}", Area: area,
                    Normal: orientation == "Reverse" ? [-normal.X, -normal.Y, -normal.Z] : [normal.X, normal.Y, normal.Z],
                    LocalFrame: parentPlane.StableId, ConsumerReferences: consumers, Boundary: boundaryProfile, ParentPlane: parentPlane));
                continue;
            }

            if (type is not ("Line" or "Arc" or "Curve")) { diagnostics.Add($"firmament-span-type-invalid:{type}"); continue; }
            if (!guides.TryGetValue(parent, out var parentGeometry)) { diagnostics.Add($"firmament-span-parent-not-found:{name}"); continue; }
            var parentType = parentGeometry switch { LineArcLineSegment2D => "Line", LineArcFullCircle2D => "Arc", LineArcCircularArc2D => "Arc", _ => parentGeometry.GetType().Name };
            if ((type == "Line" && parentGeometry is not LineArcLineSegment2D) || (type == "Arc" && parentGeometry is not LineArcFullCircle2D and not LineArcCircularArc2D))
            { diagnostics.Add($"firmament-span-type-invalid:{type}"); continue; }
            var fromName = SpanField("From"); var toName = SpanField("To");
            var sweep = SpanField("Sweep") ?? "CounterClockwise";
            var reverse = string.Equals(SpanField("Orientation"), "Reverse", StringComparison.Ordinal);
            spanFields.Complete();
            if (fromName is null || toName is null || !points.TryGetValue(fromName, out var from) || !points.TryGetValue(toName, out var to))
            { diagnostics.Add($"firmament-span-domain-invalid:{name}"); continue; }
            var curve = SelectGuide(parentGeometry, from, to, sweep, name, parent, diagnostics);
            if (curve is null) continue;
            var length = CurveLength(curve);
            if (!double.IsFinite(length) || length <= Tolerance) { diagnostics.Add($"firmament-span-zero-length:{name}"); continue; }
            if (reverse) curve = Reverse(curve);
            var domain = curve switch
            {
                LineArcLineSegment2D => $"Endpoints:{fromName}..{toName}",
                LineArcCircularArc2D arc => $"NativeRadians:{arc.StartAngleRadians:R}..{(arc.StartAngleRadians + arc.SweepAngleRadians):R}",
                _ => "Endpoints"
            };
            var view = new GeometricSpanView(name, type, parent, parentType, domain, reverse ? "Reverse" : "Forward", fromName, toName, null, length, $"span:{name};parent:{parent};parentType:{parentType}", curve);
            result.Add(view);
            if (addGuides) guides[name] = curve;
        }
        return result;
    }

    private static bool IsWorldXyLayout(string source, string frame) =>
        FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document).Any(d=>
            d.Type.Name.Text=="Struct" && d.Modifiers.Any(m=>m.Name.Text=="Concept") && d.Name?.Text==frame
            && d.Clauses.Count==1 && d.Clauses[0].Kind==ClauseKind.On && FirmamentSyntaxValues.Reference(d.Clauses[0].Value)=="XY");

    private static IReadOnlyList<string> FindSpanConsumers(string source, string spanName)
    {
        var consumers = new List<string>();
        foreach (var kind in new[] { "Hole", "Boss", "Pocket", "Fixed", "Force", "Pressure", "Traction" })
        foreach (Match header in Regex.Matches(source, $@"\b{kind}(?:\s*<[^>]+>)?\s+(?<name>[A-Za-z_]\w*)\s*\{{", RegexOptions.CultureInvariant))
        {
            var open = source.IndexOf('{', header.Index, header.Length);
            var close = FindMatchingBrace(source, open);
            if (close > open && string.Equals(Property(source[(open + 1)..close], "On") ?? Property(source[(open + 1)..close], "region"), spanName, StringComparison.Ordinal))
                consumers.Add($"{kind}:{header.Groups["name"].Value}");
        }
        return consumers.Order(StringComparer.Ordinal).ToArray();
    }

    private static double CurveLength(LineArcProfileCurve2D curve) => curve switch
    {
        LineArcLineSegment2D line => Distance(line.Start, line.End),
        LineArcCircularArc2D arc => Math.Abs(arc.Radius * arc.SweepAngleRadians),
        _ => double.NaN
    };

    /// <summary>
    /// The plane a straight Path step, or a named straight outer edge of a traced Profile, sweeps when extruded along
    /// the sketch normal, written as the explicit Concept plane an author would declare: origin at the foot of the
    /// sketch origin on the edge's line, normal pointing into the material (to the left of a counter-clockwise loop),
    /// up along +Z. It is computed from source alone, so the plane moves with the outline and never refers to a body
    /// face.
    /// </summary>
    internal static bool TryDerivePathStepPlane(string source, string path, string step, out ConceptIrPlaneValue? plane, out string? diagnostic)
    {
        plane = null; diagnostic = null;
        var diagnostics = new List<string>();
        var paths = BindPaths(source, new(StringComparer.Ordinal), new(StringComparer.Ordinal), diagnostics);
        if (paths.TryGetValue(path, out var bound))
        {
            var boundStep = bound.Steps.FirstOrDefault(s => s.Name == step);
            if (boundStep is null) { diagnostic = $"path-step-plane-step-unknown:{path}.{step}: Path '{path}' has no step '{step}'."; return false; }
            if (boundStep.Curves is not [LineArcLineSegment2D pathLine]) { diagnostic = $"path-step-plane-not-straight:{path}.{step}: only a straight Line step sweeps a plane."; return false; }
            var pathCurves = bound.Steps.SelectMany(s => s.Curves).ToArray();
            if (!IsClosed(pathCurves)) { diagnostic = $"path-step-plane-path-open:{path}.{step}: the Path must be closed for its inside to be known."; return false; }
            plane = SweptPlane(pathLine, SignedArea(pathCurves) > 0, $"Path step {path}.{step}", $"path-step:{path}.{step}");
            return true;
        }

        // A named straight edge of a closed Profile's outer loop (for example one traced with `as Front`)
        // sweeps the same plane; the Profile must lie in the XY sketch, as an extruded Path does.
        var profiles = BindPathDerivedProfiles(source, diagnostics);
        if (!profiles.TryGetValue(path, out var profile))
        { diagnostic = $"path-step-plane-path-unknown:{path}.{step}: '{path}' is not a Path or a traced Profile in this model."; return false; }
        if (profile.ConstructionPlane is { } frame && frame != ConstructionPlane.WorldXY)
        { diagnostic = $"path-step-plane-profile-not-xy:{path}.{step}: only a Profile in the XY sketch sweeps a plane along +Z."; return false; }
        var outer = profile.Loops.FirstOrDefault(l => l.IsOuter);
        var segment = outer?.Segments.FirstOrDefault(s => s.Name == step);
        if (outer is null || segment is null)
        { diagnostic = $"path-step-plane-step-unknown:{path}.{step}: Profile '{path}' has no outer-loop edge named '{step}'."; return false; }
        if (segment.Geometry is not LineArcLineSegment2D edgeLine) { diagnostic = $"path-step-plane-not-straight:{path}.{step}: only a straight edge sweeps a plane."; return false; }
        plane = SweptPlane(edgeLine, SignedArea(outer.Segments.Select(s => s.Geometry)) > 0, $"Profile edge {path}.{step}", $"profile-edge:{path}.{step}");
        return true;
    }

    /// <summary>The plane a straight edge sweeps along +Z: origin at the foot of the sketch origin on the edge's line,
    /// normal into the material (left of a counter-clockwise loop), up +Z.</summary>
    private static ConceptIrPlaneValue SweptPlane(LineArcLineSegment2D line, bool counterClockwise, string provenance, string stableId)
    {
        var dx = line.End.X - line.Start.X; var dy = line.End.Y - line.Start.Y; var length = Math.Sqrt(dx * dx + dy * dy);
        dx /= length; dy /= length;
        var inward = counterClockwise ? (X: -dy, Y: dx) : (X: dy, Y: -dx);
        var along = -(line.Start.X * dx + line.Start.Y * dy);
        var foot = (X: line.Start.X + dx * along, Y: line.Start.Y + dy * along);
        return new ConceptIrPlaneValue(stableId, new(foot.X, foot.Y, 0d), new(inward.X, inward.Y, 0d), $"derived from {provenance}", new(0d, 0d, 1d));
    }

    private static IReadOnlyDictionary<string, BoundPath> BindPaths(string source, Dictionary<string, (double X, double Y)> points, Dictionary<string, LineArcProfileCurve2D> guides, List<string> diagnostics)
    {
        var result = new Dictionary<string, BoundPath>(StringComparer.Ordinal);
        foreach (var declaration in SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements)
            .Where(d => d.Type.Name.Text == "Path"))
        {
            var name = declaration.Name?.Text ?? "<unnamed>";
            if (declaration.Name is null || declaration.Body is null || declaration.Modifiers.Any(m => m.Name.Text != "Concept")
                || declaration.Type.Arguments.Count > 0 || declaration.Parameters.Count > 0 || declaration.Annotation is not null
                || declaration.Initializer is not null || declaration.ResultType is not null || declaration.Clauses.Count > 0)
            { diagnostics.Add($"concept-path-header-invalid:{name}"); continue; }
            var content = declaration.Body.ContentSpan;
            var pathBody = source.Substring(content.Start, content.Length);
            var pathFields = new FirmamentSyntaxFields(declaration with { Modifiers = [] }, diagnostics);
            var startExpression = pathFields.Take("Start");
            var headingExpression = pathFields.Take("Heading");
            var recognizedSteps = FindPathSteps(pathBody).Select(s => content.Start + s.Index).ToHashSet();
            var steps = declaration.Body.Statements.Where(s => s is DeclarationSyntax d && recognizedSteps.Contains(d.Span.Start)
                || s is ExpressionStatementSyntax).ToHashSet();
            pathFields.Complete(steps);
            if (!result.TryAdd(name, default!)) { diagnostics.Add($"concept-path-duplicate:{name}"); continue; }
            if (pathBody.Contains("|>", StringComparison.Ordinal))
            {
                var pipelinePath = BindPathPipeline(name, pathBody, points, guides, diagnostics);
                if (pipelinePath is not null)
                {
                    result[name] = pipelinePath;
                    points[$"{name}.Start"] = pipelinePath.Start;
                    foreach (var step in pipelinePath.Steps)
                    {
                        if (step.Curves.Count == 1) guides[$"{name}.{step.Name}"] = step.Curves[0];
                        points[$"{name}.{step.Name}.End"] = step.End;
                    }
                }
                continue;
            }
            if (!FirmamentSyntaxValues.Vector(startExpression, "mm", out var startCoordinates) || startCoordinates.Length != 2
                || startCoordinates.Any(n => !double.IsFinite(n))) { diagnostics.Add($"concept-path-start-invalid:{name}"); continue; }
            var heading = 0d;
            if (headingExpression is not null && (!FirmamentSyntaxValues.TryMeasure(headingExpression, "deg", out heading) || !double.IsFinite(heading))) { diagnostics.Add($"concept-path-heading-invalid:{name}"); continue; }
            var path = new BoundPath(name, (startCoordinates[0], startCoordinates[1]), heading, []);
            if (points.ContainsKey($"{name}.Start") || guides.ContainsKey(name)) { diagnostics.Add($"concept-path-name-collision:{name}"); continue; }
            points[$"{name}.Start"] = path.Start;
            var current = path.Start;
            foreach (var step in FindPathSteps(pathBody))
            {
                if (path.Steps.Any(x => x.Name == step.Name)) { diagnostics.Add($"concept-path-duplicate-step:{name}:{step.Name}"); continue; }
                var guideName = $"{name}.{step.Name}";
                var endpointName = $"{guideName}.End";
                if (guides.ContainsKey(guideName) || points.ContainsKey(endpointName)) { diagnostics.Add($"concept-path-name-collision:{guideName}"); continue; }
                // A path whose last step already returns to the start needs no closing edge: Close then only marks
                // the loop closed, adds no segment and names no guide.
                if (step.Kind == "Close" && path.Steps.Count > 0 && Distance(current, path.Start) <= Tolerance) { points[endpointName] = path.Start; continue; }
                if (!TryBindStep(name, step, current, ref heading, path.Start, points, out var curves, out var endpoint, out var diagnostic)) { diagnostics.Add(diagnostic!); continue; }
                if (curves!.Count == 1) guides[guideName] = curves[0];
                points[endpointName] = endpoint; path.Steps.Add(new BoundPathStep(step.Name, step.Kind == "Line" ? "Span" : step.Kind == "Arc" ? "ArcTransition" : step.Kind, guideName, endpointName, curves, current, endpoint, heading)); current = endpoint;
            }
            result[name] = path;
        }
        BindRectEdgeProfiles(source, result, diagnostics);
        return result;
    }

    private static void BindRectEdgeProfiles(string source, Dictionary<string, BoundPath> result, List<string> diagnostics)
    {
        var programs = FindBlocks(source, @"\bEdgeProfile\s+(?<owner>[A-Za-z_]\w*)\.(?<edge>[A-Za-z_]\w*)\s*\{").ToArray();
        var parsedDeltas=SemanticProfileDeltaParser.Parse(source);
        diagnostics.AddRange(parsedDeltas.Diagnostics);
        var cornerPrograms = FindBlocks(source, @"\bCornerProfile\s+(?<owner>[A-Za-z_]\w*)\.(?<corner>[A-Za-z_]\w*)\s*\{").ToArray();
        var declarations = SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).ToArray();
        foreach (var rectangle in declarations.Where(d => d.Type.Name.Text == "Rect2" && d.Name is not null))
        {
            var name = rectangle.Name!.Text;
            var isProfileSource = declarations.Any(d => d.Type.Name.Text == "Profile"
                && d.Clauses.Any(c => c.Kind == ClauseKind.From && FirmamentSyntaxValues.Reference(c.Value) == name));
            if (!isProfileSource && !programs.Any(x => x.Match.Groups["owner"].Value == name) && !cornerPrograms.Any(x => x.Match.Groups["owner"].Value == name)
                &&!parsedDeltas.Deltas.Any(delta=>delta.OwnerPath.StartsWith(name+".",StringComparison.Ordinal))) continue;
            var fields = new FirmamentSyntaxFields(rectangle, diagnostics);
            if (!fields.Vector("Size", "mm", out var size) || size.Length != 2 || !fields.Vector("Center", "mm", out var center) || center.Length != 2) continue;
            var width = size[0]; var height = size[1]; var cx = center[0]; var cy = center[1];
            if (result.ContainsKey(name)) { diagnostics.Add($"profile-edge-owner-name-collision:{name}"); continue; }
            var bl = (X: cx - width / 2, Y: cy - height / 2); var br = (X: cx + width / 2, Y: cy - height / 2);
            var tr = (X: cx + width / 2, Y: cy + height / 2); var tl = (X: cx - width / 2, Y: cy + height / 2);
            var path = new BoundPath(name, bl, 0, []);
            var edges = new Dictionary<string, ((double X, double Y) Start, (double X, double Y) End)>(StringComparer.Ordinal)
            {
                ["Bottom"] = (bl, br), ["Right"] = (br, tr), ["Top"] = (tr, tl), ["Left"] = (tl, bl)
            };
            var cornerEdges = new Dictionary<string, (string EdgeA, string EdgeB)>(StringComparer.Ordinal)
            {
                ["BottomRight"] = ("Bottom", "Right"), ["TopRight"] = ("Right", "Top"),
                ["TopLeft"] = ("Top", "Left"), ["BottomLeft"] = ("Left", "Bottom")
            };
            var resolvedCorners = new Dictionary<string, ResolvedSemanticCornerProfileIr>(StringComparer.Ordinal);
            foreach (var corner in cornerEdges)
            {
                var matching = cornerPrograms.Where(x => x.Match.Groups["owner"].Value == name && x.Match.Groups["corner"].Value == corner.Key).ToArray();
                if (matching.Length == 0) continue;
                if (matching.Length > 1) { diagnostics.Add($"semantic-corner-duplicate-program:{name}.{corner.Key}"); continue; }
                var operations = FindBlocks(matching[0].Body, @"\b(?<kind>Chamfer|Cutback|Taper|NotchCorner)\s+(?<name>[A-Za-z_]\w*)\s*\{").ToArray();
                if (operations.Length != 1) { diagnostics.Add($"semantic-corner-operation-required:{name}.{corner.Key}"); continue; }
                var operation = operations[0]; var operationName = operation.Match.Groups["name"].Value; var operationKind = operation.Match.Groups["kind"].Value;
                var equal = Property(operation.Body, "Setback"); var aText = Property(operation.Body, "SetbackA") ?? equal; var bText = Property(operation.Body, "SetbackB") ?? equal;
                var operationId = $"{name}.{corner.Key}.{operationName}";
                if (aText is null || bText is null || !TryMeasure(aText, "mm", out var setbackA) || !TryMeasure(bText, "mm", out var setbackB))
                { diagnostics.Add($"semantic-corner-setbacks-required:{operationId}"); continue; }
                var pair = corner.Value; var edgeA = edges[pair.EdgeA]; var edgeB = edges[pair.EdgeB];
                SemanticCornerOperationIr authored = operationKind switch
                {
                    "Chamfer" => new SemanticCornerChamferIr(operationName, operationId, setbackA, setbackB, $"offset:{operation.Match.Index}"),
                    "Cutback" => new SemanticCornerCutbackIr(operationName, operationId, setbackA, setbackB, $"offset:{operation.Match.Index}"),
                    "Taper" => new SemanticCornerTaperIr(operationName, operationId, setbackA, setbackB, $"offset:{operation.Match.Index}"),
                    "NotchCorner" => new SemanticCornerNotchIr(operationName, operationId, setbackA, setbackB, $"offset:{operation.Match.Index}"),
                    _ => throw new InvalidOperationException()
                };
                var cornerPath = $"{name}.{corner.Key}";
                var resolution = SemanticCornerProfileResolver.Resolve(new(cornerPath, cornerPath, $"{name}.{pair.EdgeA}", $"{name}.{pair.EdgeB}",
                    new(edgeA.Start.X, edgeA.Start.Y), new(edgeA.End.X, edgeA.End.Y), new(edgeB.End.X, edgeB.End.Y), authored,
                    $"{cornerPath}[u=away-on-{pair.EdgeA},v=away-on-{pair.EdgeB}]", $"CornerProfile {cornerPath}"));
                if (!resolution.IsSuccess) diagnostics.AddRange(resolution.Diagnostics);
                else resolvedCorners[corner.Key] = resolution.Corner!;
            }
            AddEdge("Bottom", bl, br); AddEdge("Right", br, tr); AddEdge("Top", tr, tl); AddEdge("Left", tl, bl);
            result[name] = path;

            void AddEdge(string edge, (double X, double Y) start, (double X, double Y) end)
            {
                var matching = programs.Where(x => x.Match.Groups["owner"].Value == name && x.Match.Groups["edge"].Value == edge).ToArray();
                var startCorner = cornerEdges.First(x => x.Value.EdgeB == edge).Key;
                var endCorner = cornerEdges.First(x => x.Value.EdgeA == edge).Key;
                resolvedCorners.TryGetValue(startCorner, out var startResolution);
                resolvedCorners.TryGetValue(endCorner, out var endResolution);
                var edgeDeltas=parsedDeltas.Deltas.Where(delta=>delta.OwnerPath.Equals($"{name}.{edge}",StringComparison.Ordinal)).ToArray();
                if (matching.Length == 0 && edgeDeltas.Length==0 && startResolution is null && endResolution is null)
                {
                    path.Steps.Add(new(edge, "Span", $"{name}.{edge}", $"{name}.{edge}.End", [new LineArcLineSegment2D(start, end)], start, end, Heading(start, end)));
                    return;
                }
                if (matching.Length > 1) { diagnostics.Add($"semantic-edge-duplicate-program:{name}.{edge}"); return; }
                var fragments = new List<SemanticEdgeFragmentIr>();
                foreach(var parsed in edgeDeltas)
                {
                    var id=$"{name}.{edge}.{parsed.Delta.Name}";
                    fragments.Add(parsed.Delta with { StableId=id,Side=-parsed.Delta.Side,
                        Levels=parsed.Delta.Levels.Select(level=>level with { StableId=$"{id}.{level.Name}" }).ToArray(),
                        Members=parsed.Delta.Members.Select(member=>member with { StableId=$"{id}.{member.Name}",ExposeAs=member.ExposeAs is null?null:$"{id}.{member.ExposeAs.Split('.').Last()}" }).ToArray() });
                }
                foreach (var step in matching.Length == 0 ? Enumerable.Empty<PathStep>() : FindPathSteps(matching[0].Body).Where(x => x.Kind is "Chamfer" or "Step" or "Notch" or "Cutback" or "Tab"))
                {
                    var id = $"{name}.{edge}.{step.Name}";
                    var anchors = new[] { ("FromStart", SemanticEdgeAnchorKind.FromStart), ("FromEnd", SemanticEdgeAnchorKind.FromEnd), ("CenteredAt", SemanticEdgeAnchorKind.CenteredAt) }
                        .Select(x => (x.Item2, Value: Property(step.Body, x.Item1))).Where(x => x.Value is not null).ToArray();
                    if (anchors.Length != 1 || !TryMeasure(anchors[0].Value!, "mm", out var offset)) { diagnostics.Add($"semantic-edge-anchor-required:{id}"); continue; }
                    var sideText = Property(step.Body, "Side"); var side = sideText?.Equals("Left", StringComparison.OrdinalIgnoreCase) == true ? 1 : sideText?.Equals("Right", StringComparison.OrdinalIgnoreCase) == true ? -1 : 0;
                    bool Measure(string property, out double value) { value = default; var text = Property(step.Body, property); return text is not null && TryMeasure(text, "mm", out value); }
                    var anchor = new SemanticEdgeAnchorIr(anchors[0].Item1, offset); SemanticEdgeFragmentIr? fragment = null;
                    if (step.Kind == "Tab" && Measure("Width", out var tabWidth) && Measure("Extension", out var extension)) fragment = new SemanticEdgeTabIr(step.Name, id, anchor, tabWidth, extension, side, $"offset:{step.Index}");
                    else if (step.Kind == "Notch" && Measure("Width", out var notchWidth) && Measure("Depth", out var depth)) fragment = new SemanticEdgeNotchIr(step.Name, id, anchor, notchWidth, depth, side, $"offset:{step.Index}");
                    else if (step.Kind == "Step" && Measure("Width", out var stepWidth) && Measure("Rise", out var rise)) fragment = new SemanticEdgeStepIr(step.Name, id, anchor, stepWidth, rise, side, $"offset:{step.Index}");
                    else if (step.Kind == "Chamfer" && Measure("Run", out var chamferRun) && Measure("Offset", out var chamferOffset)) fragment = new SemanticEdgeChamferIr(step.Name, id, anchor, chamferRun, chamferOffset, side, $"offset:{step.Index}");
                    else if (step.Kind == "Cutback" && Measure("Run", out var cutbackRun) && Measure("Offset", out var cutbackOffset)) fragment = new SemanticEdgeCutbackIr(step.Name, id, anchor, cutbackRun, cutbackOffset, side, $"offset:{step.Index}");
                    else diagnostics.Add($"semantic-edge-fragment-properties-invalid:{id}:{step.Kind}");
                    if (fragment is not null) fragments.Add(fragment);
                }
                var consumption = new SemanticEdgeEndpointConsumptionIr(
                    startResolution?.EdgeBConsumption ?? 0d, endResolution?.EdgeAConsumption ?? 0d,
                    startResolution?.Source.CornerPath, endResolution?.Source.CornerPath);
                var resolution = SemanticEdgeProfileResolver.Resolve(new($"{name}.{edge}", $"{name}.{edge}", new(start.X, start.Y), new(end.X, end.Y), fragments, $"{name}.{edge}[u,v]", $"EdgeProfile {name}.{edge}"), consumption);
                if (!resolution.IsSuccess) { diagnostics.AddRange(resolution.Diagnostics); return; }
                foreach (var member in resolution.Profile!.OrderedMembers)
                {
                    if(member.Kind=="ProfileDelta")
                    {
                        foreach(var descendant in member.CurveDescendants)
                        {
                            var curveStart=Start(descendant.Geometry);var curveEnd=End(descendant.Geometry);var leaf=descendant.StableId.EndsWith(".curve00",StringComparison.Ordinal)?descendant.StableId[..^8]:descendant.StableId;
                            path.Steps.Add(new($"{edge}.{leaf}","ProfileDeltaMember",leaf,$"{leaf}.End",[descendant.Geometry],curveStart,curveEnd,Heading(curveStart,curveEnd)));
                        }
                        continue;
                    }
                    var first = ((LineArcLineSegment2D)member.CurveDescendants.First().Geometry).Start; var last = ((LineArcLineSegment2D)member.CurveDescendants.Last().Geometry).End;
                    path.Steps.Add(new($"{edge}.{member.Name}", member.Kind, $"{name}.{edge}.{member.Name}", $"{name}.{edge}.{member.Name}.End", member.CurveDescendants.Select(x => x.Geometry).ToArray(), first, last, Heading(first, last)));
                }
                if (endResolution is not null)
                {
                    var member = endResolution.Source.Operation; var first = ((LineArcLineSegment2D)endResolution.CurveDescendants.First().Geometry).Start; var last = ((LineArcLineSegment2D)endResolution.CurveDescendants.Last().Geometry).End;
                    path.Steps.Add(new($"{endCorner}.{member.Name}", member.Kind, member.StableId, $"{member.StableId}.End", endResolution.CurveDescendants.Select(x => x.Geometry).ToArray(), first, last, Heading(first, last)));
                }
            }
        }
        foreach (var program in programs.Where(p => !result.ContainsKey(p.Match.Groups["owner"].Value)))
            diagnostics.Add($"semantic-edge-owner-path-missing:{program.Match.Groups["owner"].Value}.{program.Match.Groups["edge"].Value}");
        foreach (var program in programs.Where(p => result.ContainsKey(p.Match.Groups["owner"].Value) && p.Match.Groups["edge"].Value is not ("Bottom" or "Right" or "Top" or "Left")))
            diagnostics.Add($"semantic-edge-owner-member-missing:{program.Match.Groups["owner"].Value}.{program.Match.Groups["edge"].Value}:available=Bottom,Right,Top,Left");
        foreach (var program in cornerPrograms.Where(p => !result.ContainsKey(p.Match.Groups["owner"].Value)))
            diagnostics.Add($"semantic-corner-owner-path-missing:{program.Match.Groups["owner"].Value}.{program.Match.Groups["corner"].Value}");
        foreach (var program in cornerPrograms.Where(p => result.ContainsKey(p.Match.Groups["owner"].Value) && p.Match.Groups["corner"].Value is not ("BottomRight" or "TopRight" or "TopLeft" or "BottomLeft")))
            diagnostics.Add($"semantic-corner-owner-member-missing:{program.Match.Groups["owner"].Value}.{program.Match.Groups["corner"].Value}:available=BottomRight,TopRight,TopLeft,BottomLeft");
    }

    private static bool TryBindStep(string path, PathStep step, (double X, double Y) current, ref double headingDegrees, (double X, double Y) start, IReadOnlyDictionary<string, (double X, double Y)> points, out IReadOnlyList<LineArcProfileCurve2D>? curves, out (double X, double Y) endpoint, out string? diagnostic)
    {
        curves = null; endpoint = default; diagnostic = null;
        var prefix = $"concept-path-{step.Kind.ToLowerInvariant()}-invalid:{path}:{step.Name}";
        if (step.Kind == "Close")
        {
            endpoint = start;
            if (Distance(current, endpoint) <= Tolerance) { diagnostic = $"concept-path-zero-length:{path}:{step.Name}"; return false; }
            curves = [new LineArcLineSegment2D(current, endpoint)]; headingDegrees = Heading(current, endpoint); return true;
        }
        var body = step.Body;
        Dictionary<string, string?>? boundFields = null;
        if (step.Kind is "Line" or "Span" or "Arc")
        {
            // Read the same AST fields after compile-time serialization as before it.
            // Casing and whitespace must not change path geometry or drop a value.
            string[] allowed = step.Kind == "Arc" ? ["Radius", "Turn"] : ["Turn", "Heading", "Length", "To"];
            var syntax = FirmamentSyntaxParser.Parse("Step PathStep {" + body + "}");
            var declaration = syntax.Document.Statements.OfType<DeclarationSyntax>().SingleOrDefault();
            if (!syntax.IsSuccess || declaration?.Body is null || declaration.Body.Statements.Any(s => s is not FieldSyntax))
            { diagnostic = prefix + ":expected-field-body"; return false; }
            var unknown = declaration.Body.Statements.OfType<FieldSyntax>().Select(f => f.Name.Text)
                .FirstOrDefault(n => !allowed.Any(a => FirmamentSyntaxFields.SameField(n, a)));
            if (unknown is not null) { diagnostic = $"concept-path-field-unknown:{path}:{step.Name}:{unknown}:allowed={string.Join(",", allowed)}"; return false; }
            var fieldDiagnostics = new List<string>(); var fields = new FirmamentSyntaxFields(declaration, fieldDiagnostics);
            boundFields = allowed.ToDictionary(n => n, n => fields.Take(n) is { } value ? FirmamentSyntaxWriter.Expression(value) : null);
            fields.Complete();
            if (fieldDiagnostics.Count > 0) { diagnostic = prefix + ":" + string.Join("; ", fieldDiagnostics); return false; }
        }
        string? Read(string name) => boundFields is null ? Property(body, name) : boundFields.GetValueOrDefault(name);
        var turn = Read("Turn"); var absolute = Read("Heading"); var length = Read("Length"); var to = Read("To");
        if (step.Kind is "Line" or "Span")
        {
            if (turn is not null && absolute is not null) { diagnostic = $"concept-path-turn-and-heading:{path}:{step.Name}"; return false; }
            if (to is not null && (length is not null || turn is not null || absolute is not null)) { diagnostic = $"concept-path-to-mixed-direction-or-length:{path}:{step.Name}"; return false; }
            if (to is not null)
            {
                var targetName = string.Equals(to, "Start", StringComparison.Ordinal) ? $"{path}.Start" : to;
                if (!points.TryGetValue(targetName, out endpoint)) { diagnostic = $"concept-path-unknown-target:{path}:{step.Name}:{to}"; return false; }
                if (Distance(current, endpoint) <= Tolerance) { diagnostic = $"concept-path-zero-length:{path}:{step.Name}"; return false; }
                curves = [new LineArcLineSegment2D(current, endpoint)]; headingDegrees = Heading(current, endpoint); return true;
            }
            if (length is null || !TryMeasure(length, "mm", out var distance) || distance <= 0) { diagnostic = $"concept-path-length-invalid:{path}:{step.Name}"; return false; }
            if (turn is not null) { if (!TryMeasure(turn, "deg", out var degrees) || !double.IsFinite(degrees)) { diagnostic = prefix; return false; } headingDegrees += degrees; }
            else if (absolute is not null) { if (!TryMeasure(absolute, "deg", out var degrees) || !double.IsFinite(degrees)) { diagnostic = prefix; return false; } headingDegrees = degrees; }
            endpoint = Advance(current, headingDegrees, distance); curves = [new LineArcLineSegment2D(current, endpoint)]; return true;
        }
        if (step.Kind is "Chamfer" or "Cutback" or "Step" or "Notch" or "Tab")
        {
            if (!TrySemanticFeature(path, step, current, headingDegrees, out curves, out endpoint, out diagnostic)) return false;
            return true;
        }
        var radiusText = Read("Radius");
        if (step.Kind != "Arc" || radiusText is null || turn is null || absolute is not null || length is not null || to is not null || !TryMeasure(radiusText, "mm", out var radius) || radius <= 0 || !TryMeasure(turn, "deg", out var sweepDegrees) || !double.IsFinite(sweepDegrees) || Math.Abs(sweepDegrees) <= Tolerance || Math.Abs(sweepDegrees) >= 360d - Tolerance)
        { diagnostic = $"concept-path-arc-invalid:{path}:{step.Name}"; return false; }
        var headingRadians = DegreesToRadians(headingDegrees); var sweepRadians = DegreesToRadians(sweepDegrees); var sign = Math.Sign(sweepRadians);
        (double X, double Y) center = (current.X - sign * radius * Math.Sin(headingRadians), current.Y + sign * radius * Math.Cos(headingRadians));
        var startAngle = Math.Atan2(current.Y - center.Y, current.X - center.X);
        curves = [new LineArcCircularArc2D(center, radius, startAngle, sweepRadians)];
        endpoint = (center.Item1 + radius * Math.Cos(startAngle + sweepRadians), center.Item2 + radius * Math.Sin(startAngle + sweepRadians));
        headingDegrees += sweepDegrees;
        return true;
    }

    private static bool TrySemanticFeature(string path, PathStep step, (double X, double Y) current, double headingDegrees, out IReadOnlyList<LineArcProfileCurve2D>? curves, out (double X, double Y) endpoint, out string? diagnostic)
    {
        curves = null; endpoint = default; diagnostic = null;
        var stableId = $"concept-path:{path}.{step.Name}";
        var sideText = Property(step.Body, "Side");
        var side = string.Equals(sideText, "Left", StringComparison.OrdinalIgnoreCase) ? 1
            : string.Equals(sideText, "Right", StringComparison.OrdinalIgnoreCase) ? -1 : 0;
        bool Measure(string name, out double value)
        {
            value = default;
            var text = Property(step.Body, name);
            return text is not null && TryMeasure(text, "mm", out value);
        }

        SemanticProfileMemberIr? member = null;
        if (step.Kind is "Chamfer" or "Cutback")
        {
            if (!Measure("Run", out var run) || !Measure("Offset", out var offset))
            { diagnostic = $"semantic-profile-invalid-{step.Kind.ToLowerInvariant()}:{stableId}:Run and Offset are required"; return false; }
            member = step.Kind == "Chamfer"
                ? new SemanticProfileChamferIr(step.Name, stableId, run, offset, side, $"offset:{step.Index}")
                : new SemanticProfileCutbackIr(step.Name, stableId, run, offset, side, $"offset:{step.Index}");
        }
        else if (step.Kind == "Step")
        {
            if (!Measure("Run", out var run) || !Measure("Rise", out var rise))
            { diagnostic = $"semantic-profile-invalid-step:{stableId}:Run and Rise are required"; return false; }
            member = new SemanticProfileStepIr(step.Name, stableId, run, rise, side, $"offset:{step.Index}");
        }
        else if (step.Kind == "Notch")
        {
            if (!Measure("Width", out var width) || !Measure("Depth", out var depth))
            { diagnostic = $"semantic-profile-invalid-notch:{stableId}:Width and Depth are required"; return false; }
            member = new SemanticProfileNotchIr(step.Name, stableId, width, depth, side, $"offset:{step.Index}");
        }
        else if (step.Kind == "Tab")
        {
            if (!Measure("Width", out var width) || !Measure("Extension", out var extension))
            { diagnostic = $"semantic-profile-invalid-tab:{stableId}:Width and Extension are required"; return false; }
            member = new SemanticProfileTabIr(step.Name, stableId, width, extension, side, $"offset:{step.Index}");
        }

        var ir = new SemanticProfileIr(path, "concept-path:" + path, "XY", new(current.X, current.Y), headingDegrees,
            [member!], [], [], "Firmament Concept Path semantic member");
        var resolution = SemanticProfileMirResolver.Resolve(ir);
        if (!resolution.IsSuccess)
        {
            diagnostic = resolution.Diagnostics.FirstOrDefault() ?? $"semantic-profile-member-unresolved:{stableId}";
            return false;
        }
        var resolved = AssertSingle(resolution.Profile!.Members);
        curves = resolved.CurveDescendants.Select(descendant => descendant.Geometry).ToArray();
        endpoint = (resolved.End.X, resolved.End.Y);
        return true;

        static ResolvedSemanticProfileMemberIr AssertSingle(IReadOnlyList<ResolvedSemanticProfileMemberIr> members) =>
            members.Count == 1 ? members[0] : throw new InvalidOperationException("A bounded semantic feature must resolve to exactly one semantic member.");
    }

    private static IReadOnlyList<ResolvedProfileLoop2D> BindProfileLoops(ProfileBlock profile, IReadOnlyDictionary<string, BoundPath> paths, IReadOnlyDictionary<string, (double X, double Y)> points, IReadOnlyDictionary<string, LineArcProfileCurve2D> guides, List<string> diagnostics)
    {
        var loops = new List<ResolvedProfileLoop2D>();
        if (profile.FromPath is not null) { AddPathLoop("Outer", true, profile.FromPath, profile, paths, loops, diagnostics); return loops; }
        var loopBlocks = FindBlocks(profile.Body ?? string.Empty, @"\bLoop\s+(?<name>[A-Za-z_]\w*)(?:\s+From\s+(?<path>[A-Za-z_]\w*))?\s*\{").ToList();
        var blockLoopNames = new HashSet<string>(loopBlocks.Select(x => x.Match.Groups["name"].Value), StringComparer.Ordinal);
        foreach (Match loop in Regex.Matches(profile.Body ?? string.Empty, @"\bLoop\s+(?<name>[A-Za-z_]\w*)\s+From\s+(?<path>[A-Za-z_]\w*)\b(?!\s*\{)", RegexOptions.CultureInvariant))
            if (blockLoopNames.Add(loop.Groups["name"].Value))
                AddPathLoop(loop.Groups["name"].Value, string.Equals(loop.Groups["name"].Value, "Outer", StringComparison.Ordinal), loop.Groups["path"].Value, profile, paths, loops, diagnostics);
        foreach (var loop in loopBlocks)
        {
            var loopSyntax = FirmamentSyntaxParser.Parse("Loop " + loop.Match.Groups["name"].Value + " {" + loop.Body + "}")
                .Document.Statements.OfType<DeclarationSyntax>().Single();
            var loopFields = new FirmamentSyntaxFields(loopSyntax, diagnostics);
            loopFields.Take("From");
            loopFields.Complete((loopSyntax.Body?.Statements.Where(s => s is ExpressionStatementSyntax
                || s is DeclarationSyntax d && d.Type.Name.Text == "Segment") ?? []).ToHashSet());
            var loopName = loop.Match.Groups["name"].Value; var fromPath = loop.Match.Groups["path"].Success ? loop.Match.Groups["path"].Value : null;
            var fromInsideMatch = Regex.Match(loop.Body, @"^\s*From\s*:\s*(?<path>[A-Za-z_]\w*)\b", RegexOptions.CultureInvariant);
            var fromInside = fromInsideMatch.Success ? fromInsideMatch.Groups["path"].Value : null;
            if (fromPath is not null || fromInside is not null) { AddPathLoop(loopName, string.Equals(loopName, "Outer", StringComparison.Ordinal), fromPath ?? fromInside!, profile, paths, loops, diagnostics); continue; }
            loops.Add(new ResolvedProfileLoop2D(loopName, string.Equals(loopName, "Outer", StringComparison.Ordinal), BindSegments(profile, loopName, loop.Body, paths, points, guides, diagnostics)));
        }
        // The first Profile frontend permitted direct segments without an explicit Loop.
        if (loops.Count == 0 && !string.IsNullOrWhiteSpace(profile.Body))
            loops.Add(new ResolvedProfileLoop2D("Outer", true, BindSegments(profile, "Outer", profile.Body, paths, points, guides, diagnostics)));
        if (loops.Count == 0) diagnostics.Add($"profile-loop-missing:{profile.Name}");
        foreach (var collision in loops.SelectMany(loop => loop.Segments.Select(segment => (Loop: loop.Name, Segment: segment.Name)))
                     .GroupBy(entry => entry.Segment, StringComparer.Ordinal).Where(group => group.Select(entry => entry.Loop).Distinct(StringComparer.Ordinal).Count() > 1))
        {
            var loopNames = collision.Select(entry => entry.Loop).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal);
            diagnostics.Add($"firmament-profile-segment-identity-collision:{collision.Key}:loops={string.Join(',', loopNames)}:use as alias or rename source guide/stage");
        }
        return loops;
    }

    private static IReadOnlyList<ResolvedProfileSegment2D> BindSegments(ProfileBlock profile, string loopName, string body, IReadOnlyDictionary<string, BoundPath> paths, IReadOnlyDictionary<string, (double X, double Y)> points, IReadOnlyDictionary<string, LineArcProfileCurve2D> guides, List<string> diagnostics)
    {
        if (!body.Contains("|>", StringComparison.Ordinal)) return BindLowLevelSegments(profile, loopName, body, points, guides, diagnostics);
        if (Segment.IsMatch(body))
        {
            diagnostics.Add($"firmament-profile-pipeline-mixed-authoring:{profile.Name}:{loopName}");
            return [];
        }
        var expression = ReadPipeline(MaskRecognizedProfileDeclarations(body));
        if (expression is null)
        {
            diagnostics.Add($"firmament-profile-pipeline-expression-required:{profile.Name}:{loopName}");
            return [];
        }
        return BindProfilePipeline(profile, loopName, expression, paths, points, guides, diagnostics);
    }

    private static IReadOnlyList<ResolvedProfileSegment2D> BindProfilePipeline(ProfileBlock profile, string loopName, ExpressionSyntax expression, IReadOnlyDictionary<string, BoundPath> paths, IReadOnlyDictionary<string, (double X, double Y)> points, IReadOnlyDictionary<string, LineArcProfileCurve2D> guides, List<string> diagnostics)
    {
        var stages = ParsePipelineStages(expression);
        if (stages.Count == 2 && stages[1].Kind == PipelineStageKind.TraceLoop)
        {
            if (stages[0].Kind != PipelineStageKind.Trace || stages[0].From is not null || stages[0].To is not null)
            {
                diagnostics.Add("firmament-pipeline-stage-type:TraceLoop");
                return [];
            }
            if (guides.TryGetValue(stages[0].Reference!, out var closedGuide) && closedGuide is LineArcFullCircle2D or LineArcFullEllipse2D)
                return [PipelineSegment(profile, loopName, stages[0].Alias ?? stages[0].Reference!.Split('.').Last(), closedGuide, $"concept:{profile.Frame ?? "XY"}.{stages[0].Reference}", stages[0].Reference!, false, 0, expression.Span.Start)];
            if (!paths.TryGetValue(stages[0].Reference!, out var path))
            {
                diagnostics.Add($"firmament-profile-traceloop-not-loop:{stages[0].Reference}");
                return [];
            }
            if (!IsClosed(path.Steps.SelectMany(step => step.Curves).ToArray()))
            {
                diagnostics.Add($"firmament-profile-traceloop-not-loop:{stages[0].Reference}");
                return [];
            }
            var curves = path.Steps.SelectMany(step => step.Curves.Select((curve, ordinal) => (Step: step, Curve: curve, Ordinal: ordinal))).ToList();
            var wantCounterClockwise = string.Equals(loopName, "Outer", StringComparison.Ordinal);
            var reversedLoop = (SignedArea(curves.Select(x => x.Curve)) > 0) != wantCounterClockwise;
            if (reversedLoop) curves = curves.AsEnumerable().Reverse().Select(x => (x.Step, Reverse(x.Curve), x.Ordinal)).ToList();
            return curves.Select((entry, index) =>
            {
                var inherited = entry.Step.Curves.Count == 1 ? entry.Step.Name : $"{entry.Step.Name}.curve{entry.Ordinal:D2}";
                var name = inherited;
                return PipelineSegment(profile, loopName, name, entry.Curve, $"concept-path:{path.Name}.{entry.Step.Name}", $"{path.Name}.{entry.Step.Name}", reversedLoop, index, expression.Span.Start);
            }).ToArray();
        }
        if (stages.Any(stage => stage.Kind == PipelineStageKind.TraceLoop))
        {
            diagnostics.Add("firmament-pipeline-stage-type:TraceLoop");
            return [];
        }
        var close = stages.LastOrDefault()?.Kind == PipelineStageKind.Close;
        if (stages.Any(stage => stage.Kind == PipelineStageKind.Close && stage != stages[^1]))
        {
            diagnostics.Add("firmament-pipeline-stage-type:Close");
            return [];
        }
        var traceStages = close ? stages.Take(stages.Count - 1).ToArray() : stages.ToArray();
        var result = new List<ResolvedProfileSegment2D>();
        var names = new HashSet<string>(StringComparer.Ordinal);
        (double X, double Y)? first = null;
        (double X, double Y)? current = null;
        string? currentIdentity = null;
        PipelineStage? pendingRound = null;
        var roundCount = 0;
        ResolvedProfileSegment2D? Rounded(PipelineStage round, int previousIndex, ref LineArcProfileCurve2D next, int index)
        {
            var previous = result[previousIndex];
            var rounded = ProfileCornerRound.TryRound(previous.Geometry, next, round.Radius!.Value, out var failure);
            if (rounded is null)
            {
                diagnostics.Add($"firmament-pipeline-round-invalid:{loopName}:{previous.Name}: Round({round.Radius.Value:0.###}mm) after '{previous.Name}': {failure}.");
                return null;
            }
            result[previousIndex] = previous with { Geometry = rounded.Previous };
            next = rounded.Next;
            var arcName = round.Alias ?? $"{previous.Name}Round{++roundCount}";
            if (!names.Add(arcName)) { diagnostics.Add($"firmament-profile-pipeline-identity-collision:{arcName}"); return null; }
            return PipelineSegment(profile, loopName, arcName, rounded.Arc, $"concept:{profile.Frame ?? "XY"}.Round:{arcName}", "Round", false, index, expression.Span.Start + round.Offset);
        }
        for (var index = 0; index < traceStages.Length; index++)
        {
            var stage = traceStages[index];
            if (stage.Kind == PipelineStageKind.Round)
            {
                if (result.Count == 0 || pendingRound is not null)
                { diagnostics.Add($"firmament-pipeline-round-invalid:{loopName}: Round must follow a traced stage and precede another stage or Close."); continue; }
                pendingRound = stage;
                continue;
            }
            if (stage.Kind != PipelineStageKind.Trace)
            {
                diagnostics.Add($"firmament-pipeline-stage-type:{stage.Reference}");
                continue;
            }
            if (!guides.TryGetValue(stage.Reference!, out var source))
            {
                diagnostics.Add($"firmament-pipeline-unknown-guide:{stage.Reference}");
                continue;
            }
            bool reversed;
            // `from P` alone runs from P to the guide's end in its own direction (its start under Reverse);
            // `to P` alone continues from the current point.
            var oriented = stage.To is null && stage.From is null
                ? OrientPipelineCurve(source, stage.Reverse, current, stage.Reference!, points, diagnostics, out reversed)
                : SelectPipelineSubspan(source, stage, current, points, diagnostics, out reversed);
            if (oriented is null) continue;
            ResolvedProfileSegment2D? roundArc = null;
            if (pendingRound is not null)
            {
                roundArc = Rounded(pendingRound, result.Count - 1, ref oriented, index);
                pendingRound = null;
                if (roundArc is not null) result.Add(roundArc);
            }
            var start = Start(oriented); var end = End(oriented);
            first ??= start;
            current = end;
            currentIdentity = DescribeEndpoint(end, points);
            var inheritedName = stage.Reference!.Split('.').Last();
            var name = stage.Alias ?? inheritedName;
            if (!names.Add(name)) { diagnostics.Add($"firmament-profile-pipeline-identity-collision:{name}"); continue; }
            result.Add(PipelineSegment(profile, loopName, name, oriented, $"concept:{profile.Frame ?? "XY"}.{stage.Reference}", stage.Reference!, reversed, index, expression.Span.Start + stage.Offset));
        }
        if (pendingRound is not null)
        {
            // A Round before Close fillets the junction where the loop closes, between the last and first stages.
            if (!close || result.Count < 2)
                diagnostics.Add($"firmament-pipeline-round-invalid:{loopName}: Round must follow a traced stage and precede another stage or Close.");
            else
            {
                var firstCurve = result[0].Geometry;
                if (Rounded(pendingRound, result.Count - 1, ref firstCurve, traceStages.Length) is { } closingArc)
                {
                    result[0] = result[0] with { Geometry = firstCurve };
                    result.Add(closingArc);
                    first = Start(firstCurve);
                    current = End(closingArc.Geometry);
                    currentIdentity = DescribeEndpoint(current.Value, points);
                }
            }
        }
        if (close && first is not null && current is not null && Distance(first.Value, current.Value) > Tolerance)
            diagnostics.Add($"firmament-pipeline-close-open:{loopName}:first={DescribeEndpoint(first.Value, points)}:current={currentIdentity}");
        return result;
    }

    private static BoundPath? BindPathPipeline(string name, string body, IReadOnlyDictionary<string, (double X, double Y)> points, IReadOnlyDictionary<string, LineArcProfileCurve2D> guides, List<string> diagnostics)
    {
        var expression = ReadPipeline(body);
        if (expression is null)
        {
            diagnostics.Add($"firmament-path-pipeline-expression-required:{name}");
            return null;
        }
        var stages = ParsePipelineStages(expression);
        if (stages.Any(stage => stage.Kind is PipelineStageKind.Close or PipelineStageKind.TraceLoop))
        {
            diagnostics.Add($"firmament-pipeline-stage-type:{stages.First(stage => stage.Kind is PipelineStageKind.Close or PipelineStageKind.TraceLoop).Kind}");
            return null;
        }
        var steps = new List<BoundPathStep>();
        var names = new HashSet<string>(StringComparer.Ordinal);
        (double X, double Y)? current = null;
        foreach (var stage in stages)
        {
            if (stage.Kind != PipelineStageKind.Trace) { diagnostics.Add($"firmament-pipeline-stage-type:{stage.Reference}"); continue; }
            if (!guides.TryGetValue(stage.Reference!, out var source)) { diagnostics.Add($"firmament-pipeline-unknown-guide:{stage.Reference}"); continue; }
            bool reversed;
            // `from P` alone runs from P to the guide's end in its own direction (its start under Reverse);
            // `to P` alone continues from the current point.
            var oriented = stage.To is null && stage.From is null
                ? OrientPipelineCurve(source, stage.Reverse, current, stage.Reference!, points, diagnostics, out reversed)
                : SelectPipelineSubspan(source, stage, current, points, diagnostics, out reversed);
            if (oriented is null) continue;
            var stepName = stage.Alias ?? stage.Reference!.Split('.').Last();
            if (!names.Add(stepName)) { diagnostics.Add($"firmament-profile-pipeline-identity-collision:{stepName}"); continue; }
            var start = Start(oriented); var end = End(oriented);
            steps.Add(new(stepName, oriented is LineArcCircularArc2D ? "ArcTransition" : "Span", $"{name}.{stepName}", $"{name}.{stepName}.End", [oriented], start, end, Heading(start, end), stage.Reference, reversed, steps.Count, $"offset:{expression.Span.Start + stage.Offset}"));
            current = end;
        }
        return steps.Count == 0 ? null : new BoundPath(name, steps[0].Start, Heading(steps[0].Start, steps[0].End), steps);
    }

    private static LineArcProfileCurve2D? OrientPipelineCurve(LineArcProfileCurve2D source, bool explicitReverse, (double X, double Y)? current, string reference, IReadOnlyDictionary<string, (double X, double Y)>? points, List<string> diagnostics, out bool reversed)
    {
        reversed = explicitReverse;
        var candidate = explicitReverse ? Reverse(source) : source;
        if (candidate is LineArcFullCircle2D)
        {
            diagnostics.Add($"firmament-profile-pipeline-orientation-ambiguous:{reference}");
            return null;
        }
        if (current is null) return candidate;
        var matchesStart = Distance(current.Value, Start(candidate)) <= Tolerance;
        var matchesEnd = Distance(current.Value, End(candidate)) <= Tolerance;
        if (matchesStart && matchesEnd) { diagnostics.Add($"firmament-profile-pipeline-orientation-ambiguous:{reference}"); return null; }
        if (explicitReverse && matchesStart) return candidate;
        if (matchesStart) return candidate;
        if (matchesEnd) { reversed = !explicitReverse; return Reverse(candidate); }
        diagnostics.Add(Disconnected(current.Value, reference, candidate, points));
        return null;
    }

    private static LineArcProfileCurve2D? SelectPipelineSubspan(
        LineArcProfileCurve2D source,
        PipelineStage stage,
        (double X, double Y)? current,
        IReadOnlyDictionary<string, (double X, double Y)> points,
        List<string> diagnostics,
        out bool reversed)
    {
        reversed = false;
        if (stage.From is not null && !points.TryGetValue(stage.From, out _))
        {
            diagnostics.Add($"firmament-pipeline-unknown-endpoint:{stage.From}");
            return null;
        }
        // `from P` alone runs to the guide's own end (its start under `reverse`).
        (double X, double Y) end;
        if (stage.To is null) end = stage.Reverse ? Start(source) : End(source);
        else if (!points.TryGetValue(stage.To, out end))
        {
            diagnostics.Add($"firmament-pipeline-unknown-endpoint:{stage.To}");
            return null;
        }

        var start = stage.From is not null
            ? points[stage.From]
            : current ?? (stage.Reverse ? End(source) : Start(source));
        if (current is not null && Distance(current.Value, start) > Tolerance)
        {
            diagnostics.Add(Disconnected(current.Value, stage.Reference!, source, points));
            return null;
        }

        if (source is LineArcLineSegment2D line)
        {
            if (!OnBoundedLine(start, line) || !OnBoundedLine(end, line) || Distance(start, end) <= Tolerance)
            {
                diagnostics.Add($"firmament-pipeline-endpoint-not-on-guide:{stage.Reference}:{stage.From ?? DescribeEndpoint(start, points)}:{stage.To ?? DescribeEndpoint(end, points)}");
                return null;
            }
            var dx = line.End.X - line.Start.X; var dy = line.End.Y - line.Start.Y;
            reversed = (end.X - start.X) * dx + (end.Y - start.Y) * dy < 0;
            return new LineArcLineSegment2D(start, end);
        }
        if (source is LineArcFullCircle2D circle)
        {
            if (!OnCircle(start, circle.Center, circle.Radius) || !OnCircle(end, circle.Center, circle.Radius) || Distance(start, end) <= Tolerance)
            {
                diagnostics.Add($"firmament-pipeline-endpoint-not-on-guide:{stage.Reference}:{stage.From ?? DescribeEndpoint(start, points)}:{stage.To ?? DescribeEndpoint(end, points)}");
                return null;
            }
            var startAngle = Math.Atan2(start.Y - circle.Center.Y, start.X - circle.Center.X);
            var sweep = Math.Atan2(end.Y - circle.Center.Y, end.X - circle.Center.X) - startAngle;
            if (stage.Reverse) { while (sweep >= 0) sweep -= 2 * Math.PI; reversed = true; }
            else while (sweep <= 0) sweep += 2 * Math.PI;
            return new LineArcCircularArc2D(circle.Center, circle.Radius, startAngle, sweep);
        }
        if (source is LineArcCircularArc2D arc)
        {
            if (TrySelectArcSubspan(stage.Reverse ? (LineArcCircularArc2D)Reverse(arc) : arc, start, end, out var selected))
            {
                reversed = stage.Reverse;
                return selected;
            }
            if (TrySelectArcSubspan(stage.Reverse ? arc : (LineArcCircularArc2D)Reverse(arc), start, end, out selected))
            {
                reversed = !stage.Reverse;
                return selected;
            }
        }
        diagnostics.Add($"firmament-pipeline-endpoint-not-on-guide:{stage.Reference}:{stage.From ?? DescribeEndpoint(start, points)}:{stage.To ?? DescribeEndpoint(end, points)}");
        return null;
    }

    private static bool TrySelectArcSubspan(LineArcCircularArc2D arc, (double X, double Y) start, (double X, double Y) end, out LineArcCircularArc2D? selected)
    {
        selected = null;
        if (!OnCircle(start, arc.Center, arc.Radius) || !OnCircle(end, arc.Center, arc.Radius)) return false;
        var direction = Math.Sign(arc.SweepAngleRadians);
        var span = Math.Abs(arc.SweepAngleRadians);
        double Progress((double X, double Y) point)
        {
            var angle = Math.Atan2(point.Y - arc.Center.Y, point.X - arc.Center.X);
            var delta = direction * (angle - arc.StartAngleRadians);
            while (delta < 0) delta += 2 * Math.PI;
            while (delta >= 2 * Math.PI) delta -= 2 * Math.PI;
            return delta;
        }
        var fromProgress = Progress(start); var toProgress = Progress(end);
        if (fromProgress > span + 1e-7 || toProgress > span + 1e-7 || toProgress <= fromProgress + Tolerance) return false;
        selected = new LineArcCircularArc2D(arc.Center, arc.Radius, Math.Atan2(start.Y - arc.Center.Y, start.X - arc.Center.X), direction * (toProgress - fromProgress));
        return true;
    }

    private static bool OnBoundedLine((double X, double Y) point, LineArcLineSegment2D line) =>
        OnLine(point, line) && point.X >= Math.Min(line.Start.X, line.End.X) - Tolerance && point.X <= Math.Max(line.Start.X, line.End.X) + Tolerance
        && point.Y >= Math.Min(line.Start.Y, line.End.Y) - Tolerance && point.Y <= Math.Max(line.Start.Y, line.End.Y) + Tolerance;

    /// <summary>Selectable spans between existing named landmarks. No points are invented and
    /// no intersection solver is introduced. Material tracing still performs its full checks.</summary>
    internal static IReadOnlyList<(string Guide, string From, string To, LineArcProfileCurve2D Geometry)> ConstructionSpans(
        IReadOnlyDictionary<string, (double X, double Y)> points, IReadOnlyDictionary<string, LineArcProfileCurve2D> guides)
    {
        var result = new List<(string, string, string, LineArcProfileCurve2D)>();
        foreach (var (name, geometry) in guides)
        {
            if (geometry is LineArcCircularArc2D arc)
            {
                // Sub-arcs between the named points along an arc, in its own direction.
                var direction = Math.Sign(arc.SweepAngleRadians); var extent = Math.Abs(arc.SweepAngleRadians);
                double Progress((double X, double Y) p)
                {
                    var delta = direction * (Math.Atan2(p.Y - arc.Center.Y, p.X - arc.Center.X) - arc.StartAngleRadians);
                    while (delta < -1e-9) delta += 2 * Math.PI;
                    while (delta >= 2 * Math.PI - 1e-9) delta -= 2 * Math.PI;
                    return Math.Abs(delta) < 1e-9 ? 0 : delta;
                }
                var stops = new List<(string Name, double At, (double X, double Y) P)>();
                foreach (var point in points.Where(p => OnCircle(p.Value, arc.Center, arc.Radius)).OrderBy(p => p.Key, StringComparer.Ordinal))
                {
                    var at = Progress(point.Value);
                    if (Distance(point.Value, End(arc)) <= 1e-7) at = extent;
                    if (at <= extent + 1e-7 && !stops.Any(s => Distance(s.P, point.Value) <= Tolerance)) stops.Add((point.Key, at, point.Value));
                }
                var along = stops.OrderBy(s => s.At).ToArray();
                for (var i = 0; i + 1 < along.Length; i++)
                    if (along[i + 1].At - along[i].At > 1e-9)
                        result.Add((name, along[i].Name, along[i + 1].Name, new LineArcCircularArc2D(arc.Center, arc.Radius,
                            Math.Atan2(along[i].P.Y - arc.Center.Y, along[i].P.X - arc.Center.X), direction * (along[i + 1].At - along[i].At))));
                continue;
            }
            if (geometry is LineArcFullCircle2D circle)
            {
                // Counter-clockwise arcs between consecutive named points on the circle.
                var stops = new List<KeyValuePair<string, (double X, double Y)>>();
                foreach (var point in points.Where(p => OnCircle(p.Value, circle.Center, circle.Radius)).OrderBy(p => p.Key, StringComparer.Ordinal))
                    if (!stops.Any(p => Distance(p.Value, point.Value) <= Tolerance)) stops.Add(point);
                if (stops.Count < 2) continue;
                var around = stops.OrderBy(p => Math.Atan2(p.Value.Y - circle.Center.Y, p.Value.X - circle.Center.X)).ToArray();
                for (var i = 0; i < around.Length; i++)
                {
                    var diagnostics = new List<string>();
                    var next = around[(i + 1) % around.Length];
                    var selected = SelectGuide(circle, around[i].Value, next.Value, "CounterClockwise", name, name, diagnostics);
                    if (selected is not null && diagnostics.Count == 0) result.Add((name, around[i].Key, next.Key, selected));
                }
                continue;
            }
            if (geometry is not LineArcLineSegment2D line || Distance(line.Start, line.End) <= Tolerance) continue;
            var owner = name.Contains('.') ? name[..name.LastIndexOf('.')] : name;
            var landmarks = new List<KeyValuePair<string, (double X, double Y)>>();
            foreach (var point in points.Where(p => OnBoundedLine(p.Value, line))
                .OrderBy(p => p.Key.StartsWith(owner + ".", StringComparison.Ordinal) ? 0 : 1).ThenBy(p => p.Key, StringComparer.Ordinal))
                if (!landmarks.Any(p => Distance(p.Value, point.Value) <= Tolerance)) landmarks.Add(point);
            var ordered = landmarks.OrderBy(p => (p.Value.X - line.Start.X) * (line.End.X - line.Start.X)
                + (p.Value.Y - line.Start.Y) * (line.End.Y - line.Start.Y)).ToArray();
            for (var i = 0; i + 1 < ordered.Length; i++)
            {
                var diagnostics = new List<string>();
                var selected = SelectGuide(line, ordered[i].Value, ordered[i + 1].Value, "", name, name, diagnostics);
                if (selected is not null && diagnostics.Count == 0) result.Add((name, ordered[i].Key, ordered[i + 1].Key, selected));
            }
        }
        return result;
    }

    internal static bool SameConstructionPoint((double X, double Y) a, (double X, double Y) b) => Distance(a, b) <= Tolerance;

    private static string MaskRecognizedProfileDeclarations(string body)
    {
        var declarationPattern = @"\b(?:(?:Concept\s+)?(?:Point2|Line2|Arc2|Rect2|Square2|Circle2|Ellipse2|Ellipse2Guide|Slot2|RoundedRect2|SmoothRoundedRect2|Path)|(?:Triangle2|Polygon2|RegularPolygon2)\s*<[^>]+>)\s+[A-Za-z_]\w*\s*\{";
        var blocks = FindBlocks(body, declarationPattern).OrderByDescending(block => block.Match.Index).ToArray();
        var characters = body.ToCharArray();
        foreach (var block in blocks)
            for (var i = block.Match.Index; i <= block.EndIndex; i++) if (characters[i] is not ('\r' or '\n')) characters[i] = ' ';
        return new string(characters);
    }

    private static string Disconnected((double X, double Y) current, string reference, LineArcProfileCurve2D candidate, IReadOnlyDictionary<string, (double X, double Y)>? points) =>
        $"firmament-profile-pipeline-disconnected:{reference}:current={DescribeEndpoint(current, points)}:candidates={DescribeEndpoint(Start(candidate), points)},{DescribeEndpoint(End(candidate), points)}";

    private static string DescribeEndpoint((double X, double Y) point, IReadOnlyDictionary<string, (double X, double Y)>? points) =>
        points?.Where(entry => Distance(entry.Value, point) <= Tolerance).Select(entry => entry.Key).OrderByDescending(x => x.Contains('.')).ThenBy(x => x, StringComparer.Ordinal).FirstOrDefault() ?? $"Point2({point.X:R}mm,{point.Y:R}mm)";

    private static ResolvedProfileSegment2D PipelineSegment(ProfileBlock profile, string loop, string name, LineArcProfileCurve2D geometry, string conceptId, string tracedFrom, bool reversed, int index, int offset) =>
        new(name, geometry, new($"profile:{profile.Name}.{loop}.{name}", conceptId, profile.SourceSpan, $"PipelineTrace({tracedFrom});reversed={reversed.ToString().ToLowerInvariant()};pipelineIndex={index}", profile.Frame ?? "XY", tracedFrom, reversed, index, $"offset:{offset}"));

    private static ExpressionSyntax? ReadPipeline(string body)
    {
        var parsed = FirmamentSyntaxParser.Parse(body);
        return parsed.IsSuccess && parsed.Document.Statements.Count == 1
            && parsed.Document.Statements[0] is ExpressionStatementSyntax { Value: BinarySyntax { Operator: BinaryOperator.Pipeline } expression }
            && !ParsePipelineStages(expression).Any(stage => stage.Kind == PipelineStageKind.Invalid && stage.Reference is null)
            ? expression : null;
    }

    private static IReadOnlyList<PipelineStage> ParsePipelineStages(ExpressionSyntax expression)
    {
        var stages = new List<PipelineStage>();
        Add(expression);
        return stages;
        void Add(ExpressionSyntax value)
        {
            if (value is BinarySyntax { Operator: BinaryOperator.Pipeline } pipeline) { Add(pipeline.Left); Add(pipeline.Right); return; }
            var offset = value.Span.Start - expression.Span.Start;
            if (value is ReferenceSyntax { Name.Text: "Close" }) { stages.Add(new(PipelineStageKind.Close, null, null, false, offset)); return; }
            if (value is ReferenceSyntax { Name.Text: "TraceLoop" }) { stages.Add(new(PipelineStageKind.TraceLoop, null, null, false, offset)); return; }
            // Round(r) between two stages fillets their junction; `Round(r) as Name` names the arc.
            var roundAlias = value is AliasSyntax { Value: CallSyntax } aliased ? aliased.Name.Text : null;
            if ((value is AliasSyntax { Value: CallSyntax } wrapped ? wrapped.Value : value) is CallSyntax { Target: ReferenceSyntax { Name.Text: "Round" } } round)
            {
                var measured = round.Arguments.Count == 1 && round.Arguments[0].Name is null
                    && FirmamentSyntaxValues.TryMeasure(round.Arguments[0].Value, "mm", out var radius) && radius > 0 ? radius : (double?)null;
                stages.Add(new(measured is null ? PipelineStageKind.Invalid : PipelineStageKind.Round, "Round", roundAlias, false, offset, Radius: measured));
                return;
            }
            string? alias = null, from = null, to = null;
            var reverse = false; var valid = true; var traced = false;
            var inner = value;
            while (true)
            {
                if (inner is AliasSyntax a) { valid &= alias is null; alias = a.Name.Text; inner = a.Value; }
                else if (inner is TraceSyntax t)
                {
                    valid &= !traced; traced = true;
                    from = FirmamentSyntaxValues.Reference(t.From); to = FirmamentSyntaxValues.Reference(t.To);
                    valid &= (t.From is null || from is not null) && (t.To is null || to is not null);
                    inner = t.Source;
                }
                else if (inner is UnarySyntax { Operator: UnaryOperator.Reverse } u) { valid &= !reverse; reverse = true; inner = u.Operand; }
                else break;
            }
            var reference = inner is ReferenceSyntax or MemberSyntax ? FirmamentSyntaxValues.Reference(inner) : null;
            valid &= reference is not null;
            stages.Add(new(valid ? PipelineStageKind.Trace : PipelineStageKind.Invalid, reference, alias, reverse, offset, from, to));
        }
    }

    private static bool IsClosed(IReadOnlyList<LineArcProfileCurve2D> curves) => curves.Count > 0 && Distance(Start(curves[0]), End(curves[^1])) <= Tolerance && curves.Zip(curves.Skip(1)).All(pair => Distance(End(pair.First), Start(pair.Second)) <= Tolerance);
    private static double SignedArea(IEnumerable<LineArcProfileCurve2D> curves) => curves.Sum(curve => curve switch
    {
        LineArcCubicBezier2D cubic => ResolvedProfile2DValidator.SignedAreaContribution(cubic),
        LineArcLineSegment2D line => (line.Start.X * line.End.Y - line.End.X * line.Start.Y) / 2d,
        LineArcCircularArc2D arc => (arc.Radius * arc.Center.X * (Math.Sin(arc.StartAngleRadians + arc.SweepAngleRadians) - Math.Sin(arc.StartAngleRadians)) + arc.Radius * arc.Center.Y * (Math.Cos(arc.StartAngleRadians) - Math.Cos(arc.StartAngleRadians + arc.SweepAngleRadians)) + arc.Radius * arc.Radius * arc.SweepAngleRadians) / 2d,
        _ => 0d
    });
    private static LineArcProfileCurve2D Reverse(LineArcProfileCurve2D curve) => curve switch
    {
        LineArcCubicBezier2D cubic => new LineArcCubicBezier2D(cubic.End, cubic.Control2, cubic.Control1, cubic.Start),
        LineArcLineSegment2D line => new LineArcLineSegment2D(line.End, line.Start),
        LineArcCircularArc2D arc => new LineArcCircularArc2D(arc.Center, arc.Radius, arc.StartAngleRadians + arc.SweepAngleRadians, -arc.SweepAngleRadians),
        _ => curve
    };

    private static IReadOnlyList<ResolvedProfileSegment2D> BindLowLevelSegments(ProfileBlock profile, string loopName, string body, IReadOnlyDictionary<string, (double X, double Y)> points, IReadOnlyDictionary<string, LineArcProfileCurve2D> guides, List<string> diagnostics)
    {
        foreach (Match raw in Regex.Matches(body, @"\bSegment\s+(?<name>\w+)\s*\{[\s\S]*?\b(?<endpoint>From|To)\s*:\s*(?<value>\[[^\]]*\]|Point2\s*\([^)]*\))", RegexOptions.CultureInvariant))
            diagnostics.Add($"{SegmentEndpointMustReferenceNamedPoint}:{raw.Groups["name"].Value}:{raw.Groups["endpoint"].Value}");
        var segments = new List<ResolvedProfileSegment2D>();
        foreach (Match match in Segment.Matches(body))
        {
            var name = match.Groups["n"].Value;
            if (!points.TryGetValue(match.Groups["from"].Value, out var from) || !points.TryGetValue(match.Groups["to"].Value, out var to)) { diagnostics.Add($"profile-segment-unresolved:{name}"); continue; }
            if (!guides.TryGetValue(match.Groups["trace"].Value, out var guide)) { diagnostics.Add($"profile-guide-missing:{name}:{match.Groups["trace"].Value}"); continue; }
            var geometry = SelectGuide(guide, from, to, match.Groups["sweep"].Value, name, match.Groups["trace"].Value, diagnostics);
            if (geometry is not null) segments.Add(SegmentResult(profile, loopName, name, geometry, $"concept:{profile.Frame ?? "XY"}.{match.Groups["trace"].Value}", $"Trace({match.Groups["trace"].Value})"));
        }
        return segments;
    }

    private static void AddPathLoop(string loopName, bool outer, string pathName, ProfileBlock profile, IReadOnlyDictionary<string, BoundPath> paths, List<ResolvedProfileLoop2D> loops, List<string> diagnostics)
    {
        if (!paths.TryGetValue(pathName, out var path)) { diagnostics.Add($"profile-path-missing:{profile.Name}:{pathName}"); return; }
        loops.Add(new ResolvedProfileLoop2D(loopName, outer, path.Steps.SelectMany(step => step.Curves.Select((curve, ordinal) => SegmentResult(
            profile, loopName,
            step.Curves.Count == 1 ? step.Name : $"{step.Name}.curve{ordinal:D2}",
            curve, $"concept-path:{pathName}.{step.Name}", $"SemanticProfileMIR:{step.Kind}"))).ToArray()));
    }

    private static ResolvedProfileSegment2D SegmentResult(ProfileBlock profile, string loop, string name, LineArcProfileCurve2D geometry, string conceptId, string derivation) => new(name, geometry, new($"profile:{profile.Name}.{loop}.{name}", conceptId, profile.SourceSpan, derivation, profile.Frame ?? "XY"));

    private static LineArcProfileCurve2D? SelectGuide(LineArcProfileCurve2D guide, (double X, double Y) from, (double X, double Y) to, string sweep, string segment, string trace, List<string> diagnostics)
    {
        if (guide is LineArcLineSegment2D line) { if (!OnLine(from, line) || !OnLine(to, line)) diagnostics.Add($"profile-endpoint-not-on-guide:{segment}:{trace}"); return new LineArcLineSegment2D(from, to); }
        if (guide is LineArcCubicBezier2D cubic)
        {
            if (!string.IsNullOrWhiteSpace(sweep) || Distance(from, cubic.Start) > Tolerance || Distance(to, cubic.End) > Tolerance)
            { diagnostics.Add($"profile-cubic-bezier-invalid:{segment}:{trace}"); return null; }
            return cubic;
        }
        if (guide is LineArcFullCircle2D circle)
        {
            if (!OnCircle(from, circle.Center, circle.Radius) || !OnCircle(to, circle.Center, circle.Radius) || string.IsNullOrWhiteSpace(sweep)) { diagnostics.Add($"profile-arc-invalid:{segment}:{trace}"); return null; }
            var start = Math.Atan2(from.Y - circle.Center.Y, from.X - circle.Center.X); var amount = Math.Atan2(to.Y - circle.Center.Y, to.X - circle.Center.X) - start;
            var ccw = sweep == "CounterClockwise"; while (ccw && amount <= 0) amount += 2 * Math.PI; while (!ccw && amount >= 0) amount -= 2 * Math.PI;
            return new LineArcCircularArc2D(circle.Center, circle.Radius, start, amount);
        }
        diagnostics.Add($"profile-guide-missing:{segment}:{trace}"); return null;
    }

    private static IEnumerable<DeclarationSyntax> ConstructionPlanes(string source) =>
        SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements)
            .Where(d => d.Type.Name.Text == "Plane" && d.Modifiers.Any(m => m.Name.Text == "Construction"));

    private static ConstructionPlane? ResolveConstructionPlane(string source, string? frame, List<string> diagnostics)
    {
        if (frame is null) return ConstructionPlane.WorldXY;
        var planes = ConstructionPlanes(source).Where(d => d.Name?.Text == frame).ToArray();
        if (planes.Length > 1) { diagnostics.Add($"profile-frame-duplicate:{frame}"); return null; }
        var plane = planes.SingleOrDefault();
        if (plane is null)
        {
            if (frame == "XY") return ConstructionPlane.WorldXY;
            var layouts = SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements)
                .Where(d => d.Type.Name.Text == "Struct" && d.Modifiers.Any(m => m.Name.Text == "Concept") && d.Name?.Text == frame).ToArray();
            if (layouts.Length > 1) { diagnostics.Add($"profile-frame-duplicate:{frame}"); return null; }
            if (layouts.SingleOrDefault() is { } layout)
            {
                if (layout.Clauses.Count == 0) return ConstructionPlane.WorldXY;
                if (layout.Clauses.Count != 1 || layout.Clauses[0] is not { Kind: ClauseKind.On, Value: ReferenceSyntax placement }
                    || placement.Name.Text is not ("XY" or "XZ" or "YZ"))
                {
                    diagnostics.Add($"profile-layout-placement-unsupported:{frame}:Use on XY, on XZ or on YZ for a 2D layout; arbitrary orientations use a traced Construction Plane.");
                    return null;
                }
                if (placement.Name.Text == "XY") return ConstructionPlane.WorldXY; // Preserve existing XY geometry and identity.
                // `on` here selects a frame for local 2D guides. It is not a general
                // transform of explicitly spatial Concept values.
                var members = layout.Body?.Statements ?? [];
                if (members.OfType<FieldSyntax>().Any(f => f.Value is not TypedValueSyntax typed
                        || FirmamentSyntaxValues.Reference(typed.Type) is not { } type || !FirmamentV2Parser.TryParseLetType(type, out _))
                    || members.OfType<DeclarationSyntax>().Any(d => !OwnsDeclaration(d) && d.Type.Name.Text != "Static"))
                {
                    diagnostics.Add($"profile-layout-spatial-members-unsupported:{frame}:This non-XY 2D layout requires local 2D guides and scalar data. Put spatial semantic values in an unplaced Concept Struct and trace a Construction Plane for that workflow.");
                    return null;
                }
                var normal = placement.Name.Text == "XZ" ? new ConceptIrVector3(0, -1, 0) : new ConceptIrVector3(1, 0, 0);
                var concept = new ConceptIrPlaneValue("concept-layout:" + frame, new(0, 0, 0), normal,
                    "ConceptLayoutFrame:" + placement.Name.Text, new(0, 0, 1));
                if (!ConstructionPlane.TryTrace("construction:layout:" + frame, concept, $"offset:{layout.Span.Start}", out var layoutPlane, out var diagnostic))
                    diagnostics.Add(diagnostic ?? "ConstructionPlaneFrameInvalid");
                return layoutPlane;
            }
            diagnostics.Add($"profile-frame-unresolved:{frame}:using must name a declared Concept Struct or Construction Plane.");
            return null;
        }
        var before = diagnostics.Count;
        var fields = new FirmamentSyntaxFields(plane, diagnostics);
        var trace = fields.Reference("Trace");
        fields.Complete();
        if (trace is null || diagnostics.Count > before) { diagnostics.Add($"profile-frame-trace-invalid:{frame}"); return null; }
        if (!ConceptIrResolver.TryResolvePlane(source, trace, out var conceptPlane, out var traceDiagnostic) || conceptPlane is null) { diagnostics.Add(traceDiagnostic ?? "ConstructionPlaneTraceMissing"); return null; }
        if (!ConstructionPlane.TryTrace("construction:" + frame, conceptPlane, $"offset:{plane.Span.Start}", out var result, out var frameDiagnostic)) diagnostics.Add(frameDiagnostic ?? "ConstructionPlaneFrameInvalid");
        return result;
    }

    internal static (ExpressionSyntax? Profile, ExpressionSyntax? From, ExpressionSyntax? To) ReadExtrudeFields(DeclarationSyntax declaration, List<string> diagnostics)
    {
        var fields = new FirmamentSyntaxFields(declaration, diagnostics);
        var profile = fields.Take("Profile");
        var from = fields.Take("From");
        var to = fields.Take("To");
        fields.CheckUnit("From", from, "mm");
        fields.CheckUnit("To", to, "mm");
        // Extrude<Hollow> carries its wall; the hollow Compose it lowers to validates the values.
        if (declaration.Type.Arguments.Count == 1 && FirmamentSyntaxValues.Reference(declaration.Type.Arguments[0].Value) == "Hollow")
        {
            fields.CheckUnit("WallThickness", fields.Take("WallThickness"), "mm");
            fields.Take("Openings");
        }
        fields.Complete();
        return (profile, from, to);
    }

    private static (double Start, double End, double Height) ResolveExtrude(string source, string profileName, List<string> diagnostics, Func<ExpressionSyntax, ExpressionSyntax>? bind = null)
    {
        foreach (var d in SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).Where(d => d.Type.Name.Text == "Extrude"))
        {
            var fields = ReadExtrudeFields(d, diagnostics);
            if (FirmamentSyntaxValues.Reference(fields.Profile) != profileName) continue;
            if (!FirmamentSyntaxValues.TryMeasure(fields.From is { } from ? bind?.Invoke(from) ?? from : null, "mm", out var start)
                || !FirmamentSyntaxValues.TryMeasure(fields.To is { } to ? bind?.Invoke(to) ?? to : null, "mm", out var end))
            {
                diagnostics.Add($"profile-extrusion-length-required:{d.Name?.Text}: Extrude from/to must be lengths in mm, not angles or scalars.");
                continue;
            }
            if (!double.IsFinite(start) || !double.IsFinite(end)) break;
            return (start, end, Math.Abs(end - start));
        }
        diagnostics.Add("profile-extrude-missing-or-mismatched"); return default;
    }

    private static IEnumerable<ProfileBlock> FindProfiles(string source)
    {
        foreach (var d in SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).Where(d => d.Type.Name.Text == "Profile" && d.Name is not null))
        {
            var frame = FirmamentSyntaxValues.Reference(d.Clauses.FirstOrDefault(c => c.Kind == ClauseKind.Using)?.Value);
            var path = FirmamentSyntaxValues.Reference(d.Clauses.FirstOrDefault(c => c.Kind == ClauseKind.From)?.Value);
            var body = d.Body is null ? null : source.Substring(d.Body.Span.Start + 1, d.Body.Span.Length - 2);
            yield return new(d.Name!.Text, frame, path, body, $"source:{d.Span.Start}");
        }
    }

    private static IEnumerable<Block> FindBlocks(string source, string headerPattern)
    {
        foreach (Match match in Regex.Matches(source, headerPattern, RegexOptions.CultureInvariant))
        {
            var open = source.IndexOf('{', match.Index, match.Length); var depth = 0; var end = -1;
            for (var index = open; index >= 0 && index < source.Length; index++) { if (source[index] == '{') depth++; else if (source[index] == '}' && --depth == 0) { end = index; break; } }
            if (open >= 0 && end > open) yield return new(match, source[(open + 1)..end], end);
        }
    }

    private static int FindMatchingBrace(string source, int open)
    {
        var depth = 0;
        for (var index = open; index >= 0 && index < source.Length; index++)
        {
            if (source[index] == '{') depth++;
            else if (source[index] == '}' && --depth == 0) return index;
        }
        return -1;
    }

    private static IEnumerable<PathStep> FindPathSteps(string body)
    {
        var entries = new List<PathStep>();
        foreach (var block in FindBlocks(body, @"\b(?<kind>Line|Span|Arc|Chamfer|Step|Notch|Cutback|Tab)\s+(?<name>[A-Za-z_]\w*)\s*\{")) entries.Add(new(block.Match.Groups["kind"].Value, block.Match.Groups["name"].Value, block.Body, block.Match.Index));
        foreach (Match match in Regex.Matches(body, @"\bClose\s+(?<name>[A-Za-z_]\w*)\b", RegexOptions.CultureInvariant)) entries.Add(new("Close", match.Groups["name"].Value, string.Empty, match.Index));
        return entries.OrderBy(x => x.Index);
    }

    internal static string? Property(string body, string name)
    {
        // A property expression may contain whitespace (for example P.Length - P.Gap),
        // while legacy compact authoring may put the next Name: property on the same line.
        var match = Regex.Match(body, $@"\b{name}\s*:\s*(?<v>.*?)(?=\s+[A-Za-z_]\w*\s*:|[;\r\n}}]|$)", RegexOptions.CultureInvariant);
        return match.Success ? match.Groups["v"].Value.Trim() : null;
    }
    internal static bool TryMeasure(string text, string unit, out double value)
    {
        var parsed = FirmamentSyntaxParser.ParseExpression(text);
        return FirmamentSyntaxValues.TryMeasure(parsed.Diagnostics.Count == 0 ? parsed.Expression : null, unit, out value);
    }
    private static bool TryNumber(string text, out double value) => double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value);
    private static (double X, double Y) Advance((double X, double Y) point, double heading, double length) { var radians = DegreesToRadians(heading); return (point.X + length * Math.Cos(radians), point.Y + length * Math.Sin(radians)); }
    private static double DegreesToRadians(double value) => value * Math.PI / 180d;
    private static double Heading((double X, double Y) from, (double X, double Y) to) => Math.Atan2(to.Y - from.Y, to.X - from.X) * 180d / Math.PI;
    private static double Distance((double X, double Y) a, (double X, double Y) b) => Math.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y));
    private static (double X,double Y) Start(LineArcProfileCurve2D curve)=>curve switch{LineArcCubicBezier2D cubic=>cubic.Start,LineArcLineSegment2D line=>line.Start,LineArcCircularArc2D arc=>(arc.Center.X+arc.Radius*Math.Cos(arc.StartAngleRadians),arc.Center.Y+arc.Radius*Math.Sin(arc.StartAngleRadians)),_=>throw new InvalidOperationException()};
    private static (double X,double Y) End(LineArcProfileCurve2D curve)=>curve switch{LineArcCubicBezier2D cubic=>cubic.End,LineArcLineSegment2D line=>line.End,LineArcCircularArc2D arc=>(arc.Center.X+arc.Radius*Math.Cos(arc.StartAngleRadians+arc.SweepAngleRadians),arc.Center.Y+arc.Radius*Math.Sin(arc.StartAngleRadians+arc.SweepAngleRadians)),_=>throw new InvalidOperationException()};
    private static bool OnLine((double X, double Y) point, LineArcLineSegment2D line) => Math.Abs((line.End.X - line.Start.X) * (point.Y - line.Start.Y) - (line.End.Y - line.Start.Y) * (point.X - line.Start.X)) < 1e-7;
    private static bool OnCircle((double X, double Y) point, (double X, double Y) center, double radius) => Math.Abs(Distance(point, center) - radius) < 1e-7;

    private sealed record Block(Match Match, string Body, int EndIndex);
    private sealed record ProfileBlock(string Name, string? Frame, string? FromPath, string? Body, string SourceSpan);
    private sealed record PathStep(string Kind, string Name, string Body, int Index);
    private sealed record BoundPathStep(string Name, string Kind, string GuideName, string EndpointName, IReadOnlyList<LineArcProfileCurve2D> Curves, (double X, double Y) Start, (double X, double Y) End, double Heading, string? SourceReference = null, bool WasReversed = false, int? PipelineIndex = null, string? SourceRange = null);
    private sealed record BoundPath(string Name, (double X, double Y) Start, double InitialHeading, List<BoundPathStep> Steps);
    private enum PipelineStageKind { Trace, Close, TraceLoop, Round, Invalid }
    private sealed record PipelineStage(PipelineStageKind Kind, string? Reference, string? Alias, bool Reverse, int Offset, string? From = null, string? To = null, double? Radius = null);

}