Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

64.6 KB
Raw Blame
using System.Runtime.InteropServices.JavaScript;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Brep.Tessellation;
using Aetheris.Kernel.Core.Diagnostics;
using Aetheris.Kernel.Core.Geometry;
using Aetheris.Kernel.Core.Step242;
using Aetheris.Kernel.Firmament;
using Aetheris.Kernel.Firmament.Assembly;
using Aetheris.Kernel.Firmament.FirmamentV2;
using Aetheris.Kernel.Firmament.Materializer;
using Aetheris.Kernel.Firmament.Scene;
using Aetheris.Kernel.Firmament.Export;

namespace Aetheris.Web.Runtime;

public static partial class Program
{
    // BUILD-PERF-M2: the compiler calls static Regex methods from ~860 sites. The runtime caches the
    // constructed patterns, 15 by default, so a build re-parsed most patterns on every call; in the
    // interpreted browser runtime that is a large share of every rebuild. Matching is unchanged.
    static Program() => System.Text.RegularExpressions.Regex.CacheSize = Math.Max(System.Text.RegularExpressions.Regex.CacheSize, 1024);

    private const string ContractVersion = "aetheris/web-editor-contract/1";
    private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
    private static readonly JsonSerializerOptions BridgeOptions = WebResponseBridge.Options(JsonOptions);
    private static byte[] _pendingBinary = [];

    /// <summary>The binary payload of the last bridge-mode response (empty when none); taken once.</summary>
    [JSExport]
    public static byte[] TakeBinary()
    {
        var binary = _pendingBinary;
        _pendingBinary = [];
        return binary;
    }
    private static readonly Dictionary<string, WebModelSession> Sessions = new(StringComparer.Ordinal);
    private static int _nextSession;

    public static void Main() { }

    [JSExport]
    public static string Invoke(string requestJson)
    {
        try
        {
            var request = JsonSerializer.Deserialize<WebRequest>(requestJson, JsonOptions)
                ?? throw new WebRuntimeException("invalid-request", "The runtime request was empty.");
            _pendingBinary = [];
            if (request.Performance) BuildPerfTrace.Start();
            object? result = request.Operation switch
            {
                "info" => Info(),
                "compile" => Compile(request),
                "languageComplete" => LanguageComplete(request),
                "languageAnalyze" => LanguageAnalyze(request),
                "languageOutline" => LanguageOutline(request),
                "languageSketch" => LanguageSketch(request),
                "languagePatterns" => LanguagePatterns(request),
                "languageSketchEdit" => LanguageSketchEdit(request),
                "languageEdit" => LanguageEdit(request),
                "languagePalette" => FirmamentLanguagePaletteService.Palette(),
                "languageHover" => LanguageHover(request),
                "languageDefinition" => LanguageDefinition(request),
                "languageFormat" => LanguageFormat(request),
                "languageSchema" => LanguageSchema(),
                "describeConstruct" => DescribeConstruct(request),
                "rewriteField" => RewriteField(request),
                "snapshot" => Session(request).Snapshot,
                "sampleMotion" => Session(request).SampleMotion(request),
                "measure" => Session(request).Measure(request),
                "setProperty" => SetProperty(request),
                "setSource" => SetSource(request),
                "rebuild" => Rebuild(request),
                "exportStep" => ExportStep(request),
                "exportArtifacts" => Session(request).ExportArtifacts(request),
                "disposeSession" => DisposeSession(request),
                "disposeRuntime" => DisposeRuntime(),
                _ => throw new WebRuntimeException("unknown-operation", $"Unknown runtime operation '{request.Operation}'.")
            };
            var response = request.Bridge >= 1 ? SerializeBridged(request, result) : JsonSerializer.Serialize(new { ok = true, result }, JsonOptions);
            BuildPerfTrace.Stop();
            return response;
        }
        catch (WebRuntimeException exception)
        {
            BuildPerfTrace.Stop();
            return JsonSerializer.Serialize(new { ok = false, error = new { code = exception.Code, message = exception.Message } }, JsonOptions);
        }
        catch (Exception exception)
        {
            BuildPerfTrace.Stop();
            return JsonSerializer.Serialize(new { ok = false, error = new { code = "internal-error", message = "Aetheris could not complete the operation.", details = exception.Message } }, JsonOptions);
        }
    }

    private static object Info() => new
    {
        packageVersion = typeof(Program).Assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyInformationalVersionAttribute), false)
            .Cast<System.Reflection.AssemblyInformationalVersionAttribute>().Single().InformationalVersion.Split('+')[0],
        runtimeVersion = typeof(Program).Assembly.GetName().Version?.ToString() ?? "2.0.0",
        contractVersion = ContractVersion,
        language = "Firmament",
        capabilities = new
        {
            compile = true, solidModeling = true, assembly = true, displayMesh = true,
            propertyInspection = true, parameterRebuild = true, stepExport = true, artifactExport = true,
            sheetMetal = false, fea = false, externalStepImport = true, forgeSubprocess = false,
            cancellation = false, worker = false
        }
    };

    private static object Compile(WebRequest request)
    {
        if (string.IsNullOrWhiteSpace(request.Source))
            throw new WebRuntimeException("source-required", "compile requires Firmament source text.");
        var id = $"model-{++_nextSession}";
        var session = new WebModelSession(id, request.Source, request.SourceName ?? "model.firmament", request.ProjectDocuments);
        var result = session.Rebuild();
        if (result.Success) Sessions[id] = session;
        else session.Dispose();
        return result;
    }

    private static object LanguageComplete(WebRequest request)
    {
        if (request.Source is null || request.Offset is null || string.IsNullOrWhiteSpace(request.SourceRevision))
            throw new WebRuntimeException("language-input-required", "languageComplete requires source, offset, and sourceRevision.");
        return FirmamentLanguageService.Complete(request.Source, request.SourceName ?? "model.firmament",
            request.SourceRevision, request.Offset.Value);
    }

    private static object LanguageAnalyze(WebRequest request)
    {
        if (request.Source is null || string.IsNullOrWhiteSpace(request.SourceRevision))
            throw new WebRuntimeException("language-input-required", "languageAnalyze requires source and sourceRevision.");
        var name = request.SourceName ?? "model.firmament";
        var documents = request.ProjectDocuments is { Count: > 0 }
            ? new Dictionary<string, string>(request.ProjectDocuments, StringComparer.Ordinal) { [name] = request.Source }
            : null;
        var root = request.ProjectRoot ?? name;
        var project = documents is null ? null : new FirmamentProjectSnapshot(root, documents);
        var analysis = project is not null
            ? FirmamentLanguageAnalysisService.Analyze(project, name, request.SourceRevision)
            : FirmamentLanguageAnalysisService.Analyze(request.Source, name, request.SourceRevision);
        return new { document = name, revision = request.SourceRevision, analysis.Tokens,
            diagnostics = analysis.Diagnostics.Select(item => new WebDiagnostic(item.Severity, item.Code, item.Message,
                SourceRefAt(name, request.Source, item.Start, item.Length))).ToArray() };
    }

    private static object LanguageOutline(WebRequest request)
    {
        if (request.Source is null || string.IsNullOrWhiteSpace(request.SourceRevision))
            throw new WebRuntimeException("language-input-required", "languageOutline requires source and sourceRevision.");
        var name = request.SourceName ?? "model.firmament";
        if (request.ProjectDocuments is not { Count: > 0 })
            return FirmamentLanguageOutlineService.Outline(request.Source, name, request.SourceRevision);
        var documents = new Dictionary<string, string>(request.ProjectDocuments, StringComparer.Ordinal) { [name] = request.Source };
        return FirmamentLanguageOutlineService.Outline(new FirmamentProjectSnapshot(request.ProjectRoot ?? name, documents), name, request.SourceRevision);
    }

    private static object LanguagePatterns(WebRequest request)
    {
        if (request.Source is null || request.SourceRevision is null)
            throw new WebRuntimeException("source-required", "A Pattern query requires source and its revision.");
        var name = request.SourceName ?? "model.firmament";
        var documents = new Dictionary<string, string>(request.ProjectDocuments ?? new Dictionary<string, string>(), StringComparer.Ordinal) { [name] = request.Source };
        return FirmamentPatternService.Project(request.Source, name, request.SourceRevision,
            new FirmamentProjectSnapshot(request.ProjectRoot ?? name, documents));
    }

    private static object LanguageSketch(WebRequest request)
    {
        if (request.Source is null || request.SourceRevision is null)
            throw new WebRuntimeException("source-required", "A sketch query requires source and its revision.");
        return FirmamentSketchService.Project(request.Source, request.SourceName ?? "model.firmament", request.SourceRevision, request.Node);
    }

    private static object LanguageSketchEdit(WebRequest request)
    {
        if (request.Source is null || request.SourceRevision is null || request.SketchEdit is null)
            throw new WebRuntimeException("source-required", "A sketch edit requires source, revision and an operation.");
        try { return FirmamentSketchService.Edit(request.Source, request.SourceName ?? "model.firmament", request.SourceRevision, request.SketchEdit); }
        catch (FirmamentLanguageEditException error) { throw new WebRuntimeException(error.Code, error.Message); }
    }

    private static object LanguageEdit(WebRequest request)
    {
        if (request.Source is null || string.IsNullOrWhiteSpace(request.SourceRevision) || request.Operations is not { Count: > 0 })
            throw new WebRuntimeException("language-input-required", "languageEdit requires source, sourceRevision and operations.");
        try { return FirmamentLanguageEditService.Apply(request.Source, request.SourceName ?? "model.firmament", request.SourceRevision, request.Operations); }
        catch (FirmamentLanguageEditException error) { throw new WebRuntimeException(error.Code, error.Message); }
    }

    private static object? LanguageHover(WebRequest request)
    {
        if (request.Source is null || request.Offset is null || string.IsNullOrWhiteSpace(request.SourceRevision))
            throw new WebRuntimeException("language-input-required", "languageHover requires source, offset, and sourceRevision.");
        return FirmamentLanguageAnalysisService.Hover(request.Source, request.SourceName ?? "model.firmament", request.SourceRevision, request.Offset.Value);
    }

    private static object? LanguageDefinition(WebRequest request)
    {
        if (request.Source is null || request.Offset is null)
            throw new WebRuntimeException("language-input-required", "languageDefinition requires source and offset.");
        var name = request.SourceName ?? "model.firmament";
        var documents = request.ProjectDocuments is { Count: > 0 }
            ? new Dictionary<string, string>(request.ProjectDocuments, StringComparer.Ordinal) { [name] = request.Source }
            : null;
        var location = documents is null
            ? FirmamentLanguageAnalysisService.Definition(request.Source, name, request.Offset.Value)
            : FirmamentLanguageAnalysisService.Definition(new FirmamentProjectSnapshot(request.ProjectRoot ?? name, documents), name, request.Offset.Value);
        return location is null ? null : SourceRefAt(location.Document,
            documents?.GetValueOrDefault(location.Document) ?? request.Source, location.Start, location.Length);
    }

    private static object LanguageFormat(WebRequest request)
    {
        if (request.Source is null || string.IsNullOrWhiteSpace(request.SourceRevision))
            throw new WebRuntimeException("language-input-required", "languageFormat requires source and sourceRevision.");
        try { return FirmamentLanguageAnalysisService.Format(request.Source, request.SourceName ?? "model.firmament", request.SourceRevision); }
        catch (InvalidOperationException exception) { throw new WebRuntimeException("format-refused", exception.Message); }
    }

    private static object LanguageSchema() => new
    {
        version = FirmamentSemanticSchemas.Version,
        projectionVersion = FirmamentFieldProjector.Version,
        constructs = FirmamentSemanticSchemas.All.Select(construct => new
        {
            id = construct.Id.Value, construct.Name, construct.Context, construct.Entry,
            construct.Description, construct.CompatibilityAlias,
            fields = construct.Fields.Select(field => new
            {
                id = field.Id.Value, field.Name, kind = field.Kind.ToString(), unit = field.Unit.ToString(),
                field.Required, field.Default, field.Choices, field.Variants, field.Description, field.SourceEditable
            }),
            outputs = construct.Outputs.Select(item => new
            {
                id = item.Id.Value, item.Name, item.Kind, item.SourceAddressable, item.SourceRole
            })
        })
    };

    private static object SetProperty(WebRequest request)
    {
        var session = Session(request);
        if (string.IsNullOrWhiteSpace(request.PropertyId) || request.Value is null)
            throw new WebRuntimeException("property-value-required", "setProperty requires propertyId and a typed value.");
        session.SetProperty(request.PropertyId, request.Value);
        return new { accepted = true, revision = session.Revision, dirty = true };
    }

    private static object SetSource(WebRequest request)
    {
        var session = Session(request);
        if (request.Source is null) throw new WebRuntimeException("source-required", "setSource requires source text.");
        session.SetSource(request.Source, request.SourceName, request.ProjectDocuments);
        return new { accepted = true, revision = session.Revision, dirty = true };
    }

    private static object DescribeConstruct(WebRequest request)
    {
        if (string.IsNullOrWhiteSpace(request.ConstructSemanticId))
            throw new WebRuntimeException("construct-required", "describeConstruct requires a semantic ID.");
        return Session(request).DescribeConstruct(request.ConstructSemanticId);
    }

    private static object RewriteField(WebRequest request)
    {
        if (request.Source is null || string.IsNullOrWhiteSpace(request.SourceRevision) ||
            string.IsNullOrWhiteSpace(request.ConstructSemanticId) || string.IsNullOrWhiteSpace(request.FieldId) ||
            request.FieldValue is null || request.BuildRevision is null)
            throw new WebRuntimeException("rewrite-input-required", "rewriteField requires source, revisions, semantic ID, field ID, and a typed value.");
        return Session(request).RewriteField(request);
    }

    private static object Rebuild(WebRequest request) => Session(request).Rebuild();

    private static object ExportStep(WebRequest request)
    {
        var session = Session(request);
        session.RequireExportRevision(request.BuildRevision);
        var stepText = session.StepText;
        if (stepText is null) throw new WebRuntimeException("step-export-unavailable", "The current document has no STEP product artifact.");
        return new { mediaType = "model/step", fileName = session.Name + ".step", base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(stepText)), revision = session.Revision };
    }

    private static object DisposeSession(WebRequest request)
    {
        if (request.SessionId is not null && Sessions.Remove(request.SessionId, out var session)) session.Dispose();
        return new { disposed = true };
    }

    private static object DisposeRuntime()
    {
        foreach (var session in Sessions.Values) session.Dispose();
        Sessions.Clear();
        return new { disposed = true };
    }

    private static WebModelSession Session(WebRequest request)
        => request.SessionId is not null && Sessions.TryGetValue(request.SessionId, out var session)
            ? session : throw new WebRuntimeException("session-not-found", "The model session was disposed or does not exist.");

    private sealed record WebRequest(string Operation, string? SessionId = null, string? Source = null,
        string? SourceName = null, string? PropertyId = null, WebPropertyValue? Value = null,
        string? SourceRevision = null, int? Offset = null, string? ConstructSemanticId = null,
        string? FieldId = null, FirmamentProjectedValue? FieldValue = null, int? BuildRevision = null,
        bool Performance = false, IReadOnlyDictionary<string, string>? ProjectDocuments = null, string? ProjectRoot = null,
        int? Bridge = null, IReadOnlyList<FirmamentLanguageEditOperation>? Operations = null,
        string? Motion = null, double? TimeSeconds = null, bool PreserveEndpoint = false,
        IReadOnlyList<string>? Formats = null, Aetheris.Geometry.MeasurementRequest? Measurement = null,
        string? Node = null, FirmamentSketchEditRequest? SketchEdit = null);

    /// <summary>
    /// BUILD-PERF-M3 response bridge (request <c>bridge: 1</c>, sent by the SDK). Large numeric arrays
    /// leave as one binary buffer (<see cref="TakeBinary"/>); a rebuild references mesh definitions the
    /// session's previous response already delivered instead of serializing them again.
    /// </summary>
    private static string SerializeBridged(WebRequest request, object? result)
    {
        var owner = (result as WebBuildResult) is { Success: true, Owner: WebModelSession session } ? session : null;
        var bridge = new WebResponseBridge(request.Operation == "rebuild" && owner is not null ? owner.SentDefinitions : null);
        WebResponseBridge.Current = bridge;
        string response;
        try { response = JsonSerializer.Serialize(new { ok = true, result }, BridgeOptions); }
        finally { WebResponseBridge.Current = null; }
        _pendingBinary = bridge.ToArray();
        owner?.MarkDelivered();
        return response;
    }

    private sealed class WebRuntimeException(string code, string message) : Exception(message)
    {
        public string Code { get; } = code;
    }

    private sealed partial class WebModelSession(string id, string source, string sourceName, IReadOnlyDictionary<string, string>? projectDocuments) : IDisposable
    {
        private string _source = source;
        private string _sourceName = sourceName;
        private IReadOnlyDictionary<string, string>? _projectDocuments = projectDocuments;
        private readonly FirmamentCompilationSession _compilationSession = new();
        private readonly FirmamentSceneSession _sceneSession = new();
        private AssemblyCompilationReuse? _lastReuse;
        private AssemblyIr? _assembly;
        private AssemblyIr? _pendingAssembly;
        private CompiledScene? _scene;
        private CompiledScene? _pendingScene;
        private AssemblyDisplayMeshDocument? _exportDisplay;
        private bool _dirty = true;
        private IReadOnlyList<string> _expectedPmi = [];
        public void RequireExportRevision(int? revision)
        {
            if (_dirty || _exportDisplay is null || revision is { } expected && expected != Revision)
                throw new WebRuntimeException("export-stale-revision", "Build the current source successfully before exporting.");
        }
        public object ExportArtifacts(WebRequest request)
        {
            RequireExportRevision(request.BuildRevision);
            var formats = request.Formats ?? [];
            var needsStep = formats.Any(f => f is not ("glb" or "usda")) || formats.Contains("glb") && _expectedPmi.Count > 0;
            try
            {
                var files = ProductArtifactExporter.Export(new(Name, needsStep ? StepText : null, _exportDisplay!, _assembly, _scene, _expectedPmi, _sourceName),
                    formats, Path.GetTempPath());
                var file = ProductArtifactExporter.Package(files);
                return new { revision = Revision, files = new[] { new { file.FileName, file.MediaType, base64 = Convert.ToBase64String(file.Bytes) } } };
            }
            catch (InvalidOperationException error)
            {
                var separator = error.Message.IndexOf(':');
                throw new WebRuntimeException(separator > 0 ? error.Message[..separator] : "export-failed", error.Message);
            }
        }
        public void Dispose() { _measurementTargets = []; _pendingMeasurementTargets = []; _assembly = null; _pendingAssembly = null; _scene = null; _pendingScene = null; _exportDisplay = null; _compilationSession.Dispose(); _sceneSession.Dispose(); }
        internal object SampleMotion(WebRequest request)
        {
            if (_assembly is null || request.Motion is null || request.TimeSeconds is null)
                throw new WebRuntimeException("assembly-motion-query-required", "sampleMotion requires a compiled Assembly, Motion name and timeSeconds.");
            var pose = AssemblyMotion.Evaluate(_assembly, request.Motion, request.TimeSeconds.Value, request.PreserveEndpoint);
            if (!pose.IsSuccess) throw new WebRuntimeException(pose.Diagnostics[0].Code, pose.Diagnostics[0].Message);
            return new { revision = Revision, motion = request.Motion, timeSeconds = request.TimeSeconds, state = pose.State,
                transforms = pose.Instances.Select(i => new { id = i.StableId, matrix = i.ResolvedTransform!.Matrix }).ToArray() };
        }
        private IReadOnlyList<WebProperty> _properties = [];
        private IReadOnlyList<FirmamentConstructProjection> _projections = [];
        private readonly Dictionary<string, WebPropertyValue> _overrides = new(StringComparer.Ordinal);
        private object? _lastSnapshot;
        public string Id { get; } = id;
        public string Name => Path.GetFileNameWithoutExtension(_sourceName);
        public int Revision { get; private set; }
        private object[] _currentDefinitions = [];
        /// <summary>Definitions of the last snapshot a bridged response delivered to the client.</summary>
        internal HashSet<object> SentDefinitions { get; private set; } = new(ReferenceEqualityComparer.Instance);
        internal void MarkDelivered() => SentDefinitions = new(_currentDefinitions, ReferenceEqualityComparer.Instance);
        private string? _stepText;
        private Func<string>? _stepWriter;
        /// <summary>STEP of the current build. Assemblies write it on first request (BUILD-PERF-M1);
        /// their structural export checks still run during the build.</summary>
        public string? StepText
        {
            get
            {
                if (_stepText is null && _stepWriter is { } writer)
                {
                    using var phase = BuildPerfTrace.Phase("web.assembly-step-export");
                    _stepText = writer();
                    _stepWriter = null;
                }
                return _stepText;
            }
        }
        public object Snapshot => _lastSnapshot ?? throw new WebRuntimeException("model-not-built", "The model has no valid snapshot.");

        public void SetSource(string nextSource, string? nextSourceName, IReadOnlyDictionary<string, string>? documents = null)
        {
            if (documents is not null) _projectDocuments = documents;
            _source = nextSource;
            _dirty = true;
            if (!string.IsNullOrWhiteSpace(nextSourceName)) _sourceName = nextSourceName;
            _overrides.Clear();
            _projections = [];
        }

        public object DescribeConstruct(string semanticId)
        {
            var projection = _projections.SingleOrDefault(item => item.SemanticId == semanticId);
            if (projection is null) throw new WebRuntimeException("construct-not-projected", $"No current field projection exists for '{semanticId}'.");
            return new
            {
                version = FirmamentFieldProjector.Version,
                constructId = projection.ConstructId.Value, semanticId = projection.SemanticId,
                projection.FeatureApplicationIdentity,
                sourceRevision = projection.SourceRevision, buildRevision = projection.BuildRevision,
                source = projection.ConstructSpan is { } span ? SourceRefAt(projection.SourceDocument, _source, span.Start, span.Length) : null,
                outputs = FirmamentSemanticSchemas.Get(projection.ConstructId.Value)!.Outputs.Select(item => new
                {
                    id = item.Id.Value, item.Name, item.Kind, item.SourceAddressable, item.SourceRole
                }),
                fields = projection.Fields.Select(field => new
                {
                    fieldId = field.FieldId.Value, name = field.Name, kind = field.Kind.ToString(), unit = field.Unit.ToString(),
                    effectiveValue = field.EffectiveValue, authoredValue = field.AuthoredValue, origin = field.Origin,
                    declaration = field.DeclarationSpan is { } declaration ? SourceRefAt(projection.SourceDocument, _source, declaration.Start, declaration.Length) : null,
                    source = field.ValueSpan is { } value ? SourceRefAt(projection.SourceDocument, _source, value.Start, value.Length) : null,
                    field.Editable, field.ReadOnlyReason
                })
            };
        }

        public object RewriteField(WebRequest request)
        {
            if (request.Source != _source || request.BuildRevision != Revision)
                throw new WebRuntimeException("stale_revision", "The requested source or build revision is stale.");
            var construct = _projections.SingleOrDefault(item => item.SemanticId == request.ConstructSemanticId);
            if (construct is null) throw new WebRuntimeException("construct-not-projected", "The construct has no current field projection.");
            var result = FirmamentFieldProjector.Rewrite(_source, request.SourceRevision!, construct,
                new FirmamentFieldId(request.FieldId!), request.FieldValue!);
            if (!result.Success) throw new WebRuntimeException(result.Code!, result.Message!);
            return new { source = result.NewSource, sourceRevision = result.NewSourceRevision,
                replaced = SourceRefAt(_sourceName, _source, result.ReplacedSpan!.Start, result.ReplacedSpan.Length),
                replacement = result.Replacement };
        }

        public void SetProperty(string propertyId, WebPropertyValue value)
        {
            var property = _properties.SingleOrDefault(candidate => candidate.Id == propertyId)
                ?? throw new WebRuntimeException("property-not-found", $"Editable property '{propertyId}' was not found.");
            if (!property.Writable) throw new WebRuntimeException("property-readonly", $"Property '{propertyId}' is read-only.");
            if (!double.IsFinite(value.Value)) throw new WebRuntimeException("property-value-invalid", "Property values must be finite.");
            if (!string.Equals(value.Unit, property.Unit, StringComparison.Ordinal))
                throw new WebRuntimeException("property-unit-mismatch", $"Property '{property.Name}' requires unit '{property.Unit}'.");
            if (property.Type == "Length" && value.Value <= 0)
                throw new WebRuntimeException("property-out-of-range", $"Property '{property.Name}' must be greater than zero.");
            _overrides[propertyId] = value;
            _dirty = true;
        }

        public WebBuildResult Rebuild()
        {
            using var rebuildPhase = BuildPerfTrace.Phase("web.rebuild");
            var totalWatch = System.Diagnostics.Stopwatch.StartNew();
            var inspectPhase = BuildPerfTrace.Phase("web.property-inspection");
            var sourceProperties = ParameterInspector.Inspect(Id, _sourceName, _source);
            inspectPhase.Dispose();
            var effective = ApplyOverrides(_source, sourceProperties, _overrides);
            _lastReuse = null;
            _pendingAssembly = null;
            _pendingScene = null;
            _pendingMeasurementTargets = [];
            _dirty = true;
            var nextProperties = sourceProperties;
            foreach (var (propertyId, value) in _overrides)
            {
                var index = nextProperties.FindIndex(property => property.Id == propertyId);
                if (index >= 0) nextProperties[index] = nextProperties[index] with { Value = value.Value };
            }
            var rootDocuments = new Dictionary<string, string>(_projectDocuments ?? new Dictionary<string, string>(), StringComparer.Ordinal)
                { [_sourceName] = effective };
            var assembly = FirmamentLanguageAnalysisService.HasAssemblyRoot(effective, _sourceName,
                new FirmamentProjectSnapshot(_sourceName, rootDocuments));
            var scene = SceneAuthoring.HasRoot(effective);
            var compiled = scene ? CompileScene(effective) : assembly ? CompileAssembly(effective, nextProperties) : CompilePart(effective, nextProperties);
            if (!compiled.Success)
                return compiled with { Revision = Revision, RetainedPreviousGeometry = _lastSnapshot is not null };

            Revision++;
            _measurementTargets = _pendingMeasurementTargets;
            _assembly = _pendingAssembly;
            _scene = _pendingScene;
            _exportDisplay = compiled.ExportDisplay ?? (AssemblyDisplayMeshDocument)compiled.Mesh!;
            _dirty = false;
            _expectedPmi = compiled.ExpectedPmi;
            _properties = nextProperties;
            _projections = compiled.Projections ?? [];
            _stepText = compiled.StepText;
            _stepWriter = compiled.StepWriter;
            var changes = new
            {
                changedEntityIds = compiled.EntityIds,
                addedEntityIds = Revision == 1 ? compiled.EntityIds : Array.Empty<string>(),
                removedEntityIds = Array.Empty<string>(),
                meshChanged = true,
                diagnosticsChanged = false
            };
            var perf = BuildPerfTrace.Snapshot();
            var timings = new { compileMilliseconds = compiled.CompileMilliseconds, meshMilliseconds = compiled.MeshMilliseconds,
                totalBeforeSnapshotMilliseconds = totalWatch.Elapsed.TotalMilliseconds, reuse = _lastReuse,
                profile = new { phases = perf.Phases.Select(sample => new { sample.Name, sample.InclusiveMilliseconds,
                    sample.ExclusiveMilliseconds, sample.AllocatedBytes }).ToArray(), counts = perf.Counts,
                    gc0 = perf.Gc0, gc1 = perf.Gc1, gc2 = perf.Gc2 } };
            _lastSnapshot = new
            {
                id = Id, name = Name, revision = Revision, source = _source, sourceName = _sourceName,
                tree = compiled.Tree, properties = _properties, mesh = compiled.Mesh,
                measurementAvailable = _measurementTargets.Count > 0,
                diagnostics = compiled.Diagnostics, changes, timings,
                exportFormats = ProductArtifactExporter.Options(_stepText is not null || _stepWriter is not null, _assembly is null && _scene is null),
                motions = (_assembly?.Motions ?? []).Select(m => new { m.Name, m.DurationSeconds, repeat = m.Repeat.ToString(),
                    tracks = m.Tracks.Select(t => new { t.Name, t.MateStableId, t.JointName, valueDimension = t.Curve.ValueDimension.ToString() }) }).ToArray()
            };
            _currentDefinitions = compiled.Mesh is AssemblyDisplayMeshDocument document ? document.Definitions.Cast<object>().ToArray() : [];
            // The snapshot carries tree, mesh and entity ids; the response does not repeat them.
            return compiled with { Revision = Revision, Model = _lastSnapshot, Changes = changes, StepText = null, StepWriter = null,
                Tree = null, Mesh = null, EntityIds = null, Owner = this };
        }

        private WebBuildResult CompilePart(string effective, List<WebProperty> properties)
        {
            var watch = System.Diagnostics.Stopwatch.StartNew();
            var compilePhase = BuildPerfTrace.Phase("web.compile-and-export");
            var project = _projectDocuments is { Count: > 0 } ? new FirmamentProjectSnapshot(_sourceName, _projectDocuments) : null;
            var build = FirmamentBuildAndExport.CompileSource(effective, Path.GetDirectoryName(_sourceName), project?.Documents);
            compilePhase.Dispose();
            var compileMs = watch.Elapsed.TotalMilliseconds;
            if (!build.IsSuccess || build.Value is null)
                return WebBuildResult.Failed(Diagnostics(build.Diagnostics, _sourceName, effective), compileMs);
            var step = build.Value.StepText;
            BrepBody displayBody;
            if (build.Value.RuntimeBody is { } canonicalBody) displayBody = canonicalBody;
            else
            {
                var displayImportPhase = BuildPerfTrace.Phase("web.display-step-reimport");
                var import = Step242Importer.ImportBody(step);
                displayImportPhase.Dispose();
                if (!import.IsSuccess || import.Value is null)
                    return WebBuildResult.Failed(Diagnostics(import.Diagnostics, _sourceName), compileMs);
                displayBody = import.Value;
            }
            watch.Restart();
            var mappingPhase = BuildPerfTrace.Phase("web.source-projection");
            var definitionId = "definition:" + Sha(step)[..16].ToLowerInvariant();
            var entityId = build.Value.RuntimeCorrespondence?.BodyStableId
                ?? (string.IsNullOrWhiteSpace(build.Value.ExportedFeatureId) ? Id + ":body" : build.Value.ExportedFeatureId);
            _pendingMeasurementTargets = [new(entityId + ":occurrence", displayBody, Aetheris.Kernel.Core.Math.Transform3D.Identity)];
            var sourceMap = build.Value.RuntimeCorrespondence is { } correspondence
                ? new Aetheris.Kernel.Firmament.Materializer.GeometrySourceMap(correspondence) : null;
            WebSourceRef? CompilerSource(string symbol) =>
                sourceMap?.TryGetSourceSpan(symbol, out var span) == true
                    ? SourceRefAt(_sourceName, effective, span.Start, span.Length) : null;
            var boxSource = CompilerSource(entityId);
            // Preserve the exported body category in Kind; report the authored construct separately.
            var parsed = FirmamentV2Parser.Parse(effective, Path.GetDirectoryName(_sourceName), null, null, project?.Documents);
            var semanticConstruct = boxSource is null ? null : parsed.Document?.Solids
                .FirstOrDefault(solid => string.Equals(solid.Name, entityId, StringComparison.Ordinal))?.RecordType;
            IReadOnlyList<FirmamentConstructProjection> projections = _overrides.Count == 0 && parsed.Document is { } document
                ? FirmamentFieldProjector.Project(document, effective, _sourceName, Revision + 1) : [];
            if (_overrides.Count == 0 && build.Value.WireForm is not null)
            {
                var wire = WireFormAuthoring.Parse(effective);
                if (wire.IsSuccess && wire.Value is not null)
                    projections = [.. projections, .. FirmamentFieldProjector.ProjectWireForm(wire.Value, effective, _sourceName, Revision + 1)];
            }
            if (_overrides.Count == 0 && build.Value.ExportedBodyCategory == "section-chain" && LoftAuthoringParser.IsLoftSource(effective))
            {
                var loft = LoftAuthoringParser.Compile(effective, materialize: false);
                if (FirmamentFieldProjector.ProjectLoft(loft, effective, _sourceName, Revision + 1) is { } projection)
                    projections = [.. projections, projection];
            }
            semanticConstruct ??= projections.FirstOrDefault(item => item.SemanticId == entityId)?.ConstructId.Value;
            var featureSources = (build.Value.Features ?? []).ToDictionary(feature => feature.FeatureId,
                feature => projections.FirstOrDefault(p => p.SemanticId == feature.FeatureId)?.ConstructSpan is { } span
                    ? SourceRefAt(_sourceName, effective, span.Start, span.Length) : CompilerSource(feature.FeatureId), StringComparer.Ordinal);
            mappingPhase.Dispose();
            var meshPhase = BuildPerfTrace.Phase("web.mesh-build");
            IReadOnlyList<Aetheris.Kernel.Firmament.Visualization.PmiDisplayAnnotation> annotations;
            IReadOnlyList<WebDiagnostic> presentationDiagnostics = [];
            try { annotations = Aetheris.Kernel.Firmament.Visualization.PmiDisplayProjection.FromStep(step, WebMeshBuilder.TessellationOptions); }
            catch (InvalidOperationException error) when (error.Message.StartsWith("pmi-display-", StringComparison.Ordinal))
            {
                // A missing presentation adapter cannot invalidate admitted engineering geometry.
                // STEP keeps its requirements; annotated GLB export still requires complete projection.
                annotations = [];
                presentationDiagnostics = [new("warning", "pmi-preview-unavailable", error.Message + " STEP remains authoritative. Annotated GLB export requires a supported callout projection.")];
            }
            var mesh = WebMeshBuilder.Build(Name, definitionId, entityId, displayBody, out var exportDisplay,
                build.Value.RuntimeCorrespondence, boxSource, Revision + 1, featureSources, build.Value.Cir, Aetheris.Kernel.Firmament.Visualization.ConceptDisplayProjection.Project(build.Value),
                build.Value.ExportedBodyCategory == "inline-step" ? entityId : null, annotations,
                parsed.Document?.Solids.SingleOrDefault()?.InlineStep);
            meshPhase.Dispose();
            var meshMs = watch.Elapsed.TotalMilliseconds;
            var featureNodes = (build.Value.EngineeringFeatures ?? []).Select(feature => new WebTreeNode(feature.FeatureId, feature.Kind, feature.Name, entityId, [], true,
                    projections.FirstOrDefault(item => item.SemanticId == feature.FeatureId)?.ConstructSpan is { } span
                        ? SourceRefAt(_sourceName, effective, span.Start, span.Length) : null))
                .Concat((build.Value.Features ?? []).Select(feature => new WebTreeNode(feature.FeatureId, feature.Kind, feature.Name, entityId, [], true, featureSources[feature.FeatureId], feature.Diameter,
                    HolePlacement: new(feature.PlacementFace, feature.LocalU, feature.LocalV, feature.ResolvedPoint3)))).ToArray();
            var projectedBodySource = projections.FirstOrDefault(item => item.SemanticId == entityId)?.ConstructSpan is { } bodySpan
                ? SourceRefAt(_sourceName, effective, bodySpan.Start, bodySpan.Length) : null;
            // The tree shows the names the source declares (`Model Bracket`, `Extrude body`); the file
            // stem is only a fallback, so a part has one name in the editor, the tree and the viewport.
            var modelName = Regex.Match(effective, @"\bModel\s+([A-Za-z_]\w*)\s*\{") is { Success: true } model ? model.Groups[1].Value : Name;
            var owner = MaterialOwner(effective, entityId);
            var bodyName = projections.FirstOrDefault(item => item.SemanticId == entityId)?.ConstructSpan is { } named
                && Regex.Match(effective.Substring(named.Start, Math.Min(named.Length, effective.Length - named.Start)), @"^\s*(?:[A-Z]\w*\s+)*?[A-Z]\w*(?:<[^>]*>)?\s+([A-Za-z_]\w*)\s*[{;]") is { Success: true } declared
                ? declared.Groups[1].Value : owner?.Name?.Text ?? modelName;
            var body = new WebTreeNode(entityId, build.Value.ExportedBodyCategory, bodyName, Id, featureNodes.Select(item => item.Id).ToArray(), true,
                boxSource ?? projectedBodySource ?? (owner is null ? null : SourceRefAt(_sourceName, effective, owner.Span.Start, owner.Span.Length))
                    ?? SourceRef(_sourceName, 0, effective.Length), SemanticConstruct: semanticConstruct);
            var root = new WebTreeNode(Id, "Model", modelName, null, [body.Id], true, SourceRef(_sourceName, 0, effective.Length));
            var tree = new { rootId = root.Id, nodes = new[] { root, body }.Concat(featureNodes).ToArray() };
            var expectedPmi = Aetheris.Kernel.Firmament.Drawing.FirmamentDrawingCompiler.AuthoredPmiNames(build.Value);
            return WebBuildResult.Passed(step, tree, mesh, [Id, entityId, .. featureNodes.Select(item => item.Id)], compileMs, meshMs)
                with { Projections = projections, ExportDisplay = exportDisplay, ExpectedPmi = expectedPmi, Diagnostics = presentationDiagnostics };
        }

        private WebBuildResult CompileAssembly(string effective, List<WebProperty> properties)
        {
            var watch = System.Diagnostics.Stopwatch.StartNew();
            // Browser projects are explicit source snapshots. Includes, ports and
            // SectionChain/Loft resources must resolve through the compiler's
            // project path, rather than falling through to the host filesystem.
            var assemblyCompilePhase = BuildPerfTrace.Phase("web.assembly-compile");
            var compilation = _projectDocuments is { Count: > 0 }
                ? _compilationSession.CompileProject(new FirmamentProjectSnapshot(_sourceName,
                    new Dictionary<string, string>(_projectDocuments, StringComparer.Ordinal) { [_sourceName] = effective }))
                : _compilationSession.Compile(effective, _sourceName);
            assemblyCompilePhase.Dispose();
            _lastReuse = compilation.Reuse;
            var compileMs = watch.Elapsed.TotalMilliseconds;
            if (!compilation.IsSuccess || compilation.Ir is null || compilation.Geometry is null)
                return WebBuildResult.Failed(compilation.Diagnostics.Select(d => new WebDiagnostic(d.Severity == AssemblyDiagnosticSeverity.Error ? "error" : "warning", d.Code, d.Message,
                    DiagnosticSource(d), d.LocationNote)).ToArray(), compileMs);
            WebSourceRef? DiagnosticSource(AssemblyDiagnostic diagnostic)
            {
                if (diagnostic.SourceSpan is not { } span) return null;
                var text = span.Source == _sourceName ? effective : _projectDocuments?.GetValueOrDefault(span.Source);
                if (text is null) return new(span.Source, 0, 0, span.Start, span.Length);
                var start = Math.Clamp(span.Start, 0, text.Length);
                var prefix = text.AsSpan(0, start);
                var line = 1; foreach (var character in prefix) if (character == '\n') line++;
                return new(span.Source, line, start - prefix.LastIndexOf('\n'), span.Start, span.Length);
            }
            var assemblyStepPhase = BuildPerfTrace.Phase("web.assembly-step-prepare");
            var step = AssemblyIrAp242Exporter.PrepareExport(compilation);
            assemblyStepPhase.Dispose();
            if (!step.IsSuccess) return WebBuildResult.Failed(Diagnostics(step.Diagnostics, _sourceName), compileMs);
            var writeStep = step.Value;
            string StepWriter()
            {
                var written = writeStep();
                return written.IsSuccess ? written.Value
                    : throw new WebRuntimeException("step-export-failed", string.Join("; ", written.Diagnostics.Select(diagnostic => diagnostic.Message)));
            }
            watch.Restart();
            var assemblyMeshPhase = BuildPerfTrace.Phase("web.assembly-display-mesh");
            var mesh = _compilationSession.ExportDisplayMesh(compilation);
            assemblyMeshPhase.Dispose();
            var meshMs = watch.Elapsed.TotalMilliseconds;
            var nodes = compilation.Ir.Instances.OrderBy(instance => instance.Path.Segments.Count).Select(instance =>
                new WebTreeNode(instance.StableId, instance.Kind.ToString(), instance.Path.Segments.Last(), instance.ParentStableId, instance.ChildrenStableIds, true, null)).ToArray();
            var children = nodes.Where(node => node.ParentId == compilation.Ir.RootInstanceStableId).Select(node => node.Id).ToArray();
            var root = new WebTreeNode(compilation.Ir.RootInstanceStableId, "Assembly", compilation.Ir.Name, null, children, true, SourceRef(_sourceName, 0, effective.Length));
            var tree = new { rootId = root.Id, nodes = nodes.Prepend(root).DistinctBy(node => node.Id).ToArray() };
            _pendingAssembly = compilation.Ir;
            var measurementDefinitions = compilation.Geometry.Artifact.Definitions.ToDictionary(d => d.StableId,
                d => compilation.Geometry.DefinitionBodies[d.DefinitionIdentity], StringComparer.Ordinal);
            _pendingMeasurementTargets = compilation.Geometry.Artifact.Instances.Select(instance =>
                new Aetheris.Geometry.MeasurementTarget(instance.InstanceStableId, measurementDefinitions[instance.DefinitionArtifactStableId],
                    Aetheris.Kernel.Core.Math.Transform3D.FromRowMajor(instance.WorldTransform.Matrix))).ToArray();
            return WebBuildResult.Passed(null, tree, mesh, nodes.Select(node => node.Id).Prepend(root.Id).Distinct().ToArray(), compileMs, meshMs) with { StepWriter = StepWriter };
        }

        private WebBuildResult CompileScene(string effective)
        {
            var watch = System.Diagnostics.Stopwatch.StartNew();
            // A project snapshot is explicit; missing resources never fall through to browser disk.
            var documents = new Dictionary<string, string>(_projectDocuments ?? new Dictionary<string, string>(), StringComparer.Ordinal)
                { [_sourceName] = effective };
            var scenePhase = BuildPerfTrace.Phase("web.scene-compile");
            var compilation = _sceneSession.CompileProject(new FirmamentProjectSnapshot(_sourceName, documents));
            scenePhase.Dispose();
            if (!compilation.IsSuccess || compilation.Scene is null)
                return WebBuildResult.Failed(compilation.Diagnostics.Select(d => new WebDiagnostic("error", d.Code, d.Message)).ToArray(), watch.Elapsed.TotalMilliseconds);
            var compiledScene = compilation.Scene;
            var sceneMeshPhase = BuildPerfTrace.Phase("web.scene-display-projection");
            var mesh = DisplayProjection.Project(compiledScene);
            sceneMeshPhase.Dispose();
            var sourceNodes = compiledScene.Nodes.ToDictionary(n => n.Path, StringComparer.Ordinal);
            WebSourceRef? SceneSource(string path)
            {
                if (!sourceNodes.TryGetValue(path, out var node)) return null;
                var text = documents.GetValueOrDefault(node.Span.Source);
                return text is null ? null : SourceRefAt(node.Span.Source, text, node.Span.Start, node.Span.Length);
            }
            var nodes = mesh.Occurrences.Select(o => new WebTreeNode(o.Id, o.Kind ?? "SceneNode", o.Path.Split('.').Last(), o.ParentId,
                mesh.Occurrences.Where(c => c.ParentId == o.Id).Select(c => c.Id).ToArray(), true, SceneSource(o.Path))).ToArray();
            var tree = new { rootId = mesh.Occurrences.Single(o => o.ParentId is null).Id, nodes };
            _pendingScene = compiledScene;
            return WebBuildResult.Passed(null, tree, mesh, nodes.Select(n => n.Id).ToArray(), watch.Elapsed.TotalMilliseconds, compiledScene.Performance.DisplayPreparationMilliseconds);
        }
    }

    private static string ApplyOverrides(string source, IReadOnlyList<WebProperty> properties, IReadOnlyDictionary<string, WebPropertyValue> overrides)
    {
        var edits = properties.Where(property => overrides.ContainsKey(property.Id)).OrderByDescending(property => property.Start).ToArray();
        var result = source;
        foreach (var property in edits)
        {
            var value = overrides[property.Id];
            result = result[..property.Start] + value.Value.ToString("R", System.Globalization.CultureInfo.InvariantCulture) + value.Unit + result[(property.Start + property.Length)..];
        }
        return result;
    }

    private static IReadOnlyList<WebDiagnostic> Diagnostics(IEnumerable<KernelDiagnostic> diagnostics, string source, string? text = null)
        => diagnostics.Select(diagnostic =>
        {
            var presented = FirmamentBuildAdmissionValidation.Present(diagnostic, source, text);
            var location = presented.SourceSpan is { } span
                ? new WebSourceRef(presented.SourceFile ?? source, presented.Line ?? 0, presented.Column ?? 0, span.Start, span.Length)
                : null;
            return new WebDiagnostic(presented.Severity is "fatal" or "error" ? "error" : presented.Severity,
                presented.Code, presented.Message, location, presented.LocationNote ?? diagnostic.Source);
        }).ToArray();

    private static WebSourceRef SourceRef(string source, int start, int length) => new(source, 1, 1, start, length);

    /// <summary>
    /// The declaration that owns a part's material: the one named like the built entity, else the single
    /// Compose or Extrude. Profile-built bodies carry compiler ids (a Profile name, the Model) rather than this name.
    /// </summary>
    private static Aetheris.Kernel.Firmament.FirmamentV2.Syntax.DeclarationSyntax? MaterialOwner(string source, string entityId)
    {
        var declarations = Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxTraversal.Declarations(
            Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxParser.Parse(source).Document)
            .Where(d => d.Name is not null && d.Type.Name.Text is not ("Model" or "Modify" or "Profile" or "Static" or "Concept")).ToArray();
        var owners = declarations.Where(d => d.Type.Name.Text is "Compose" or "Extrude").ToArray();
        return declarations.FirstOrDefault(d => d.Name!.Text == entityId) ?? (owners.Length == 1 ? owners[0] : null);
    }
    private static WebSourceRef SourceRefAt(string name, string text, int start, int length)
    {
        var prefix = text[..start];
        var line = 1 + prefix.Count(character => character == '\n');
        var lastBreak = prefix.LastIndexOf('\n');
        return new(name, line, start - lastBreak, start, length);
    }
    private static string Sha(string value) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value)));
}

internal static class ParameterInspector
{
    private static readonly Regex Assignment = new(@"(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<literal>-?(?<number>\d+(?:\.\d+)?)\s*(?<unit>mm|cm|m|deg|rad))(?=\s*[,>\r\n])", RegexOptions.CultureInvariant);
    private static readonly Regex BoxSize = new(@"\bSize\s*:\s*\[\s*(?<width>-?\d+(?:\.\d+)?\s*(?:mm|cm|m))\s*,\s*(?<height>-?\d+(?:\.\d+)?\s*(?:mm|cm|m))\s*,\s*(?<thickness>-?\d+(?:\.\d+)?\s*(?:mm|cm|m))\s*\]", RegexOptions.CultureInvariant);
    private static readonly Regex HoleDiameter = new(@"\bDiameter\s*:\s*(?<diameter>-?\d+(?:\.\d+)?\s*(?:mm|cm|m))", RegexOptions.CultureInvariant);

    public static List<WebProperty> Inspect(string modelId, string sourceName, string source)
    {
        var specialization = Regex.Matches(source, @"=\s*[A-Za-z_][A-Za-z0-9_]*\s*<", RegexOptions.CultureInvariant).LastOrDefault();
        if (specialization is null) return InspectDirectModel(modelId, sourceName, source);
        var start = specialization.Index + specialization.Length;
        var depth = 1; var end = start;
        for (; end < source.Length && depth > 0; end++)
        {
            if (source[end] == '<') depth++;
            else if (source[end] == '>') depth--;
        }
        if (depth != 0) return [];
        var segment = source[start..(end - 1)];
        return Assignment.Matches(segment).Select(match =>
        {
            var unit = match.Groups["unit"].Value;
            var number = double.Parse(match.Groups["number"].Value, System.Globalization.CultureInfo.InvariantCulture);
            var literal = match.Groups["literal"];
            var absolute = start + literal.Index;
            var (line, column) = LineColumn(source, absolute);
            var name = match.Groups["name"].Value;
            return new WebProperty($"{modelId}.parameter.{name}", modelId, name, unit is "deg" or "rad" ? "Angle" : "Length", unit, number, true, absolute, literal.Length, new(sourceName, line, column, absolute, literal.Length));
        }).GroupBy(property => property.Name, StringComparer.Ordinal).Select(group => group.Last()).OrderBy(property => property.Name, StringComparer.Ordinal).ToList();
    }

    private static List<WebProperty> InspectDirectModel(string modelId, string sourceName, string source)
    {
        var result = new List<WebProperty>();
        var size = BoxSize.Match(source);
        if (size.Success)
        {
            Add("Width", size.Groups["width"]);
            Add("Height", size.Groups["height"]);
            Add("Thickness", size.Groups["thickness"]);
        }
        var diameter = HoleDiameter.Match(source);
        if (diameter.Success) Add("HoleDiameter", diameter.Groups["diameter"]);
        return result.OrderBy(property => property.Name, StringComparer.Ordinal).ToList();

        void Add(string name, Group literal)
        {
            var parsed = Regex.Match(literal.Value, @"(?<number>-?\d+(?:\.\d+)?)\s*(?<unit>mm|cm|m)", RegexOptions.CultureInvariant);
            var (line, column) = LineColumn(source, literal.Index);
            result.Add(new($"{modelId}.parameter.{name}", modelId, name, "Length", parsed.Groups["unit"].Value,
                double.Parse(parsed.Groups["number"].Value, System.Globalization.CultureInfo.InvariantCulture), true, literal.Index, literal.Length,
                new(sourceName, line, column, literal.Index, literal.Length)));
        }
    }

    private static (int Line, int Column) LineColumn(string source, int offset)
    {
        var line = 1; var column = 1;
        for (var i = 0; i < offset; i++) { if (source[i] == '\n') { line++; column = 1; } else column++; }
        return (line, column);
    }
}

internal static class WebMeshBuilder
{
    internal static DisplayTessellationOptions TessellationOptions { get; } = new(double.Pi / 16, .3, 6, 64);
    public static object Build(string name, string definitionId, string entityId, BrepBody body, out AssemblyDisplayMeshDocument exportDisplay,
        Aetheris.Kernel.Firmament.Materializer.SemanticTopologyCorrespondence? correspondence = null,
        WebSourceRef? source = null, int buildRevision = 0, IReadOnlyDictionary<string, WebSourceRef?>? featureSources = null,
        FirmamentCirRetention? cir = null, IReadOnlyList<Aetheris.Kernel.Firmament.Visualization.ConceptDisplayWire>? concepts = null,
        string? importedBodyName = null, IReadOnlyList<Aetheris.Kernel.Firmament.Visualization.PmiDisplayAnnotation>? annotations = null,
        FirmamentV2InlineStepRecord? importedAsset = null)
    {
        // Browser WASM has no blocking monitor wait. Use the existing synchronous
        // tessellator authority; the Worker transport supplies UI responsiveness.
        var tessPhase = BuildPerfTrace.Phase("web.tessellation");
        var tessellation = BrepDisplayTessellator.Tessellate(body, TessellationOptions);
        tessPhase.Dispose();
        if (!tessellation.IsSuccess) throw new InvalidOperationException(string.Join("; ", tessellation.Diagnostics.Select(item => item.Message)));
        BuildPerfTrace.Count("brep.faces", body.Topology.Faces.Count());
        BuildPerfTrace.Count("brep.edges", body.Topology.Edges.Count());
        BuildPerfTrace.Count("display.triangles", tessellation.Value.FacePatches.Sum(face => face.TriangleIndices.Count / 3));
        BuildPerfTrace.Count("display.edge-polylines", tessellation.Value.EdgePolylines.Count);
        var mapPhase = BuildPerfTrace.Phase("web.mesh-source-map-and-arrays");
        var positions = new List<double>(); var normals = new List<double>(); var indices = new List<int>(); var ranges = new List<object>();
        var sourceMap = correspondence is null ? null : new Aetheris.Kernel.Firmament.Materializer.GeometrySourceMap(correspondence);
        var edgeFinishes = correspondence is null ? null : Aetheris.Kernel.Firmament.Materializer.SingleEdgeFinishSelection.Index(correspondence);
        var edgeFinishReason = correspondence is null ? null : Aetheris.Kernel.Firmament.Materializer.SingleEdgeFinishSelection.UnavailableReason(correspondence);
        foreach (var face in tessellation.Value.FacePatches.OrderBy(face => face.FaceId.Value))
        {
            var vertexOffset = positions.Count / 3; var triangleStart = indices.Count / 3;
            positions.AddRange(face.Positions.SelectMany(point => new[] { point.X, point.Y, point.Z }));
            normals.AddRange(face.Normals.SelectMany(normal => new[] { normal.X, normal.Y, normal.Z }));
            indices.AddRange(face.TriangleIndices.Select(index => index + vertexOffset));
            Aetheris.Kernel.Firmament.Materializer.SemanticTopologyDescendant? semanticFace = null;
            if (sourceMap is not null && sourceMap.TryGetByBrepFace(face.FaceId, out var mappedFace)) semanticFace = mappedFace;
            var owner = semanticFace?.ParentStableId is { } parent && featureSources?.ContainsKey(parent) == true ? parent : entityId;
            var faceSource = owner == entityId ? source : featureSources![owner];
            var imported = importedBodyName is not null && body.Bindings.TryGetFaceBinding(face.FaceId, out var binding) ? binding.SourceStepEntityId : null;
            body.TryGetFaceSurface(face.FaceId, out var surface);
            ranges.Add(new { startTriangle = triangleStart, triangleCount = face.TriangleIndices.Count / 3, faceId = $"face:{face.FaceId.Value}", semanticEntityId = owner,
                semanticTopologyId = semanticFace?.StableId ?? (imported is { } importedEntity ? importedBodyName + ":#" + importedEntity : null), topologyKind = "Face", outputRole = semanticFace?.Role.ToString(), originFeature = semanticFace?.SourceStableId,
                sourceAddressability = imported is not null ? "ImportedStable" : semanticFace?.Addressability.ToString() ?? "RuntimeOnly",
                selector = imported is not null ? $"{importedBodyName}.face(\"#{imported}\")" : semanticFace?.FirmamentSelector,
                surfaceKind = surface?.Kind.ToString(), diameterMm = surface?.Cylinder is { } cylinder ? (double?)(2 * cylinder.Radius) : null,
                support = semanticFace?.FirmamentSelector?.Contains(".Side(", StringComparison.Ordinal) == true
                    ? Aetheris.Kernel.Firmament.Materializer.PlanarFaceThroughHole.Support(body, face.FaceId, semanticFace.SupportOrigin) : null,
                selectorReason = imported is not null ? null : semanticFace is null ? "No compiler-owned source topology mapping is available for this display face."
                    : semanticFace.FirmamentSelector is null ? "Construction identity is known, but Firmament has no qualified source selector for this topology." : null,
                source = semanticFace is null ? null : faceSource, buildRevision });
        }
        mapPhase.Dispose();
        var shader = CirShaderArtifactProvider.Resolve(cir);
        var positionArray = positions.ToArray(); var normalArray = normals.ToArray(); var indexArray = indices.ToArray();
        var transform = new double[] { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 };
        exportDisplay = new("aetheris/display-mesh/1", name, "mm",
            [new(definitionId, entityId, positionArray, normalArray, indexArray)],
            [new(entityId + ":occurrence", name, null, definitionId, transform, entityId)]) { Annotations = annotations ?? [], TessellationOptions = TessellationOptions };
        return new
        {
            schema = "aetheris/display-mesh/1",
            name,
            units = "mm",
            annotations = annotations ?? [],
            importedAsset = importedAsset is null ? null : new { path = importedAsset.SourcePath, sha256 = importedAsset.ContentHash,
                evidence = importedAsset.CanonicalEvidence, qualification = body.ImportQualification },
            definitions = new[] { new { id = definitionId, identity = entityId, positions = positionArray, normals = normalArray, indices = indexArray, ranges,
                cir, shader, geometryRevision = definitionId, displayPath = shader.Artifact is not null ? "cir" : "mesh", fallbackReason = shader.Reason,
                concepts = concepts ?? [],
                edges = tessellation.Value.EdgePolylines.Select(edge =>
                {
                    Aetheris.Kernel.Firmament.Materializer.SemanticTopologyDescendant? semanticEdge = null;
                    if (sourceMap is not null && sourceMap.TryGetByBrepEdge(edge.EdgeId, out var mappedEdge)) semanticEdge = mappedEdge;
                    var owner = semanticEdge?.ParentStableId is { } parent && featureSources?.ContainsKey(parent) == true ? parent : entityId;
                    return new { edgeId = $"edge:{edge.EdgeId.Value}", points = edge.Points.Select(point => new[] { point.X, point.Y, point.Z }).ToArray(), closed = edge.IsClosed,
                        semanticEntityId = owner, semanticTopologyId = semanticEdge?.StableId, topologyKind = "Edge", outputRole = semanticEdge?.Role.ToString(), originFeature = semanticEdge?.SourceStableId,
                        sourceAddressability = semanticEdge?.Addressability.ToString() ?? "RuntimeOnly", selector = semanticEdge?.FirmamentSelector,
                        edgeFinish = edgeFinishes?.GetValueOrDefault(edge.EdgeId),
                        edgeFinishReason = edgeFinishes?.ContainsKey(edge.EdgeId) == true ? null : edgeFinishReason,
                        selectorReason = semanticEdge is null ? "Display BRep edge has no construction-owned source correspondence."
                            : semanticEdge.FirmamentSelector is null ? "Construction identity is known, but Firmament has no qualified source selector for this edge." : null,
                        source = semanticEdge is null ? null : owner == entityId ? source : featureSources![owner], buildRevision };
                }).ToArray() } },
            occurrences = new[] { new { id = entityId + ":occurrence", path = name, parentId = (string?)null, definitionId, semanticEntityId = entityId, transform } }
        };
    }
}

internal sealed record WebPropertyValue(double Value, string Unit);
internal sealed record WebSourceRef(string Source, int Line, int Column, int Start, int Length);
internal sealed record WebProperty(string Id, string OwnerEntityId, string Name, string Type, string Unit, double Value, bool Writable, int Start, int Length, WebSourceRef Source);
internal sealed record WebTreeNode(string Id, string Kind, string Name, string? ParentId, IReadOnlyList<string> Children, bool Visible, WebSourceRef? Source, double? HoleDiameterMm = null, string? SemanticConstruct = null,
    WebHolePlacement? HolePlacement = null);
/// <summary>Where a built hole sits: its support face, the center in that face's local frame, and the world point when resolved.</summary>
internal sealed record WebHolePlacement(string Face, double U, double V, IReadOnlyList<double>? PointMm);
internal sealed record WebDiagnostic(string Severity, string Code, string Message, WebSourceRef? Source = null, string? Details = null);
internal sealed record WebBuildResult(bool Success, int Revision, object? Model, IReadOnlyList<WebDiagnostic> Diagnostics, bool RetainedPreviousGeometry,
    object? Tree = null, object? Mesh = null, IReadOnlyList<string>? EntityIds = null, object? Timings = null, object? Changes = null, string? StepText = null,
    IReadOnlyList<FirmamentConstructProjection>? Projections = null, double CompileMilliseconds = 0, double MeshMilliseconds = 0)
{
    [System.Text.Json.Serialization.JsonIgnore] public AssemblyDisplayMeshDocument? ExportDisplay { get; init; }
    [System.Text.Json.Serialization.JsonIgnore] public IReadOnlyList<string> ExpectedPmi { get; init; } = [];
    /// <summary>The session that produced this build; never serialized.</summary>
    [System.Text.Json.Serialization.JsonIgnore] public object? Owner { get; init; }
    /// <summary>Writes the STEP text on first request; never serialized.</summary>
    [System.Text.Json.Serialization.JsonIgnore] public Func<string>? StepWriter { get; init; }
    public static WebBuildResult Failed(IReadOnlyList<WebDiagnostic> diagnostics, double compileMs) => new(false, 0, null, diagnostics, false, Timings: new { compileMilliseconds = compileMs }, CompileMilliseconds: compileMs);
    public static WebBuildResult Passed(string? step, object tree, object mesh, IReadOnlyList<string> ids, double compileMs, double meshMs) => new(true, 0, null, [], false, tree, mesh, ids, new { compileMilliseconds = compileMs, meshMilliseconds = meshMs }, StepText: step, CompileMilliseconds: compileMs, MeshMilliseconds: meshMs);
}