Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add bounded volume measurement and assertion diagnostics
Yuechen Lid462d911cbf5
diff --git a/Aetheris.CLI.Tests/FirmamentMeasureCliTests.cs b/Aetheris.CLI.Tests/FirmamentMeasureCliTests.csnew file mode 100644index 00000000..136aa8aa--- /dev/null+++ b/Aetheris.CLI.Tests/FirmamentMeasureCliTests.cs@@ -0,0 +1,111 @@+using System.Text.Json;++namespace Aetheris.CLI.Tests;++public sealed class FirmamentMeasureCliTests+{+ private static string Root()+ {+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;+ return directory!.FullName;+ }+ private static string Fixture(string name) => Path.Combine(Root(), "fixtures/Regression/Assertions", name + ".firmament");++ [Fact]+ public void CompilerMeasurementsProvideCopyableAssertionsAndDiscloseTheirLevel()+ {+ var output = new StringWriter(); var error = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["measure", Fixture("box"), "--json"], output, error));+ Assert.Empty(error.ToString());+ using var json = JsonDocument.Parse(output.ToString()); var root = json.RootElement;+ Assert.Equal("MeasuredNotAsserted", root.GetProperty("status").GetString());+ Assert.False(root.GetProperty("assertionsEvaluated").GetBoolean());+ Assert.Equal(480, root.GetProperty("volume").GetProperty("valueMm3").GetDouble());+ Assert.Equal(3, root.GetProperty("assertionTemplates").GetArrayLength());+ Assert.Contains("expected: 480mm^3", root.GetProperty("assertionTemplates")[0].GetString());+ Assert.Equal(6, root.GetProperty("topology").GetProperty("faces").GetInt32());+ }++ [Theory]+ [InlineData(false)]+ [InlineData(true)]+ public void ValidateAndBuildRejectTheSameFailedAssertionOnItsAuthoredLine(bool withExpansion)+ {+ var scratch = Path.Combine(Root(), "artifacts/local/tests/assertions", Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(scratch);+ try+ {+ var path = Path.Combine(scratch, "bad.firmament"); var destination = Path.Combine(scratch, "bad.step");+ var source = (withExpansion ? "Record Unused { value: Length }\n" : "")+ + File.ReadAllText(Fixture("box")).Replace("expected: 480mm^3", "expected: 479mm^3", StringComparison.Ordinal);+ File.WriteAllText(path, source);+ var expectedLine = source[..source.IndexOf("Assert Volume", StringComparison.Ordinal)].Count(c => c == '\n') + 1;+ foreach (var command in new[] { "validate", "build" })+ {+ var output = new StringWriter(); var error = new StringWriter();+ Assert.Equal(1, CliRunner.Run(command == "build" ? [command, path, "--out", destination, "--json"] : [command, path, "--json"], output, error));+ using var json = JsonDocument.Parse(output.ToString()); var root = json.RootElement;+ if (root.TryGetProperty("firmamentV2Validation", out var validation)) root = validation;+ var failure = root.GetProperty("diagnostics").EnumerateArray().Single(d => d.GetProperty("code").GetString() == "firmament-v2-assert-volume-failed");+ Assert.Equal(expectedLine, failure.GetProperty("line").GetInt32());+ }+ Assert.False(File.Exists(destination));+ var measured = new StringWriter(); var measureError = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["measure", path, "--json"], measured, measureError));+ using var report = JsonDocument.Parse(measured.ToString());+ Assert.False(report.RootElement.GetProperty("assertionsEvaluated").GetBoolean());+ }+ finally { Directory.Delete(scratch, true); }+ }++ [Fact]+ public void AssemblyValidationBuildAndInspectionEnforceTheSameStackupAndPreserveItsSpan()+ {+ var scratch = Path.Combine(Root(), "artifacts/local/tests/assertions", Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(scratch);+ try+ {+ var source = File.ReadAllText(Path.Combine(Root(), "fixtures/Canonical/Assembly/template-block-pair.firmament"))+ .Replace("Between:", "between:", StringComparison.Ordinal)+ .Replace("Require: Clearance >= 2mm", "require: clearance >= 3mm", StringComparison.Ordinal);+ var path = Path.Combine(scratch, "bad-stackup.firmament"); var destination = Path.Combine(scratch, "bad.step");+ File.WriteAllText(path, source);+ foreach (var command in new[] { "validate", "build", "inspect" })+ {+ var output = new StringWriter(); var error = new StringWriter();+ var args = command == "inspect" ? new[] { "asm", "inspect", path, "--json" }+ : command == "build" ? [command, path, "--out", destination, "--json"] : [command, path, "--json"];+ Assert.Equal(1, CliRunner.Run(args, output, error));+ using var json = JsonDocument.Parse(output.ToString());+ var failure = json.RootElement.GetProperty("diagnostics").EnumerateArray()+ .Single(d => d.GetProperty("code").GetString() == "assembly-tolerance-assertion-failure");+ Assert.Contains("worst-case minimum 2", failure.GetProperty("message").GetString());+ var span = failure.GetProperty("sourceSpan");+ Assert.StartsWith("Assert ToleranceStackup", source.Substring(span.GetProperty("start").GetInt32(), span.GetProperty("length").GetInt32()));+ if (command == "inspect")+ {+ var stack = json.RootElement.GetProperty("assemblyIr").GetProperty("toleranceStackups")[0];+ Assert.Equal(2, stack.GetProperty("worstCaseMinimum").GetDouble());+ Assert.False(stack.GetProperty("passed").GetBoolean());+ }+ }+ Assert.False(File.Exists(destination));+ }+ finally { Directory.Delete(scratch, true); }+ }++ [Fact]+ public void SdfMeasurementCarriesUncertaintyAndKeepsMeshComparisonDiagnosticOnly()+ {+ var output = new StringWriter(); var error = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["measure", Fixture("sphere"), "--sdf", "--compare-mesh", "--error", "50", "--json"], output, error));+ using var json = JsonDocument.Parse(output.ToString()); var root = json.RootElement;+ var volume = root.GetProperty("volume");+ var expected = 4 * Math.PI * 1000 / 3;+ Assert.InRange(expected, volume.GetProperty("lowerBoundMm3").GetDouble(), volume.GetProperty("upperBoundMm3").GetDouble());+ Assert.True(volume.GetProperty("authoritative").GetBoolean());+ Assert.Equal("SdfAdaptiveOccupiedVolumeInterval", volume.GetProperty("method").GetString());+ Assert.True(root.TryGetProperty("meshComparison", out _));+ }+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex b71d90bb..5e97b833 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -221,6 +221,7 @@ public static class CliRunner"frontend-shadow" => FrontendShadowCommand.Run(args.Skip(1).ToArray(), stdout, stderr),"format" => RunFormat(args.Skip(1).ToArray(), stdout, stderr),"inspect" => RunInspect(args.Skip(1).ToArray(), stdout, stderr),+ "measure" => FirmamentMeasureCommand.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),"inspect-3dm" => ThreeDmCli.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),"recover-3dm" => ThreeDmCli.Recover(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),"inspect-profile" => RunInspectProfile(args.Skip(1).ToArray(), stdout, stderr),@@ -571,6 +572,7 @@ public static class CliRunnerwireForm = build.Value.Export.WireForm,sweep = build.Value.Export.Sweep,assertions = build.Value.Export.Assertions,+ geometryAssertions = build.Value.Export.GeometryAssertions,features = build.Value.Export.Features,engineeringFeatures = build.Value.Export.EngineeringFeatures,edgeFinishPlanning = build.Value.Export.EdgeFinishPlanning,@@ -5229,8 +5231,29 @@ Model CanonicalPanel {var compilation = string.Equals(Path.GetExtension(args[0]), ".firmasm", StringComparison.OrdinalIgnoreCase) && !usesSheetMetalParts? new FirmamentAssemblyDocumentCompiler().CompileFile(args[0]).Compilation: usesSheetMetalParts ? EnclosureProductFamilies.CompileAssemblyFile(args[0]) : new AssemblyM1Pipeline().CompileFile(args[0]);+ if (!compilation.IsSuccess)+ {+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = false, diagnostics = compilation.Diagnostics }, JsonOptions));+ else foreach (var diagnostic in compilation.Diagnostics)+ {+ var span = diagnostic.SourceSpan;+ var file = span?.Source ?? args[0];+ var text = File.Exists(file) ? File.ReadAllText(file) : null;+ var presented = FirmamentBuildAdmissionValidation.Locate(new(diagnostic.Code,+ diagnostic.Severity == AssemblyDiagnosticSeverity.Error ? "error" : "warning", diagnostic.Message)+ { SourceSpan = span is null ? null : new(span.Start, span.Length), LocationNote = diagnostic.LocationNote }, text, file);+ stderr.WriteLine($"{file}:{presented.Line}:{presented.Column}: {presented.Severity} {diagnostic.Code}: {diagnostic.Message}");+ }+ return 1;+ }var export = AssemblyIrAp242Exporter.Export(compilation);- if (!export.IsSuccess) { foreach (var diagnostic in export.Diagnostics) stderr.WriteLine($"{diagnostic.Source}: {diagnostic.Message}"); return 1; }+ if (!export.IsSuccess)+ {+ var diagnostics = export.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, args[0], sourceText)).ToArray();+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = false, diagnostics }, JsonOptions));+ else foreach (var diagnostic in diagnostics) stderr.WriteLine($"{diagnostic.SourceFile}:{diagnostic.Line}:{diagnostic.Column}: {diagnostic.Severity} {diagnostic.Code}: {diagnostic.Message}");+ return 1;+ }var fullOutput = Path.GetFullPath(output); Directory.CreateDirectory(Path.GetDirectoryName(fullOutput)!); File.WriteAllText(fullOutput, export.Value);var hash = Convert.ToHexString(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(export.Value)));stdout.WriteLine(json ? JsonSerializer.Serialize(new { success = true, output = fullOutput, sha256 = hash, occurrenceCount = compilation.Ir!.Instances.Count - 1, definitionCount = compilation.Geometry!.Artifact.Definitions.Count + (compilation.Ir.AssemblyDefinitions?.Count ?? 0) }, JsonOptions) : $"Exported native AP242 assembly: {fullOutput} sha256={hash}");@@ -5305,6 +5328,7 @@ Model CanonicalPanel {stdout.WriteLine(" mesh Export a supported exact B-rep as STL or topology-preserving OBJ.");stdout.WriteLine(" view Build/open a model in Cadmata.");stdout.WriteLine(" inspect Inspect Firmament semantics or STEP topology.");+ stdout.WriteLine(" measure Measure a compiled part and print assertion templates without claiming its assertions passed.");stdout.WriteLine(" inspect-3dm Inventory local Rhino 3DM geometry and import blockers.");stdout.WriteLine(" recover-3dm Measure Rhino recovery candidates or bind qualified BReps to STEP.");stdout.WriteLine(" analyze Analyze STEP topology and analytic surfaces.");diff --git a/Aetheris.CLI/FirmamentMeasureCommand.cs b/Aetheris.CLI/FirmamentMeasureCommand.csnew file mode 100644index 00000000..48ead35d--- /dev/null+++ b/Aetheris.CLI/FirmamentMeasureCommand.cs@@ -0,0 +1,68 @@+using System.Globalization;+using System.Text.Json;+using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Firmament;+using Aetheris.Kernel.Firmament.Analysis;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.CLI;++internal static class FirmamentMeasureCommand+{+ private const string Usage = "Usage: aetheris measure <part.firmament> [--sdf] [--error <mm3>] [--compare-mesh] [--json]";+ internal static int Run(string[] args, TextWriter stdout, TextWriter stderr, JsonSerializerOptions jsonOptions)+ {+ if (args.Length == 0 || args[0] is "--help" or "-h")+ { (args.Length == 0 ? stderr : stdout).WriteLine(Usage); return args.Length == 0 ? 1 : 0; }+ var json = args.Contains("--json"); var sdf = false; var mesh = false; double? error = null;+ for (var i = 1; i < args.Length; i++)+ switch (args[i])+ {+ case "--json": break;+ case "--sdf": sdf = true; break;+ case "--compare-mesh": mesh = true; break;+ case "--error" when i + 1 < args.Length && double.TryParse(args[++i], NumberStyles.Float, CultureInfo.InvariantCulture, out var n) && double.IsFinite(n) && n >= 0: error = n; break;+ default: stderr.WriteLine(Usage); return 1;+ }+ var path = Path.GetFullPath(args[0]); var source = File.ReadAllText(path);+ var built = FirmamentBuildAndExport.CompileForMeasurement(source, Path.GetDirectoryName(path));+ if (!built.IsSuccess)+ {+ var diagnostics = built.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, path, source)).ToArray();+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = false, geometryBuilt = false, assertionsEvaluated = false, diagnostics }, jsonOptions));+ else foreach (var d in diagnostics) stderr.WriteLine($"{d.SourceFile}:{d.Line}:{d.Column}: {d.Severity} {d.Code}: {d.Message}");+ return 1;+ }+ var measurements = new FirmamentMeasurements(built.Value);+ var volume = measurements.Volume(error, sdf);+ var bounds = measurements.Bounds;+ var topology = measurements.Topology;+ var snippets = new List<string>();+ string N(double value) => value.ToString("G17", CultureInfo.InvariantCulture);+ if (measurements.TargetBodyId is { } target)+ {+ if (volume.ValueMm3 is { } value && volume.ErrorBoundMm3 is { } uncertainty)+ snippets.Add($"Assert Volume {target} {{ expected: {N(value)}mm^3; tolerance: {N(uncertainty == 0 ? 0 : uncertainty * 1.1)}mm^3; }}");+ if (bounds is not null) snippets.Add($"Assert Bounds {target} {{ min: [{string.Join(", ", bounds.MinimumMm.Select(v => N(v) + "mm"))}]; max: [{string.Join(", ", bounds.MaximumMm.Select(v => N(v) + "mm"))}]; tolerance: 0mm; }}");+ snippets.Add($"Assert Topology {target} {{ faces: {topology.Faces}; edges: {topology.Edges}; vertices: {topology.Vertices}; shells: {topology.Shells}; }}");+ }+ var comparison = mesh ? BrepMassProperties.Evaluate(measurements.Body) : null;+ var notes = new[] { "Measurements only: declared assertions were not evaluated. This is not validation success.",+ "Suggested verification tolerances cover numerical uncertainty; choose the design's acceptance range independently.",+ "Bounds are exact only for qualified rectangular stock or planar straight-edge bodies. SDF bounds are enclosing domains, not necessarily the tight bounds of Boolean results." };+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "measure", success = volume.Authoritative, geometryBuilt = true,+ status = "MeasuredNotAsserted", assertionsEvaluated = false, target = measurements.TargetBodyId, volume, bounds, topology,+ meshComparison = comparison, assertionTemplates = snippets, notes }, jsonOptions));+ else+ {+ stdout.WriteLine("MeasuredNotAsserted — declared assertions were not evaluated.");+ stdout.WriteLine(FormattableString.Invariant($"Volume: {volume.ValueMm3:G17} mm^3; interval [{volume.LowerBoundMm3:G17}, {volume.UpperBoundMm3:G17}]; method={volume.Method}; errorBound={volume.ErrorBoundMm3:G17} mm^3"));+ if (volume.Diagnostic is { } message) stderr.WriteLine(message);+ stdout.WriteLine($"Topology: {topology.Faces} faces, {topology.Edges} edges, {topology.Vertices} vertices, {topology.Shells} shells");+ foreach (var snippet in snippets) stdout.WriteLine(snippet);+ if (comparison is not null) stdout.WriteLine(FormattableString.Invariant($"Mesh comparison (diagnostic only): {comparison.AbsoluteVolume:G17} mm^3; {comparison.EvaluationMethod}"));+ stdout.WriteLine(notes[1]);+ }+ return volume.Authoritative ? 0 : 1;+ }+}diff --git a/Aetheris.Continuum.Tests/Backends/Sdf/BoundedVolumeTests.cs b/Aetheris.Continuum.Tests/Backends/Sdf/BoundedVolumeTests.csnew file mode 100644index 00000000..e5c33a40--- /dev/null+++ b/Aetheris.Continuum.Tests/Backends/Sdf/BoundedVolumeTests.cs@@ -0,0 +1,53 @@+using Aetheris.Continuum.Backends.Sdf;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Continuum.Tests.Backends.Sdf;++public sealed class BoundedVolumeTests+{+ [Theory]+ [InlineData(1)]+ [InlineData(10001)]+ [InlineData(100001)]+ public void SphereEnclosureContainsAnalyticVolumeEvenWhenBudgetRunsOut(int budget)+ {+ var sphere = new SdfSphereNode(10);+ var result = SdfAdaptiveVolumeEstimator.EstimateBounded(SdfTapeLowerer.Lower(sphere), sphere.Bounds, 50, budget);+ var expected = 4 * Math.PI * 1000 / 3;+ Assert.InRange(expected, result.LowerBound, result.UpperBound);+ Assert.InRange(result.RegionsVisited, 1, budget);+ Assert.Equal(result, SdfAdaptiveVolumeEstimator.EstimateBounded(SdfTapeLowerer.Lower(sphere), sphere.Bounds, 50, budget));+ if (budget == 1) Assert.True(result.BudgetExhausted);+ }++ [Fact]+ public void ConeIntervalIncludesInteriorEvenWhenEveryCornerIsOutside()+ {+ var cone = new SdfConeNode(4, 2, 8);+ var tape = SdfTapeLowerer.Lower(cone);+ var interval = tape.EvaluateInterval(cone.Bounds);+ Assert.True(tape.Evaluate(new Point3D(0, 0, 0)) < 0);+ Assert.True(interval.MinValue < 0);+ var result = SdfAdaptiveVolumeEstimator.EstimateBounded(tape, cone.Bounds, 10, 30001);+ var expected = Math.PI * 8 * (16 + 8 + 4) / 3;+ Assert.InRange(expected, result.LowerBound, result.UpperBound);+ }++ [Fact]+ public void InvalidBudgetsDoNotStartUnboundedWork()+ {+ var sphere = new SdfSphereNode(1);+ var tape = SdfTapeLowerer.Lower(sphere);+ Assert.Throws<ArgumentException>(() => SdfAdaptiveVolumeEstimator.EstimateBounded(tape, sphere.Bounds, double.NaN));+ Assert.Throws<ArgumentException>(() => SdfAdaptiveVolumeEstimator.EstimateBounded(tape, sphere.Bounds, 0, 0));+ }++ [Fact]+ public void BooleanCavityBoundsContainTheIndependentAnalyticDifference()+ {+ var shell = new SdfSubtractNode(new SdfSphereNode(10), new SdfSphereNode(5));+ var result = SdfAdaptiveVolumeEstimator.EstimateBounded(SdfTapeLowerer.Lower(shell), shell.Bounds, 50, 100001);+ Assert.InRange(4 * Math.PI * (1000 - 125) / 3, result.LowerBound, result.UpperBound);+ Assert.True(result.LowerBound > 0);+ }+}diff --git a/Aetheris.Continuum/Backends/Sdf/SdfAdaptiveVolumeEstimator.cs b/Aetheris.Continuum/Backends/Sdf/SdfAdaptiveVolumeEstimator.csindex b1306b41..5a6cc0dc 100644--- a/Aetheris.Continuum/Backends/Sdf/SdfAdaptiveVolumeEstimator.cs+++ b/Aetheris.Continuum/Backends/Sdf/SdfAdaptiveVolumeEstimator.cs@@ -35,8 +35,58 @@ public sealed record SdfAdaptiveVolumeResult(IReadOnlyList<SdfAdaptiveTraceEvent> TraceEvents,IReadOnlyList<string> Notes);+public sealed record SdfBoundedVolumeResult(double LowerBound, double UpperBound, int RegionsVisited, bool BudgetExhausted)+{+ public double EstimatedVolume => (LowerBound + UpperBound) * .5;+ public double ErrorBound => (UpperBound - LowerBound) * .5;+}+public static class SdfAdaptiveVolumeEstimator{+ /// <summary>Occupied-volume enclosure. Mixed cells contribute [0, cell volume],+ /// never a sampling-based error claim. Refine the largest uncertainty first.+ /// Bounds assume the tape's supported analytic interval contract and finite+ /// enclosing input bounds; roundoff guards are included, not formal interval arithmetic.</summary>+ public static SdfBoundedVolumeResult EstimateBounded(SdfTape tape, SdfBounds bounds, double absoluteError,+ int maximumRegions = 100_001, int maximumDepth = 30)+ {+ ArgumentNullException.ThrowIfNull(tape);+ var enclosingVolume = RegionVolume(bounds);+ if (!double.IsFinite(absoluteError) || absoluteError < 0 || maximumRegions < 1 || maximumDepth < 0+ || !double.IsFinite(enclosingVolume) || enclosingVolume <= 0+ || bounds.SizeX <= 0 || bounds.SizeY <= 0 || bounds.SizeZ <= 0)+ throw new ArgumentException("Bounded volume requires finite positive bounds, a nonnegative error and a positive region budget.");+ var queue = new PriorityQueue<(SdfBounds Region, int Depth), (double Volume, int Order)>();+ double inside = 0, uncertain = 0;+ var visited = 0;+ var padding = 1e-12 * Math.Max(1, new[] { bounds.Min.X, bounds.Min.Y, bounds.Min.Z, bounds.Max.X, bounds.Max.Y, bounds.Max.Z }.Max(Math.Abs));+ void Admit(SdfBounds region, int depth)+ {+ var interval = tape.EvaluateInterval(region);+ var volume = RegionVolume(region);+ visited++;+ if (!double.IsFinite(interval.MinValue) || !double.IsFinite(interval.MaxValue) || interval.MinValue > interval.MaxValue)+ throw new InvalidOperationException("sdf-volume-interval-invalid: The field returned no finite conservative interval.");+ if (interval.MaxValue < -padding) inside += volume;+ else if (interval.MinValue <= padding)+ {+ uncertain += volume;+ if (depth < maximumDepth) queue.Enqueue((region, depth), (-volume, visited));+ }+ }+ Admit(bounds, 0);+ while (uncertain > 2 * absoluteError && queue.Count > 0 && visited + 2 <= maximumRegions)+ {+ var item = queue.Dequeue();+ uncertain -= RegionVolume(item.Region);+ foreach (var child in SplitLongestAxis(item.Region)) Admit(child, item.Depth + 1);+ }+ var roundoff = enclosingVolume * 1e-12;+ var lower = Math.Max(0, inside - roundoff);+ var upper = Math.Min(enclosingVolume, inside + Math.Max(0, uncertain) + roundoff);+ return new(lower, upper, visited, upper - lower > 2 * absoluteError);+ }+public static SdfAdaptiveVolumeResult EstimateVolume(SdfTape tape, SdfBounds bounds, SdfAdaptiveVolumeOptions? options = null, ToleranceContext? tolerance = null){ArgumentNullException.ThrowIfNull(tape);diff --git a/Aetheris.Fields/SdfTape.cs b/Aetheris.Fields/SdfTape.csindex 1b259538..b9e050d3 100644--- a/Aetheris.Fields/SdfTape.cs+++ b/Aetheris.Fields/SdfTape.cs@@ -292,17 +292,13 @@ public sealed class SdfTapeprivate static FieldInterval EvaluateConeInterval(SdfBounds region, SdfTapeConePayload payload){var local = TransformBounds(region, payload.InverseTransform);- var corners = GetCorners(local);- var min = double.PositiveInfinity;- var max = double.NegativeInfinity;- foreach (var c in corners)- {- var value = SdfConeNode.EvaluateFiniteCone(c, payload.BottomRadius, payload.TopRadius, payload.Height);- min = double.Min(min, value);- max = double.Max(max, value);- }-- return new FieldInterval(min, max);+ // Corner samples are not bounds: a region can contain the cone while+ // all eight corners are outside. The finite-cone distance is 1-Lipschitz+ // in local coordinates, so its center +/- half diagonal encloses it.+ var center = new Point3D((local.Min.X + local.Max.X) * .5, (local.Min.Y + local.Max.Y) * .5, (local.Min.Z + local.Max.Z) * .5);+ var distance = SdfConeNode.EvaluateFiniteCone(center, payload.BottomRadius, payload.TopRadius, payload.Height);+ var radius = .5 * double.Sqrt(local.SizeX * local.SizeX + local.SizeY * local.SizeY + local.SizeZ * local.SizeZ);+ return new FieldInterval(distance - radius, distance + radius);}private static SdfBounds TransformBounds(SdfBounds bounds, Transform3D transform)diff --git a/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs b/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.csindex 0814fab7..dad9c5fe 100644--- a/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs+++ b/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs@@ -81,6 +81,22 @@ public sealed record BrepMassPropertiesResult(/// </summary>public static class BrepMassProperties{+ /// <summary>Exact occupied-volume recognition only. Never invokes display tessellation.</summary>+ public static bool TryEvaluateExactVolume(BrepBody body, out BrepMassPropertiesResult result)+ {+ ArgumentNullException.ThrowIfNull(body);+ var topology = ValidateTopology(body);+ result = null!;+ return topology.IsEnclosed && topology.IsOrientationConsistent+ && TryEvaluateExactVolumeCore(body, BrepMassPropertiesOptions.Default, topology, out result);+ }++ private static bool TryEvaluateExactVolumeCore(BrepBody body, BrepMassPropertiesOptions options,+ BrepMassPropertiesTopologyDiagnostics topology, out BrepMassPropertiesResult result) =>+ TryEvaluateExactSphereCylinderSeamBody(body, options, topology, out result)+ || TryEvaluateExactVerticalLineArcPrism(body, options, topology, out result)+ || TryEvaluateExactAxisAlignedBoxQuarterCylinderFillet(body, options, topology, out result);+public static BrepMassPropertiesResult Evaluate(BrepBody body, BrepMassPropertiesOptions? options = null){ArgumentNullException.ThrowIfNull(body);@@ -196,9 +212,7 @@ public static class BrepMassPropertiesvar topology = ValidateTopology(body);if (!topology.IsEnclosed)return Unavailable(effective, topology, "Mass properties require a closed, orientable material boundary.");- if (TryEvaluateExactSphereCylinderSeamBody(body, effective, topology, out var exact)- || TryEvaluateExactVerticalLineArcPrism(body, effective, topology, out exact)- || TryEvaluateExactAxisAlignedBoxQuarterCylinderFillet(body, effective, topology, out exact))+ if (TryEvaluateExactVolumeCore(body, effective, topology, out var exact))return exact;var coarse = EvaluateAtResolution(body, effective, refinement: 1);if (coarse.Error is not null) return Unavailable(effective, topology, coarse.Error);diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/ToleranceStackupAssertionTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/ToleranceStackupAssertionTests.csnew file mode 100644index 00000000..4f6eaacd--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/ToleranceStackupAssertionTests.cs@@ -0,0 +1,86 @@+using Aetheris.Kernel.Firmament.Assembly;++namespace Aetheris.Kernel.Firmament.Tests.Assembly;++public sealed class ToleranceStackupAssertionTests+{+ private static string Source() => File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Assembly/bearing-module.firmament"));++ [Fact]+ public void ModernFieldsPreserveTheWorstCaseChainAndAuthoredLocation()+ {+ var source = Source().Replace("Between:", "between:", StringComparison.Ordinal)+ .Replace("Require: Clearance", "require: clearance", StringComparison.Ordinal);+ var parsed = new AssemblyM0Parser().Parse(source, "stackup.firmament");+ Assert.True(parsed.IsSuccess, string.Join("; ", parsed.Diagnostics.Select(d => d.Message)));+ var assertion = Assert.Single(parsed.Source!.StackupAsserts);+ Assert.StartsWith("Assert ToleranceStackup", source.Substring(assertion.SourceSpan!.Start, assertion.SourceSpan.Length));+ var compiled = new AssemblyM0Compiler().Compile(parsed.Source);+ Assert.True(compiled.IsSuccess, string.Join("; ", compiled.Diagnostics.Select(d => d.Message)));+ var stackup = Assert.Single(compiled.Ir!.ToleranceStackups);+ Assert.Equal(45, stackup.Nominal);+ Assert.Equal(44.92, stackup.WorstCaseMinimum, 8);+ Assert.Equal(45.1, stackup.WorstCaseMaximum, 8);+ Assert.Equal(6, stackup.Contributions.Count);+ }++ [Fact]+ public void FailedStackupKeepsItsMessageAndOriginalSpan()+ {+ var source = Source().Replace(">= 44.90mm", ">= 45mm", StringComparison.Ordinal);+ var parsed = new AssemblyM0Parser().Parse(source, "stackup.firmament");+ Assert.True(parsed.IsSuccess);+ var result = new AssemblyM0Compiler().Compile(parsed.Source!);+ Assert.False(result.IsSuccess);+ var diagnostic = Assert.Single(result.Diagnostics.Where(d => d.Code == AssemblyM0Compiler.ToleranceAssertionFailure));+ Assert.Contains("44.92", diagnostic.Message);+ Assert.Equal("stackup.firmament", diagnostic.SourceSpan!.Source);+ Assert.StartsWith("Assert ToleranceStackup", source.Substring(diagnostic.SourceSpan.Start, diagnostic.SourceSpan.Length));+ }++ [Theory]+ [InlineData("Require: Clearance", "Requre: Clearance")]+ [InlineData("Require: Clearance >= 44.90mm;", "Require: Clearance >= 44.90mm; unexpected: 1mm;")]+ [InlineData("Between:", "between: [A, B]; Between:")]+ public void ExtraMisspelledAndDuplicateFieldsCannotBypassAdmission(string before, string after)+ {+ var parsed = new AssemblyM0Parser().Parse(Source().Replace(before, after, StringComparison.Ordinal));+ Assert.False(parsed.IsSuccess);+ Assert.Contains(parsed.Diagnostics, d => d.Code.Contains("field-unknown", StringComparison.Ordinal) || d.Code.Contains("field-duplicate", StringComparison.Ordinal));+ Assert.All(parsed.Diagnostics, d => Assert.NotNull(d.SourceSpan));+ }++ [Fact]+ public void ReversedPathReversesAsymmetricToleranceContributions()+ {+ var source = Source().Replace("[BearingModule.FixedSupport.Housing.Datum, BearingModule.Rotor.Shaft.Shoulder]",+ "[BearingModule.Rotor.Shaft.Shoulder, BearingModule.FixedSupport.Housing.Datum]", StringComparison.Ordinal)+ .Replace(">= 44.90mm", ">= -45.11mm", StringComparison.Ordinal);+ var parsed = new AssemblyM0Parser().Parse(source);+ Assert.True(parsed.IsSuccess);+ var compiled = new AssemblyM0Compiler().Compile(parsed.Source!);+ Assert.True(compiled.IsSuccess, string.Join("; ", compiled.Diagnostics.Select(d => d.Message)));+ var stackup = Assert.Single(compiled.Ir!.ToleranceStackups);+ Assert.Equal(-45.1, stackup.WorstCaseMinimum, 8);+ Assert.Equal(-44.92, stackup.WorstCaseMaximum, 8);+ }++ [Theory]+ [InlineData(false)]+ [InlineData(true)]+ public void MissingAndAmbiguousDimensionalPathsRejectAtTheAssertion(bool ambiguous)+ {+ var source = Source();+ var start = source.IndexOf(" Relation HousingSeatDepth:", StringComparison.Ordinal);+ var end = source.IndexOf(';', start) + 1;+ var relation = source[start..end];+ source = ambiguous ? source.Insert(end, "\n" + relation.Replace("HousingSeatDepth:", "AlternateDepth:", StringComparison.Ordinal))+ : source.Remove(start, end - start);+ var parsed = new AssemblyM0Parser().Parse(source);+ Assert.True(parsed.IsSuccess);+ var result = new AssemblyM0Compiler().Compile(parsed.Source!);+ Assert.False(result.IsSuccess);+ var diagnostic = Assert.Single(result.Diagnostics, d => d.Code == (ambiguous ? AssemblyM0Compiler.TolerancePathAmbiguous : AssemblyM0Compiler.TolerancePathMissing));+ Assert.StartsWith("Assert ToleranceStackup", source.Substring(diagnostic.SourceSpan!.Start, diagnostic.SourceSpan.Length));+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentAssertionsTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentAssertionsTests.csnew file mode 100644index 00000000..58404dac--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentAssertionsTests.cs@@ -0,0 +1,123 @@+using Aetheris.Kernel.Firmament.Analysis;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentAssertionsTests+{+ private static string Source(string name) => File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Regression/Assertions/" + name + ".firmament"));++ [Fact]+ public void ExactVolumeBoundsAndTopologyGateTheRealCompilationWithoutChangingGeometry()+ {+ var source = Source("box");+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));+ Assert.True(Assert.Single(built.Value.Assertions!).Passed);+ Assert.Equal("Passed", built.Value.Assertions![0].VerificationStatus);+ Assert.Equal(2, built.Value.GeometryAssertions.Count);+ Assert.All(built.Value.GeometryAssertions, a => Assert.True(a.Passed));+ var measured = FirmamentBuildAndExport.CompileForMeasurement(source);+ Assert.True(measured.IsSuccess);+ Assert.Equal(measured.Value.StepText, built.Value.StepText);+ var report = new FirmamentMeasurements(measured.Value);+ Assert.Equal("Body", report.TargetBodyId);+ Assert.Equal(480, report.Volume().ValueMm3);+ Assert.Equal([-5d, -4, 0], report.Bounds!.MinimumMm);+ }++ [Fact]+ public void AThroughHoleRemovesTheAnalyticCylinderVolumeAndPreservesStockBounds()+ {+ var source = Source("through-hole-plate");+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));+ var measured = new FirmamentMeasurements(built.Value);+ Assert.InRange(Math.Abs(measured.Volume().ValueMm3!.Value - (80 * 50 * 8 - Math.PI * 4 * 4 * 8)), 0, 1e-8);+ Assert.Equal([-40d, -25, 0], measured.Bounds!.MinimumMm);+ Assert.Equal([40d, 25, 8], measured.Bounds.MaximumMm);+ Assert.All(built.Value.GeometryAssertions, a => Assert.True(a.Passed));+ Assert.Equal(FirmamentBuildAndExport.CompileForMeasurement(source).Value.StepText, built.Value.StepText);+ }++ [Theory]+ [InlineData("expected: 480mm^3", "expected: 479mm^3", "firmament-v2-assert-volume-failed")]+ [InlineData("faces: 6", "faces: 5", "firmament-v2-assert-topology-failed")]+ [InlineData("max: [5mm", "max: [6mm", "firmament-v2-assert-bounds-failed")]+ public void FalseAssertionsFailAtTheirOwnSourceSpan(string before, string after, string code)+ {+ var source = Source("box").Replace(before, after, StringComparison.Ordinal);+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.False(built.IsSuccess);+ var diagnostic = Assert.Single(built.Diagnostics.Where(d => d.Message.StartsWith(code, StringComparison.Ordinal)));+ Assert.NotNull(diagnostic.SourceSpan);+ Assert.StartsWith("Assert ", source.Substring(diagnostic.SourceSpan!.Start, diagnostic.SourceSpan.Length));+ Assert.True(FirmamentBuildAndExport.CompileForMeasurement(source).IsSuccess);+ }++ [Fact]+ public void UnknownFieldsAndNonExportedTargetsNeverDisappear()+ {+ var unknown = FirmamentV2Parser.Parse(Source("box").Replace("tolerance: 0mm^3", "tolerence: 0mm^3", StringComparison.Ordinal));+ Assert.False(unknown.IsSuccess);+ Assert.Contains(unknown.Diagnostics, d => d.Contains("field-unknown", StringComparison.Ordinal));+ var wrong = FirmamentBuildAndExport.CompileSource(Source("two-bodies"));+ Assert.False(wrong.IsSuccess);+ Assert.Contains(wrong.Diagnostics, d => d.Message.StartsWith("firmament-v2-multiple-material-bodies-unsupported", StringComparison.Ordinal));+ }++ [Fact]+ public void SdfSphereAssertionUsesAnIntervalRatherThanMeshMass()+ {+ var built = FirmamentBuildAndExport.CompileSource(Source("sphere"));+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));+ var field = new FirmamentMeasurements(built.Value).Volume(50, forceSdf: true);+ Assert.Equal("SdfAdaptiveOccupiedVolumeInterval", field.Method);+ Assert.InRange(4 * Math.PI * 1000 / 3, field.LowerBoundMm3!.Value, field.UpperBoundMm3!.Value);+ Assert.True(field.RegionsVisited > 1);+ }++ [Fact]+ public void DisplayEligibilityAloneCannotAuthorizeAnSdfVolumeAssertion()+ {+ var built = FirmamentBuildAndExport.CompileForMeasurement(Source("sphere"));+ Assert.True(built.IsSuccess);+ var displayOnly = built.Value with { Cir = built.Value.Cir! with { RuntimeRootIsExportedPrimitive = false } };+ var measurement = new FirmamentMeasurements(displayOnly).Volume(forceSdf: true);+ Assert.False(measurement.Authoritative);+ Assert.Null(measurement.ValueMm3);+ Assert.Contains("Display-only or legacy Boolean mirrors", measurement.Diagnostic);+ }++ [Fact]+ public void APartAssertionCannotDisappearInADedicatedRevolveOwner()+ {+ var path = FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Canonical/Revolve/sphere.firmament");+ var source = File.ReadAllText(path);+ Assert.True(FirmamentV2Parser.Parse(source).IsSuccess);+ source = source.Insert(source.LastIndexOf('}'), "Assert Topology Ball { shells: 42 }\n");+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.False(parsed.IsSuccess);+ Assert.Contains(parsed.Diagnostics, d => d.Contains("assert-owner-unsupported", StringComparison.Ordinal)+ || d.Contains("declaration-unknown", StringComparison.Ordinal));+ }++ [Fact]+ public void UncertaintyOverlappingTheLimitCannotPassOrPretendToBeADesignMismatch()+ {+ var assertion = new FirmamentV2VolumeAssertion("test", "Body", 480, 1, null, new(0, 1));+ var result = FirmamentV2VolumeAssertionComparer.Compare(assertion,+ new FirmamentVolumeMeasurement(480, 470, 490, "BoundedSdf", true));+ Assert.False(result.Passed);+ Assert.Equal("Unverified", result.VerificationStatus);+ Assert.StartsWith("firmament-v2-assert-volume-unverified:", result.Diagnostic);+ }++ [Fact]+ public void ValidationErrorsRemainErrorsInTheSdkProjection()+ {+ var adapted = Aetheris.Kernel.Firmament.FirmamentV2.FirmamentInterop.FirmamentV2DiagnosticAdapter.FromValidationDiagnostic(+ new("firmament-v2-assert-volume-failed", "error", "The measured volume is outside the allowed range."));+ Assert.Equal(Aetheris.Forge.Abstractions.FirmamentInterop.FirmamentDiagnosticSeverity.Fatal, adapted.Severity);+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentCorpusHarness.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentCorpusHarness.csindex 7176fab6..0ed5a562 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentCorpusHarness.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentCorpusHarness.cs@@ -68,6 +68,23 @@ internal static class FirmamentCorpusHarnessvar request = new FirmamentCompileRequest(new FirmamentSourceDocument(fixtureText));return compiler.Compile(request);}++ // These preserved historical specimens asserted a curved-fillet volume+ // while only a display mesh was measured. Qualify their geometry separately+ // and require ordinary compilation to disclose the missing volume authority.+ public static FirmamentStepExportResult InspectUnverifiedVolumeSpecimen(string fullPath)+ {+ var source = NormalizeLf(File.ReadAllText(fullPath));+ var rejected = FirmamentBuildAndExport.CompileSource(source, Path.GetDirectoryName(fullPath));+ Assert.False(rejected.IsSuccess);+ Assert.Contains(rejected.Diagnostics, d => d.Message.StartsWith("firmament-v2-assert-volume-measurement-unavailable:", StringComparison.Ordinal));+ var inspected = FirmamentBuildAndExport.CompileForMeasurement(source, Path.GetDirectoryName(fullPath));+ Assert.True(inspected.IsSuccess, string.Join("; ", inspected.Diagnostics.Select(d => d.Message)));+ var control = FirmamentBuildAndExport.CompileSource(FirmamentV2.FirmamentAssertionSyntax.Mask(source), Path.GetDirectoryName(fullPath));+ Assert.True(control.IsSuccess, string.Join("; ", control.Diagnostics.Select(d => d.Message)));+ Assert.Equal(control.Value.StepText, inspected.Value.StepText);+ return inspected.Value;+ }}internal sealed class FirmamentCorpusManifestdiff --git a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferFixtureTests.cs b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferFixtureTests.csindex b4987d53..d055bbb0 100644--- a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferFixtureTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileBoundaryChamferFixtureTests.cs@@ -107,27 +107,16 @@ public sealed class ProfileBoundaryChamferFixtureTestspublic void ConvexTwoSegmentFilletFixture_ExportsDeterministicTwoCylindersAndSphere(string fixtureName){var source = FirmamentCorpusHarness.ResolveFixtureFullPath($"fixtures/Regression/CanonicalGeometry/{fixtureName}");- var firstOutput = Path.Combine(Path.GetTempPath(), $"aetheris-{Guid.NewGuid():N}.step");- var secondOutput = Path.Combine(Path.GetTempPath(), $"aetheris-{Guid.NewGuid():N}.step");- try- {- var first = FirmamentBuildAndExport.Run(source, firstOutput); var second = FirmamentBuildAndExport.Run(source, secondOutput);- Assert.True(first.IsSuccess, string.Join(Environment.NewLine, first.Diagnostics.Select(item => item.Message)));- Assert.True(second.IsSuccess, string.Join(Environment.NewLine, second.Diagnostics.Select(item => item.Message)));- Assert.Equal(first.Value.Export.StepText, second.Value.Export.StepText);- var imported = Step242Importer.ImportBody(first.Value.Export.StepText);- Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(item => item.Message)));- Assert.Equal(2, imported.Value!.Geometry.Surfaces.Count(item => item.Value.Kind == SurfaceGeometryKind.Cylinder));- Assert.Equal(1, imported.Value.Geometry.Surfaces.Count(item => item.Value.Kind == SurfaceGeometryKind.Sphere));- var mass = BrepMassProperties.Evaluate(imported.Value);- Assert.True(mass.IsEnclosed);- Assert.True(mass.IsOrientationConsistent);- }- finally- {- if (File.Exists(firstOutput)) File.Delete(firstOutput);- if (File.Exists(secondOutput)) File.Delete(secondOutput);- }+ var first = FirmamentCorpusHarness.InspectUnverifiedVolumeSpecimen(source);+ var second = FirmamentCorpusHarness.InspectUnverifiedVolumeSpecimen(source);+ Assert.Equal(first.StepText, second.StepText);+ var imported = Step242Importer.ImportBody(first.StepText);+ Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(item => item.Message)));+ Assert.Equal(2, imported.Value!.Geometry.Surfaces.Count(item => item.Value.Kind == SurfaceGeometryKind.Cylinder));+ Assert.Equal(1, imported.Value.Geometry.Surfaces.Count(item => item.Value.Kind == SurfaceGeometryKind.Sphere));+ var mass = BrepMassProperties.Evaluate(imported.Value);+ Assert.True(mass.IsEnclosed);+ Assert.True(mass.IsOrientationConsistent);}[Fact]@@ -149,12 +138,10 @@ public sealed class ProfileBoundaryChamferFixtureTestspublic void ReflexTwoSegmentFilletFixture_ExportsDeterministicTwoCylindersAndHornTorus(string fixtureName){var source = FirmamentCorpusHarness.ResolveFixtureFullPath($"fixtures/Regression/CanonicalGeometry/{fixtureName}");- var first = FirmamentBuildAndExport.Run(source, Path.Combine(Path.GetTempPath(), $"aetheris-{Guid.NewGuid():N}.step"));- var second = FirmamentBuildAndExport.Run(source, Path.Combine(Path.GetTempPath(), $"aetheris-{Guid.NewGuid():N}.step"));- Assert.True(first.IsSuccess, string.Join(Environment.NewLine, first.Diagnostics.Select(item => item.Message)));- Assert.True(second.IsSuccess, string.Join(Environment.NewLine, second.Diagnostics.Select(item => item.Message)));- Assert.Equal(first.Value.Export.StepText, second.Value.Export.StepText);- var imported = Step242Importer.ImportBody(first.Value.Export.StepText);+ var first = FirmamentCorpusHarness.InspectUnverifiedVolumeSpecimen(source);+ var second = FirmamentCorpusHarness.InspectUnverifiedVolumeSpecimen(source);+ Assert.Equal(first.StepText, second.StepText);+ var imported = Step242Importer.ImportBody(first.StepText);Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(item => item.Message)));Assert.Equal(2, imported.Value!.Geometry.Surfaces.Count(item => item.Value.Kind == SurfaceGeometryKind.Cylinder));Assert.Equal(1, imported.Value.Geometry.Surfaces.Count(item => item.Value.Kind == SurfaceGeometryKind.Torus));diff --git a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishMixedShellPlanTests.cs b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishMixedShellPlanTests.csindex e814558d..9cba3f33 100644--- a/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishMixedShellPlanTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Integration/ProfileEdgeFinishMixedShellPlanTests.cs@@ -154,13 +154,10 @@ public sealed class ProfileEdgeFinishMixedShellPlanTestspublic void SevenStationFillet_ExportsDeterministicallyWithExpectedSphereTorusDelta(string fixture, int spheres, int tori){var source = FirmamentCorpusHarness.ResolveFixtureFullPath($"fixtures/Regression/CanonicalGeometry/{fixture}");- var first = FirmamentBuildAndExport.Run(source, Path.Combine(Path.GetTempPath(), $"aetheris-{Guid.NewGuid():N}.step"));- var second = FirmamentBuildAndExport.Run(source, Path.Combine(Path.GetTempPath(), $"aetheris-{Guid.NewGuid():N}.step"));-- Assert.True(first.IsSuccess, string.Join(Environment.NewLine, first.Diagnostics.Select(diagnostic => diagnostic.Message)));- Assert.True(second.IsSuccess, string.Join(Environment.NewLine, second.Diagnostics.Select(diagnostic => diagnostic.Message)));- Assert.Equal(first.Value.Export.StepText, second.Value.Export.StepText);- var imported = Step242Importer.ImportBody(first.Value.Export.StepText);+ var first = FirmamentCorpusHarness.InspectUnverifiedVolumeSpecimen(source);+ var second = FirmamentCorpusHarness.InspectUnverifiedVolumeSpecimen(source);+ Assert.Equal(first.StepText, second.StepText);+ var imported = Step242Importer.ImportBody(first.StepText);Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(diagnostic => diagnostic.Message)));var body = Assert.IsType<Aetheris.Kernel.Core.Brep.BrepBody>(imported.Value);AssertClosedManifold(body);@@ -176,9 +173,8 @@ public sealed class ProfileEdgeFinishMixedShellPlanTestspublic void SevenStationFillet_ReimportedMassIsNonAuthoritativeSanityEvidence(string fixture){var source = FirmamentCorpusHarness.ResolveFixtureFullPath($"fixtures/Regression/CanonicalGeometry/{fixture}");- var built = FirmamentBuildAndExport.Run(source, Path.Combine(Path.GetTempPath(), $"aetheris-{Guid.NewGuid():N}.step"));- Assert.True(built.IsSuccess, string.Join(Environment.NewLine, built.Diagnostics.Select(diagnostic => diagnostic.Message)));- var imported = Step242Importer.ImportBody(built.Value.Export.StepText);+ var built = FirmamentCorpusHarness.InspectUnverifiedVolumeSpecimen(source);+ var imported = Step242Importer.ImportBody(built.StepText);Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(diagnostic => diagnostic.Message)));var mass = BrepMassProperties.Evaluate(Assert.IsType<Aetheris.Kernel.Core.Brep.BrepBody>(imported.Value));diff --git a/Aetheris.Kernel.Firmament/Analysis/FirmamentMeasurements.cs b/Aetheris.Kernel.Firmament/Analysis/FirmamentMeasurements.csnew file mode 100644index 00000000..7606865c--- /dev/null+++ b/Aetheris.Kernel.Firmament/Analysis/FirmamentMeasurements.cs@@ -0,0 +1,96 @@+using Aetheris.Continuum.Backends.Sdf;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Queries;+using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Judgment;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Analysis;++public sealed record FirmamentVolumeMeasurement(double? ValueMm3, double? LowerBoundMm3, double? UpperBoundMm3,+ string Method, bool Authoritative, int? RegionsVisited = null, bool BudgetExhausted = false, string? Diagnostic = null)+{+ public double? ErrorBoundMm3 => LowerBoundMm3 is { } lo && UpperBoundMm3 is { } hi ? (hi - lo) * .5 : null;+}+public sealed record FirmamentBoundsMeasurement(double[] MinimumMm, double[] MaximumMm, string Method);+public sealed record FirmamentTopologyMeasurement(int Faces, int Edges, int Vertices, int Shells);++/// <summary>Compiler inspection and source assertions consume this same measurement authority.+/// Mesh-derived mass properties remain a separately requested diagnostic comparison.</summary>+public sealed class FirmamentMeasurements+{+ private readonly FirmamentStepExportResult product;+ private readonly RectangularPlateDefinition? rectangularPlate;+ public BrepBody Body { get; }+ public string? TargetBodyId { get; }+ public FirmamentTopologyMeasurement Topology { get; }+ public FirmamentBoundsMeasurement? Bounds { get; }++ public FirmamentMeasurements(FirmamentStepExportResult product)+ {+ this.product = product;+ var imported = Step242Importer.ImportBody(product.StepText);+ if (!imported.IsSuccess) throw new InvalidOperationException("firmament-measurement-import-failed: " + string.Join("; ", imported.Diagnostics.Select(d => d.Message)));+ Body = imported.Value;+ Topology = new(Body.Topology.Faces.Count(), Body.Topology.Edges.Count(), Body.Topology.Vertices.Count(), Body.Topology.Shells.Count());+ var document = product.RuntimeAdmissionDocument;+ var candidates = (document?.Composes is { Count: > 0 } composes ? composes.Select(c => c.Name)+ : document?.SymbolTable is { } symbols ? symbols.Symbols.Where(s => s.Kind == FirmamentV2CanonicalSymbolKind.Body).Select(s => s.Name)+ : document?.Solids.Where(s => s.RecordType != "Profile").Select(s => s.Name) ?? []).Distinct(StringComparer.Ordinal).ToArray();+ // Some legacy executors identify their generating Profile, not its owning+ // material Struct. Resolve through admitted material symbols before using+ // an executor's internal identity as an author-visible assertion target.+ TargetBodyId = new[] { product.RuntimeBodySourceName, product.RuntimeCorrespondence?.BodyStableId, product.ExportedFeatureId }+ .FirstOrDefault(name => name is not null && candidates.Contains(name, StringComparer.Ordinal))+ ?? (candidates.Length == 1 ? candidates[0] : null);+ if (BrepRectangularPlateQuery.TryDefine(Body, out var plate, out _))+ {+ rectangularPlate = plate;+ Bounds = new([plate!.Origin.X, plate.Origin.Y, plate.Origin.Z],+ [plate.Origin.X + plate.Width, plate.Origin.Y + plate.Height, plate.Origin.Z + plate.Thickness], "ExactRectangularStockEnvelope");+ }+ else if (Body.Geometry.Surfaces.All(s => s.Value.Kind == SurfaceGeometryKind.Plane)+ && Body.Geometry.Curves.All(c => c.Value.Kind == CurveGeometryKind.Line3))+ {+ var points = Body.Topology.Vertices.Select(v => Body.TryGetVertexPoint(v.Id, out var p) ? p : throw new InvalidOperationException("firmament-bounds-unavailable: Missing vertex coordinates.")).ToArray();+ if (points.Length > 0) Bounds = new([points.Min(p => p.X), points.Min(p => p.Y), points.Min(p => p.Z)],+ [points.Max(p => p.X), points.Max(p => p.Y), points.Max(p => p.Z)], "ExactPlanarLinearBoundaryExtrema");+ }+ }++ private sealed record VolumeContext(BrepMassPropertiesResult? Exact, RectangularPlateDefinition? Plate, SdfNode? Root, bool ForceSdf);+ private static readonly JudgmentEngine<VolumeContext> VolumePolicy = new();+ private static readonly JudgmentCandidate<VolumeContext>[] VolumeStrategies =+ [+ new("ExactBrep", c => !c.ForceSdf && c.Exact is not null, _ => 2,+ RejectionReason: _ => "No admitted exact volume recognizer, or SDF was explicitly requested.", TieBreakerPriority: 0),+ new("ExactRectangularPlate", c => !c.ForceSdf && c.Plate is not null, _ => 2,+ RejectionReason: _ => "The complete rectangular-stock/through-hole query did not admit this body, or SDF was explicitly requested.", TieBreakerPriority: 1),+ new("BoundedSdf", c => c.Root is not null, _ => 1,+ RejectionReason: _ => "The compiler retained no analytic CIR field qualified to measure the exported primitive. Display-only or legacy Boolean mirrors are not volume authority.", TieBreakerPriority: 2)+ ];++ public FirmamentVolumeMeasurement Volume(double? absoluteErrorMm3 = null, bool forceSdf = false, int maximumRegions = 1_000_001)+ {+ BrepMassPropertiesResult? exact = null;+ if (!forceSdf && BrepMassProperties.TryEvaluateExactVolume(Body, out var recognized)) exact = recognized;+ var root = product.Cir is { RuntimeRootIsExportedPrimitive: true } cir ? cir.RuntimeRoot : null;+ var decision = VolumePolicy.Evaluate(new(exact, rectangularPlate, root, forceSdf), VolumeStrategies);+ if (!decision.IsSuccess) return new(null, null, null, "Unavailable", false, Diagnostic:+ "firmament-v2-assert-volume-measurement-unavailable: " + string.Join(" ", decision.Rejections.Select(r => r.Reason)));+ if (decision.Selection!.Value.Candidate.Name == "ExactBrep")+ return new(exact!.AbsoluteVolume, exact.AbsoluteVolume, exact.AbsoluteVolume, exact.EvaluationMethod, true);+ if (decision.Selection.Value.Candidate.Name == "ExactRectangularPlate")+ {+ var plate = rectangularPlate!;+ var value = (plate.Width * plate.Height - plate.Holes.Sum(h => Math.PI * h.Diameter * h.Diameter / 4)) * plate.Thickness;+ return new(value, value, value, "ExactRectangularStockMinusThroughHoles", true);+ }+ var bounds = root!.Bounds;+ var error = absoluteErrorMm3 ?? bounds.SizeX * bounds.SizeY * bounds.SizeZ * .005;+ var result = SdfAdaptiveVolumeEstimator.EstimateBounded(SdfTapeLowerer.Lower(root), bounds, error, maximumRegions);+ return new(result.EstimatedVolume, result.LowerBound, result.UpperBound, "SdfAdaptiveOccupiedVolumeInterval", true, result.RegionsVisited, result.BudgetExhausted);+ }+}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.csindex df7bf3d5..8fc6d028 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs@@ -974,11 +974,13 @@ public sealed class AssemblyM0Compilervar result = new List<ToleranceStackupResultIr>();foreach (var assertion in source.StackupAsserts){+ void Error(string code, string message) => diagnostics.Add(new(code, message)+ { SourceSpan = assertion.SourceSpan, LocationNote = assertion.LocationNote });if (!TryResolve(assertion.From, instances, out var from) || !TryResolve(assertion.To, instances, out var to))- { diagnostics.Add(new(TolerancePathMissing, $"Assert ToleranceStackup '{assertion.Name}' endpoints cannot be resolved.")); continue; }+ { Error(TolerancePathMissing, $"Assert ToleranceStackup '{assertion.Name}' endpoints '{assertion.From}' and '{assertion.To}' cannot be resolved."); continue; }var paths = FindPaths(from!.Value.StableIdentity, to!.Value.StableIdentity, relations, 2);- if (paths.Count == 0) { diagnostics.Add(new(TolerancePathMissing, $"Assert ToleranceStackup '{assertion.Name}' has no dimensional path.")); continue; }- if (paths.Count > 1) { diagnostics.Add(new(TolerancePathAmbiguous, $"Assert ToleranceStackup '{assertion.Name}' has multiple valid dimensional paths.")); continue; }+ if (paths.Count == 0) { Error(TolerancePathMissing, $"Assert ToleranceStackup '{assertion.Name}' has no dimensional path."); continue; }+ if (paths.Count > 1) { Error(TolerancePathAmbiguous, $"Assert ToleranceStackup '{assertion.Name}' has multiple valid dimensional paths."); continue; }var contributions = paths[0].Select(step => new StackupContributionIr(step.edge.StableId, step.sign,step.sign * step.edge.Nominal,step.sign > 0 ? step.edge.LowerTolerance : -step.edge.UpperTolerance,@@ -986,13 +988,13 @@ public sealed class AssemblyM0Compilerstep.edge.Unit, step.edge.OriginInstancePath, step.edge.Provenance, step.edge.MateStableId, step.edge.InterfaceStableId, step.edge.SourceProvenance,step.edge.ExpandedContributors)).ToArray();if (contributions.Any(x => x.Unit != assertion.Unit))- { diagnostics.Add(new("assembly-tolerance-unit-mismatch", $"Assert ToleranceStackup '{assertion.Name}' mixes units.")); continue; }+ { Error("assembly-tolerance-unit-mismatch", $"Assert ToleranceStackup '{assertion.Name}' mixes units."); continue; }var nominal = contributions.Sum(x => x.Nominal);var min = nominal + contributions.Sum(x => x.LowerTolerance);var max = nominal + contributions.Sum(x => x.UpperTolerance);var passed = min >= assertion.RequiredMinimum;- if (!passed) diagnostics.Add(new(ToleranceAssertionFailure,- $"Assert ToleranceStackup '{assertion.Name}' failed: worst-case minimum {min:G6} {assertion.Unit} < required {assertion.RequiredMinimum:G6} {assertion.Unit}."));+ if (!passed) Error(ToleranceAssertionFailure,+ $"Assert ToleranceStackup '{assertion.Name}' failed: worst-case minimum {min:G6} {assertion.Unit} < required {assertion.RequiredMinimum:G6} {assertion.Unit}.");result.Add(new(assertion.Name, from.Value.StableIdentity, to.Value.StableIdentity, nominal, min, max,assertion.RequiredMinimum, assertion.Unit, passed, passed ? "passed" : "failed", contributions));}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.csindex 3e6c86b4..1c5a98ed 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.cs@@ -115,7 +115,10 @@ public sealed record AssemblyExposedRelationSource(public sealed record MateRoleAssignment(string Role, AssemblyPath Participant);public sealed record MateSource(string Name, string InterfaceName, IReadOnlyList<MateRoleAssignment> Roles, SemanticSourceSpan? SourceSpan = null);public sealed record DimensionalRelationSource(string Name, AssemblyPath From, AssemblyPath To, double Nominal, double LowerTolerance, double UpperTolerance, string Unit, string Provenance);-public sealed record ToleranceStackupAssertSource(string Name, AssemblyPath From, AssemblyPath To, double RequiredMinimum, string Unit, SemanticSourceSpan? SourceSpan = null);+public sealed record ToleranceStackupAssertSource(string Name, AssemblyPath From, AssemblyPath To, double RequiredMinimum, string Unit, SemanticSourceSpan? SourceSpan = null)+{+ public string? LocationNote { get; init; }+}public sealed record AssemblySource(string Name, AssemblyMemberSource Root, IReadOnlyList<InterfaceDefinition> Interfaces,IReadOnlyList<MateSource> Mates, AssemblyPath Anchor,diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.csindex cfbee4d6..84e0f8c0 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs@@ -113,6 +113,15 @@ public sealed class AssemblyM0Parservar concreteSyntax = FirmamentSyntaxParser.Parse(source).Document;var motionSyntax = AssemblyMotionAuthoring.Extract(concreteSyntax, ref source, sourceIdentity, diagnostics);var motionOrigins = new FirmamentSyntaxOrigins(syntax.Document, concreteSyntax);+ IReadOnlyList<ToleranceStackupAssertSource> Stackups(string ownerName)+ {+ var owner = concreteSyntax.Statements.OfType<DeclarationSyntax>()+ .FirstOrDefault(d => d.Type.Name.Text is "Assembly" or "Subassembly" && d.Name?.Text == ownerName);+ if (owner is null) return [];+ return AssemblyStackupSyntax.Bind(owner, sourceIdentity, diagnostics, motionOrigins.Find)+ .Select(a => projection is null || a.SourceSpan is null ? a : a with+ { SourceSpan = projection.Map(new AssemblyDiagnostic("location", "") { SourceSpan = a.SourceSpan }).SourceSpan }).ToArray();+ }AssemblyDiagnostic MapMotion(AssemblyDiagnostic diagnostic){if (diagnostic.SourceSpan is not { } span) return diagnostic;@@ -177,7 +186,7 @@ public sealed class AssemblyM0Parser}var templateRanges = new List<(int Start, int Length)>();var assemblydefinitionsPhase = Aetheris.Kernel.Core.Diagnostics.BuildPerfTrace.Phase("m0.assembly-definitions");- var assemblyDefinitions = ParseAssemblyDefinitions(source, sourceIdentity, interfaces, concepts, gearAuthorities, diagnostics, templateRanges, Ports, layout, graph);+ var assemblyDefinitions = ParseAssemblyDefinitions(source, sourceIdentity, interfaces, concepts, gearAuthorities, diagnostics, templateRanges, Stackups, Ports, layout, graph);assemblydefinitionsPhase.Dispose();// Template-produced Assembly bodies are declarations, not exported roots.// Blank them without changing offsets, then locate the single root Assembly.@@ -202,7 +211,7 @@ public sealed class AssemblyM0Parser}var mates = ParseMates(body, sourceIdentity, diagnostics);var relations = ParseRelations(body, diagnostics);- var asserts = ParseAsserts(body, sourceIdentity, diagnostics);+ var asserts = Stackups(assemblyHeader.Groups["name"].Value);var anchorMatch = Regex.Match(RemoveBlocks(body, "Mate", @"Assert\s+ToleranceStackup"), @"\bAnchor\s*:\s*(?<path>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*;", RegexOptions.CultureInvariant);var anchor = anchorMatch.Success ? AssemblyPath.Parse(anchorMatch.Groups["path"].Value) : new AssemblyPath([tree.Name]);var frames = ParseFrameTransforms(body, sourceIdentity, diagnostics);@@ -354,6 +363,7 @@ public sealed class AssemblyM0ParserIReadOnlyList<InterfaceDefinition> interfaces, IReadOnlyList<AssemblyConceptDefinition> concepts,IReadOnlyDictionary<string, GearAir> gearAuthorities,List<AssemblyDiagnostic> diagnostics, List<(int Start, int Length)> ranges,+ Func<string, IReadOnlyList<ToleranceStackupAssertSource>> stackups,Func<string, IReadOnlyList<SemanticValue>>? publishedPorts = null,IReadOnlyList<AssemblyLayoutDatum>? layout = null, FirmamentModuleGraph? graph = null){@@ -395,7 +405,7 @@ public sealed class AssemblyM0Parser[new("assembly-template-definition", name, template.Groups["parameter"].Value + ":" + template.Groups["type"].Value, SemanticSourceSpan.Generated(sourceIdentity)),.. claimedConcept is null ? [] : new[] { new SemanticProvenance("assembly-concept-satisfaction", claimedConcept, name, SemanticSourceSpan.Generated(sourceIdentity)) },.. staticProvenance],- anchor, localMates, ParseRelations(body, diagnostics), ParseAsserts(body, sourceIdentity, diagnostics), exposedRelations, claimedConcept,+ anchor, localMates, ParseRelations(body, diagnostics), stackups(name), exposedRelations, claimedConcept,ParseFrameTransforms(body, sourceIdentity, diagnostics).Concat(datumFrames).ToArray()) { ExposedMates = exposedMates });}return result;@@ -899,20 +909,6 @@ public sealed class AssemblyM0ParserRegex.Matches(body, @"\bRelation\s+(?<name>[A-Za-z_]\w*)\s*:\s*(?<from>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*->\s*(?<to>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*=\s*(?<nom>[-+]?\d+(?:\.\d+)?)mm(?:\s+tol\s+(?:(?<bil>\d+(?:\.\d+)?)mm|\+(?<plus>\d+(?:\.\d+)?)mm\s+-(?<minus>\d+(?:\.\d+)?)mm))?\s+from\s+""(?<provenance>[^""]+)""\s*;", RegexOptions.CultureInvariant).Select(m => { var plus = m.Groups["bil"].Success ? Number(m.Groups["bil"].Value) : m.Groups["plus"].Success ? Number(m.Groups["plus"].Value) : 0; var minus = m.Groups["bil"].Success ? Number(m.Groups["bil"].Value) : m.Groups["minus"].Success ? Number(m.Groups["minus"].Value) : 0; return new DimensionalRelationSource(m.Groups["name"].Value, AssemblyPath.Parse(m.Groups["from"].Value), AssemblyPath.Parse(m.Groups["to"].Value), Number(m.Groups["nom"].Value), -minus, plus, "mm", m.Groups["provenance"].Value); }).ToArray();- private static IReadOnlyList<ToleranceStackupAssertSource> ParseAsserts(string body, string sourceIdentity, List<AssemblyDiagnostic> diagnostics)- {- var result = new List<ToleranceStackupAssertSource>();- foreach (Match header in Regex.Matches(body, @"\bAssert\s+ToleranceStackup\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))- {- var block = BalancedBody(body, header.Index + header.Length - 1, diagnostics, "Assert ToleranceStackup"); if (block is null) continue;- var between = Regex.Match(block, @"\bBetween\s*:\s*\[(?<from>[^,]+),\s*(?<to>[^]]+)\]\s*;");- var require = Regex.Match(block, @"\bRequire\s*:\s*Clearance\s*>=\s*(?<min>[-+]?\d+(?:\.\d+)?)mm\s*;");- if (!between.Success || !require.Success) { diagnostics.Add(new("assembly-tolerance-assert-invalid", $"Assert ToleranceStackup '{header.Groups["name"].Value}' requires Between and Clearance fields.")); continue; }- result.Add(new(header.Groups["name"].Value, AssemblyPath.Parse(between.Groups["from"].Value.Trim()), AssemblyPath.Parse(between.Groups["to"].Value.Trim()), Number(require.Groups["min"].Value), "mm", SemanticSourceSpan.Generated(sourceIdentity)));- }- return result;- }-internal static string? BalancedBody(string source, int openingBrace, List<AssemblyDiagnostic> diagnostics, string construct){var depth = 0;diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyStackupSyntax.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyStackupSyntax.csnew file mode 100644index 00000000..6b6198e9--- /dev/null+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyStackupSyntax.cs@@ -0,0 +1,69 @@+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;+using Aetheris.Semantics;++namespace Aetheris.Kernel.Firmament.Assembly;++/// <summary>Authoring binding only; dimensional paths and worst-case arithmetic+/// remain owned by AssemblyM0Compiler.</summary>+internal static class AssemblyStackupSyntax+{+ internal static IReadOnlyList<ToleranceStackupAssertSource> Bind(DeclarationSyntax owner, string file,+ List<AssemblyDiagnostic> diagnostics, Func<FirmamentV2SourceSpan, FirmamentV2SourceSpan?> origin)+ {+ var result = new List<ToleranceStackupAssertSource>();+ var names = new HashSet<string>(StringComparer.Ordinal);+ foreach (var declaration in owner.Body?.Statements.OfType<DeclarationSyntax>()+ .Where(d => d.Modifiers.Any(m => m.Name.Text == "Assert")) ?? [])+ {+ var name = declaration.Name?.Text ?? "";+ if (declaration.Type.Name.Text != "ToleranceStackup")+ { Error("assembly-assert-kind-unsupported", "Assembly assertions require ToleranceStackup.", declaration.Span); continue; }+ if (name.Length == 0 || declaration.Body is null || !names.Add(name))+ { Error("assembly-tolerance-assert-invalid", "ToleranceStackup requires a unique name and a field body.", declaration.Span); continue; }+ var fieldErrors = new List<string>();+ var fields = new FirmamentSyntaxFields(declaration, fieldErrors);+ var between = fields.Take("Between");+ var require = fields.Take("Require");+ fields.Complete();+ foreach (var error in fieldErrors)+ {+ var pieces = error.Split(':');+ var field = declaration.Body.Statements.OfType<FieldSyntax>()+ .FirstOrDefault(f => pieces.Length > 2 && FirmamentSyntaxFields.SameField(f.Name.Text, pieces[2]));+ Error(pieces[0], $"Invalid ToleranceStackup '{name}': {string.Join(": ", pieces.Skip(1))}. Admitted fields are between and require.", field?.Span ?? declaration.Span);+ }+ var paths = between is SequenceSyntax { Kind: SequenceKind.List, Items.Count: 2 } sequence+ && sequence.Items.All(i => i.Name is null && i.Default is null)+ ? sequence.Items.Select(i => Path(i.Value)).ToArray() : [];+ var validPaths = paths.Length == 2 && paths.All(p => p is not null);+ var minimum = double.NaN;+ var validRequirement = require is BinarySyntax { Operator: BinaryOperator.GreaterEqual,+ Left: ReferenceSyntax { Name.Text: "clearance" or "Clearance" } } comparison+ && FirmamentSyntaxValues.TryMeasure(comparison.Right, "mm", out minimum) && double.IsFinite(minimum);+ if (!validPaths || !validRequirement)+ { Error("assembly-tolerance-assert-invalid", $"Assert ToleranceStackup '{name}' requires between: [From.Semantic, To.Semantic] and require: clearance >= length.", declaration.Span); continue; }+ if (fieldErrors.Count > 0) continue;+ var original = origin(declaration.Span);+ var span = original ?? origin(owner.Span);+ result.Add(new(name, AssemblyPath.Parse(paths[0]!), AssemblyPath.Parse(paths[1]!), minimum, "mm",+ span is null ? null : new SemanticSourceSpan(file, span.Start, span.Length))+ { LocationNote = original is null ? "Enclosing Assembly location; expansion retained no exact authored assertion location." : null });+ }+ return result;++ void Error(string code, string message, FirmamentV2SourceSpan location)+ {+ var original = origin(location); var span = original ?? origin(owner.Span);+ diagnostics.Add(new(code, message) { SourceSpan = span is null ? null : new(file, span.Start, span.Length),+ LocationNote = original is null ? "Enclosing Assembly location; expansion retained no exact authored assertion location." : null });+ }+ }++ private static string? Path(ExpressionSyntax expression) => expression switch+ {+ ReferenceSyntax r => r.Name.Text,+ MemberSyntax m when Path(m.Target) is { } path => path + "." + m.Member.Text,+ _ => null+ };+}diff --git a/Aetheris.Kernel.Firmament/FirmamentAssertions.cs b/Aetheris.Kernel.Firmament/FirmamentAssertions.csnew file mode 100644index 00000000..68463dc0--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentAssertions.cs@@ -0,0 +1,72 @@+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Firmament.Analysis;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament;++public static partial class FirmamentBuildAndExport+{+ private static KernelResult<FirmamentStepExportResult> EvaluateAssertions(string source, string? sourceDirectory, FirmamentStepExportResult export)+ {+ var document = export.RuntimeAdmissionDocument ?? ParseSemanticSource(source, sourceDirectory).Document;+ var volume = document?.VolumeAssertions ?? [];+ var geometry = document?.GeometryAssertions ?? [];+ if (volume.Count == 0 && geometry.Count == 0) return KernelResult<FirmamentStepExportResult>.Success(export);+ var diagnostics = new List<KernelDiagnostic>();+ void Error(string message, FirmamentV2SourceSpan span) => diagnostics.Add(new(KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Error, message, "FirmamentV2.Assert") { SourceSpan = new(span.Start, span.Length) });+ FirmamentMeasurements measurements;+ try { measurements = new(export); }+ catch (InvalidOperationException error)+ {+ Error(error.Message, volume.FirstOrDefault()?.SourceSpan ?? geometry[0].SourceSpan);+ return KernelResult<FirmamentStepExportResult>.Failure(diagnostics);+ }+ bool Target(string name, FirmamentV2SourceSpan span)+ {+ if (name == measurements.TargetBodyId) return true;+ Error($"firmament-v2-assert-target-not-exported: '{name}' is not the uniquely identified exported product '{measurements.TargetBodyId ?? "unknown"}'. Assertions never measure a different body under the requested name.", span);+ return false;+ }+ var results = new List<FirmamentV2VolumeAssertionResult>();+ FirmamentVolumeMeasurement? measuredVolume = null;+ foreach (var assertion in volume)+ {+ if (!Target(assertion.TargetBodyId, assertion.SourceSpan)) continue;+ measuredVolume ??= measurements.Volume(volume.Min(a => a.ToleranceMm3) * .25);+ var result = FirmamentV2VolumeAssertionComparer.Compare(assertion, measuredVolume);+ results.Add(result);+ if (!result.Passed) Error(result.Diagnostic!, assertion.SourceSpan);+ }+ var geometryResults = new List<FirmamentGeometryAssertionResult>();+ foreach (var assertion in geometry)+ {+ if (!Target(assertion.TargetBodyId, assertion.SourceSpan)) continue;+ bool passed; string method; string? reason;+ if (assertion.Kind == "Bounds")+ {+ var bounds = measurements.Bounds;+ passed = bounds is not null && Enumerable.Range(0, 3).All(i =>+ Math.Abs(bounds.MinimumMm[i] - assertion.Minimum![i]) <= assertion.ToleranceMm+ && Math.Abs(bounds.MaximumMm[i] - assertion.Maximum![i]) <= assertion.ToleranceMm);+ method = bounds?.Method ?? "Unavailable";+ reason = bounds is null ? "Exact world-space bounds are not yet qualified for this body; a sampled or conservative field envelope was not substituted."+ : $"measuredMinMm=[{string.Join(",", bounds.MinimumMm)}]; measuredMaxMm=[{string.Join(",", bounds.MaximumMm)}]; toleranceMm={assertion.ToleranceMm:G17}";+ }+ else+ {+ var counts = measurements.Topology;+ int Count(string name) => name switch { "Faces" => counts.Faces, "Edges" => counts.Edges, "Vertices" => counts.Vertices, _ => counts.Shells };+ passed = assertion.Counts!.All(pair => Count(pair.Key) == pair.Value);+ method = "ExportedBrepTopology";+ reason = string.Join("; ", assertion.Counts!.Select(pair => $"{pair.Key}: expected={pair.Value}, measured={Count(pair.Key)}"));+ }+ var message = passed ? null : $"firmament-v2-assert-{assertion.Kind.ToLowerInvariant()}-failed: target={assertion.TargetBodyId}; {reason}";+ geometryResults.Add(new(assertion.Id, assertion.Kind, assertion.TargetBodyId, passed, method, message, assertion.SourceSpan));+ if (message is not null) Error(message, assertion.SourceSpan);+ }+ return diagnostics.Count > 0 ? KernelResult<FirmamentStepExportResult>.Failure(diagnostics)+ : KernelResult<FirmamentStepExportResult>.Success(export with { Assertions = results, GeometryAssertions = geometryResults });+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 716efa7e..7de6d6d1 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -27,7 +27,7 @@ using Aetheris.Kernel.Firmament.Piping;namespace Aetheris.Kernel.Firmament;-public static class FirmamentBuildAndExport+public static partial class FirmamentBuildAndExport{public const string EdgeFinishProfileComposeBoundaryUnsupported = "EdgeFinishProfileComposeBoundaryUnsupported";private enum ExportRouteDisposition { Declined, Failed, Succeeded }@@ -95,12 +95,12 @@ public static class FirmamentBuildAndExportreturn KernelResult<FirmamentBuildAndExportResult>.Failure(pmiParity.Diagnostics);}- var assertions = EvaluateVolumeAssertions(sourceText, Path.GetDirectoryName(fullSourcePath), enrichedExport);+ var assertions = EvaluateAssertions(sourceText, Path.GetDirectoryName(fullSourcePath), enrichedExport);if (!assertions.IsSuccess){return KernelResult<FirmamentBuildAndExportResult>.Failure(assertions.Diagnostics);}- var export = enrichedExport with { Assertions = assertions.Value };+ var export = assertions.Value;var resolvedOutputPath = string.IsNullOrWhiteSpace(outputPath)? ResolveDefaultOutputPath(fullSourcePath): Path.GetFullPath(outputPath);@@ -122,7 +122,14 @@ public static class FirmamentBuildAndExport/// </summary>public static KernelResult<FirmamentStepExportResult> CompileSource(string sourceText,- string? sourceDirectory = null)+ string? sourceDirectory = null) => CompileSourceCore(sourceText, sourceDirectory, true);++ /// <summary>Explicit inspection boundary: admit and build geometry, but do not+ /// claim that its declared assertions passed. Used to discover assertion inputs.</summary>+ public static KernelResult<FirmamentStepExportResult> CompileForMeasurement(string sourceText, string? sourceDirectory = null)+ => CompileSourceCore(sourceText, sourceDirectory, false);++ private static KernelResult<FirmamentStepExportResult> CompileSourceCore(string sourceText, string? sourceDirectory, bool enforceAssertions){ArgumentNullException.ThrowIfNull(sourceText);var normalized = sourceText;@@ -156,9 +163,10 @@ public static class FirmamentBuildAndExportvar enrichedExport = AttachAuthoredFeatureReports(normalized, sourceDirectory, export.Value);var pmiParity = VerifyV2PmiExportParity(normalized, sourceDirectory, enrichedExport);if (!pmiParity.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(pmiParity.Diagnostics);- var assertions = EvaluateVolumeAssertions(normalized, sourceDirectory, enrichedExport);+ if (!enforceAssertions) return KernelResult<FirmamentStepExportResult>.Success(enrichedExport, export.Diagnostics);+ var assertions = EvaluateAssertions(normalized, sourceDirectory, enrichedExport);return assertions.IsSuccess- ? KernelResult<FirmamentStepExportResult>.Success(enrichedExport with { Assertions = assertions.Value }, export.Diagnostics)+ ? KernelResult<FirmamentStepExportResult>.Success(assertions.Value, export.Diagnostics): KernelResult<FirmamentStepExportResult>.Failure(assertions.Diagnostics);}@@ -213,31 +221,6 @@ public static class FirmamentBuildAndExport};}- private static KernelResult<IReadOnlyList<FirmamentV2VolumeAssertionResult>> EvaluateVolumeAssertions(string source, string? sourceDirectory, FirmamentStepExportResult export)- {- var parsed = ParseSemanticSource(source, sourceDirectory);- if (!parsed.IsSuccess || parsed.Document?.VolumeAssertions is not { Count: > 0 } assertions) return KernelResult<IReadOnlyList<FirmamentV2VolumeAssertionResult>>.Success([]);- var imported = Step242Importer.ImportBody(export.StepText);- if (!imported.IsSuccess || imported.Value is null)- {- return KernelResult<IReadOnlyList<FirmamentV2VolumeAssertionResult>>.Failure([new Kernel.Core.Diagnostics.KernelDiagnostic(- Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,- "firmament-v2-assert-volume-measurement-unavailable: STEP reimport failed", "FirmamentV2.AssertVolume")]);- }- var mass = BrepMassProperties.Evaluate(imported.Value);- var results = assertions.Select(assertion => FirmamentV2VolumeAssertionComparer.Compare(assertion, mass)).ToArray();- // Display-tessellation estimates remain useful evidence, but they do- // not gate a production build as the definition of occupied volume.- // Analytic B-rep recognizers retain their existing bounded gate until- // the post-Preview-1 CIR authority path is implemented.- var failures = results.Where(result => result.MeasurementAuthoritative && !result.Passed).Select(result => new Kernel.Core.Diagnostics.KernelDiagnostic(- Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,- result.Diagnostic ?? "firmament-v2-assert-volume-failed", "FirmamentV2.AssertVolume")).ToArray();- return failures.Length == 0- ? KernelResult<IReadOnlyList<FirmamentV2VolumeAssertionResult>>.Success(results)- : KernelResult<IReadOnlyList<FirmamentV2VolumeAssertionResult>>.Failure(failures);- }-private static KernelResult<bool> VerifyV2PmiExportParity(string source, string? sourceDirectory, FirmamentStepExportResult export){var parsed = ParseSemanticSource(source, sourceDirectory);@@ -624,7 +607,8 @@ public static class FirmamentBuildAndExportDimensionInspection: []){RuntimeBody = executedPrimitive.Body,- Cir = FirmamentCirRetention.FromRoot(execution.Value.NativeGeometryState.CirMirror.RuntimeRoot, step.Value)+ Cir = FirmamentCirRetention.FromRoot(execution.Value.NativeGeometryState.CirMirror.RuntimeRoot, step.Value,+ exportedPrimitive: execution.Value.ExecutedPrimitives.Count == 1 && execution.Value.ExecutedBooleans.Count == 0)};if (executedPrimitive.Kind == FirmamentLoweredPrimitiveKind.Box&& executedPrimitive.BoxConstructionTopology is { } boxTopologydiff --git a/Aetheris.Kernel.Firmament/FirmamentCirRetention.cs b/Aetheris.Kernel.Firmament/FirmamentCirRetention.csindex 7e9d2954..b5e4162f 100644--- a/Aetheris.Kernel.Firmament/FirmamentCirRetention.cs+++ b/Aetheris.Kernel.Firmament/FirmamentCirRetention.cs@@ -12,17 +12,21 @@ public sealed record FirmamentCirRetention(string DefinitionId, string Qualificapublic const string Version = "aetheris/cir-retention/1";public string Schema => Version;[JsonIgnore] public SdfNode? RuntimeRoot { get; init; }+ // Display eligibility alone is not proof of occupied-volume parity. The+ // exporter grants this only when the same single primitive produced STEP.+ [JsonIgnore] public bool RuntimeRootIsExportedPrimitive { get; init; }- internal static FirmamentCirRetention FromRoot(SdfNode? root, string step)+ internal static FirmamentCirRetention FromRoot(SdfNode? root, string step, bool exportedPrimitive = false){var definition = "definition:" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step)))[..16].ToLowerInvariant();if (root is null) return new(definition, "mesh", "no-qualified-cir-mirror", null, null, null, null);var display = CirVisualTsLowerer.Lower(root);if (!display.Success) return new(definition, "mesh", display.FallbackReason, null, null, null, null)- { RuntimeRoot = root };+ { RuntimeRoot = root, RuntimeRootIsExportedPrimitive = exportedPrimitive };var program = display.Program!;return new(definition, "cir-qualified", null, program.StructuralHash, program.FieldSource,[program.Bounds.Min.X, program.Bounds.Min.Y, program.Bounds.Min.Z],- [program.Bounds.Max.X, program.Bounds.Max.Y, program.Bounds.Max.Z]) { RuntimeRoot = root };+ [program.Bounds.Max.X, program.Bounds.Max.Y, program.Bounds.Max.Z])+ { RuntimeRoot = root, RuntimeRootIsExportedPrimitive = exportedPrimitive };}}diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.csindex 40ff10ee..541aab8f 100644--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs@@ -38,6 +38,7 @@ public sealed record FirmamentStepExportResult(FirmamentThreadReport? Thread = null){public string? DocumentName { get; init; }+ public IReadOnlyList<FirmamentV2.FirmamentGeometryAssertionResult> GeometryAssertions { get; init; } = [];// In-process display can use the exact body that was exported to STEP.// It is intentionally absent from CLI/JSON artifact serialization.[JsonIgnore] public BrepBody? RuntimeBody { get; init; }diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.csindex 0faec9e6..beed4ed7 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalSymbolTable.cs@@ -148,6 +148,12 @@ internal static class FirmamentV2CanonicalSymbolBinderelse if (target.Kind is not (FirmamentV2CanonicalSymbolKind.Body or FirmamentV2CanonicalSymbolKind.Compose)) diagnostics.Add($"firmament-v2-assert-volume-target-not-material-body:{assertion.TargetBodyId}:{target.Kind}");else bindings.Add(new($"AssertVolume:{assertion.Id}", "Target", target.CanonicalId, assertion.SourceSpan));}+ foreach (var assertion in document.GeometryAssertions)+ {+ if (!byName.TryGetValue(assertion.TargetBodyId, out var target)) diagnostics.Add($"firmament-v2-assert-target-unknown:{assertion.TargetBodyId}");+ else if (target.Kind is not (FirmamentV2CanonicalSymbolKind.Body or FirmamentV2CanonicalSymbolKind.Compose)) diagnostics.Add($"firmament-v2-assert-target-not-material-body:{assertion.TargetBodyId}:{target.Kind}");+ else bindings.Add(new($"Assert{assertion.Kind}:{assertion.Id}", "Target", target.CanonicalId, assertion.SourceSpan));+ }return new(new(symbols, bindings), diagnostics.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray());}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentGeometryAssertions.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentGeometryAssertions.csnew file mode 100644index 00000000..e86fc7e9--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentGeometryAssertions.cs@@ -0,0 +1,92 @@+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++public sealed record FirmamentGeometryAssertion(string Id, string Kind, string TargetBodyId,+ double[]? Minimum, double[]? Maximum, double ToleranceMm, IReadOnlyDictionary<string, int>? Counts,+ string? Note, FirmamentV2SourceSpan SourceSpan);+public sealed record FirmamentGeometryAssertionResult(string AssertionId, string Kind, string TargetBodyId,+ bool Passed, string MeasurementMethod, string? Diagnostic, FirmamentV2SourceSpan SourceSpan);++internal static class FirmamentAssertionSyntax+{+ internal static IReadOnlyList<DeclarationSyntax> Declarations(string source) =>+ FirmamentV2Parser.MechanicalDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements)+ .Where(d => d.Modifiers.Any(m => m.Name.Text == "Assert")).ToArray();++ internal static (IReadOnlyList<FirmamentV2VolumeAssertion> Volume, IReadOnlyList<FirmamentGeometryAssertion> Geometry) Parse(+ string source, List<string> diagnostics)+ {+ var volume = new List<FirmamentV2VolumeAssertion>();+ var geometry = new List<FirmamentGeometryAssertion>();+ foreach (var declaration in Declarations(source))+ {+ var kind = declaration.Type.Name.Text;+ var target = declaration.Name?.Text ?? "";+ if (kind is not ("Volume" or "Bounds" or "Topology"))+ { diagnostics.Add($"{FirmamentV2Parser.AssertVolumeKindUnsupported}:{kind}:{target}"); continue; }+ if (declaration.Body is null || target.Length == 0)+ { diagnostics.Add($"{FirmamentV2Parser.AssertVolumeMalformed}:{target}"); continue; }+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);+ var noteExpression = fields.Take("Note");+ var note = noteExpression is LiteralSyntax { Kind: LiteralKind.String } ? FirmamentSyntaxValues.Reference(noteExpression) : null;+ if (noteExpression is not null && note is null) diagnostics.Add($"{FirmamentV2Parser.AssertVolumeMalformed}:{target}:Note");+ var id = kind.ToLowerInvariant() + ":" + target + ":" + declaration.Span.Start;+ if (kind == "Volume")+ {+ var expectedOk = Volume(fields.Take("Expected"), source, out var expected);+ var toleranceOk = Volume(fields.Take("Tolerance"), source, out var tolerance);+ if (!expectedOk) diagnostics.Add($"{FirmamentV2Parser.AssertVolumeExpectedDimensionMismatch}:{target}:Volume");+ if (!toleranceOk) diagnostics.Add($"{FirmamentV2Parser.AssertVolumeToleranceDimensionMismatch}:{target}:Volume");+ if (tolerance < 0) diagnostics.Add($"{FirmamentV2Parser.AssertVolumeToleranceNegative}:{target}");+ if (expected < 0) diagnostics.Add($"{FirmamentV2Parser.AssertVolumeMalformed}:{target}:negative-expected");+ if (expectedOk && toleranceOk && expected >= 0 && tolerance >= 0)+ volume.Add(new(id, target, expected, tolerance, note, declaration.Span));+ }+ else if (kind == "Bounds")+ {+ var minimum = fields.Take("Min"); var maximum = fields.Take("Max"); var tolerance = fields.Number("Tolerance", "mm", 0);+ var valid = FirmamentSyntaxValues.Vector(minimum, "mm", out var min) && min.Length == 3;+ valid &= FirmamentSyntaxValues.Vector(maximum, "mm", out var max) && max.Length == 3;+ valid &= double.IsFinite(tolerance) && tolerance >= 0;+ if (valid && Enumerable.Range(0, 3).Any(i => min[i] > max[i])) valid = false;+ if (!valid) diagnostics.Add($"firmament-v2-assert-bounds-malformed:{target}:expected-Min-Max-length-vectors-and-nonnegative-Tolerance");+ else geometry.Add(new(id, kind, target, min, max, tolerance, null, note, declaration.Span));+ }+ else+ {+ var counts = new Dictionary<string, int>(StringComparer.Ordinal);+ foreach (var name in new[] { "Faces", "Edges", "Vertices", "Shells" })+ {+ var value = fields.Take(name); if (value is null) continue;+ if (!FirmamentSyntaxValues.TryMeasure(value, "", out var number) || !double.IsFinite(number) || number < 0 || number > int.MaxValue || Math.Truncate(number) != number)+ diagnostics.Add($"firmament-v2-assert-topology-malformed:{target}:{name}:expected-nonnegative-integer");+ else counts.Add(name, (int)number);+ }+ if (counts.Count == 0) diagnostics.Add($"firmament-v2-assert-topology-malformed:{target}:specify-at-least-one-count");+ else geometry.Add(new(id, kind, target, null, null, 0, counts, note, declaration.Span));+ }+ fields.Complete();+ }+ return (volume, geometry);+ }++ private static bool Volume(ExpressionSyntax? expression, string source, out double value)+ {+ value = double.NaN;+ if (expression is null) return false;+ var raw = source.Substring(expression.Span.Start, expression.Span.Length).Trim();+ return raw.EndsWith("mm^3", StringComparison.Ordinal)+ && double.TryParse(raw[..^4].Trim(), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out value)+ && double.IsFinite(value);+ }++ internal static string Mask(string source)+ {+ var chars = source.ToCharArray();+ foreach (var declaration in Declarations(source))+ for (var i = declaration.Span.Start; i < declaration.Span.Start + declaration.Span.Length; i++)+ if (chars[i] is not ('\n' or '\r')) chars[i] = ' ';+ return new(chars);+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2DiagnosticAdapter.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2DiagnosticAdapter.csindex 49a7ccfe..a5147f95 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2DiagnosticAdapter.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentInterop/FirmamentV2DiagnosticAdapter.cs@@ -15,7 +15,7 @@ public static class FirmamentV2DiagnosticAdapterdiagnostic.Code,diagnostic.Severity switch{- "fatal" => FirmamentDiagnosticSeverity.Fatal,+ "fatal" or "error" => FirmamentDiagnosticSeverity.Fatal,"warning" => FirmamentDiagnosticSeverity.Warning,_ => FirmamentDiagnosticSeverity.Info},@@ -64,6 +64,18 @@ public static class FirmamentV2DiagnosticAdapterFirmamentV2Parser.ConceptMissingRequiredField => "Forge concept application is missing a required descriptor field.",FirmamentV2Parser.PmiUnknownDatum => "PMI relation references an unknown datum.",FirmamentV2Parser.ToleranceDroppedThroughArithmetic => "A toleranced value was used in arithmetic and only the nominal value was preserved.",+ _ when diagnosticCode.StartsWith(FirmamentV2Parser.AssertVolumeKindUnsupported + ":", StringComparison.Ordinal)+ => "This part admits Assert Volume, Assert Bounds and Assert Topology. Assert ToleranceStackup belongs on an Assembly with dimensional relations.",+ _ when diagnosticCode.StartsWith(FirmamentV2Parser.AssertVolumeExpectedDimensionMismatch + ":", StringComparison.Ordinal)+ => "Assert Volume expected requires a finite nonnegative volume literal in mm^3.",+ _ when diagnosticCode.StartsWith(FirmamentV2Parser.AssertVolumeToleranceDimensionMismatch + ":", StringComparison.Ordinal)+ => "Assert Volume tolerance requires a finite nonnegative volume literal in mm^3.",+ _ when diagnosticCode.StartsWith(FirmamentV2Parser.AssertVolumeToleranceNegative + ":", StringComparison.Ordinal)+ => "Assert Volume tolerance cannot be negative.",+ _ when diagnosticCode.StartsWith("firmament-v2-assert-bounds-malformed:", StringComparison.Ordinal)+ => "Assert Bounds requires three-component min and max length vectors in ascending order, and a nonnegative length tolerance.",+ _ when diagnosticCode.StartsWith("firmament-v2-assert-topology-malformed:", StringComparison.Ordinal)+ => "Assert Topology requires at least one finite nonnegative integer count: faces, edges, vertices or shells.",_ when diagnosticCode.StartsWith("firmament-v2-field-duplicate:", StringComparison.Ordinal)=> $"Field '{diagnosticCode.Split(':')[^1]}' is specified more than once in {diagnosticCode.Split(':')[1]}. Keep one value.",_ when diagnosticCode.StartsWith("firmament-v2-field-value-invalid:", StringComparison.Ordinal)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.csindex b8e4172f..7e72bf50 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs@@ -6,6 +6,7 @@ namespace Aetheris.Kernel.Firmament.FirmamentV2;public sealed record FirmamentV2Document(string ModelName, string Units, IReadOnlyList<FirmamentV2SolidBinding> Solids, IReadOnlyList<FirmamentV2ModifyBlock>? ModifyBlocks = null, IReadOnlyList<FirmamentV2TemplateDecl>? Templates = null, IReadOnlyList<FirmamentV2PmiDecl>? Pmi = null, IReadOnlyList<FirmamentV2RecognizedRegion>? RecognizedRegions = null, IReadOnlyList<FirmamentV2ReplacementDecl>? Replacements = null, IReadOnlyList<FirmamentV2LetDeclaration>? Lets = null, IReadOnlyList<FirmamentV2BoundLet>? BoundLets = null, IReadOnlyList<FirmamentV2LetRecordDeclaration>? LetRecords = null, IReadOnlyList<FirmamentV2BoundLetRecord>? BoundLetRecords = null, IReadOnlyList<FirmamentV2ManufacturingConceptDeclaration>? ManufacturingConcepts = null, IReadOnlyList<FirmamentV2FeatureConceptDeclaration>? FeatureConcepts = null, FirmamentV2PmiBlock? PmiBlock = null, FirmamentV2BoundPmiBlock? BoundPmi = null, ConceptIrDocument? ConceptIr = null, IReadOnlyList<FirmamentV2LatticeFillDecl>? LatticeFills = null, IReadOnlyList<FirmamentV2StandaloneLatticeFillDecl>? StandaloneLatticeFills = null, IReadOnlyList<FirmamentV2ProfileDecl>? Profiles = null, IReadOnlyList<FirmamentV2ComposeDecl>? Composes = null, IReadOnlyList<FirmamentV2SelectionDecl>? Selections = null, FirmamentV2StaticAuthoringDocument? StaticAuthoring = null, FirmamentV2CanonicalSymbolTable? SymbolTable = null, IReadOnlyList<FirmamentV2VolumeAssertion>? VolumeAssertions = null, IReadOnlyList<ConceptIrTemplateInstantiation>? TemplateInstantiations = null, IReadOnlyList<PanelIr>? Panels = null, IReadOnlyList<FirmamentV2BossDecl>? Bosses = null, IReadOnlyList<FirmamentV2PocketDecl>? Pockets = null, IReadOnlyList<FirmamentV2FeatureDefinition>? FeatureDefinitions = null, IReadOnlyList<FirmamentV2FeatureInvocation>? FeatureInvocations = null, FirmamentV2FeatureExpansionMetrics? FeatureExpansion = null, IReadOnlyList<FirmamentV2Polygon2Decl>? Polygons = null, IReadOnlyList<FirmamentV2ClosedBoundary2Decl>? Boundaries = null, IReadOnlyList<FirmamentV2ThreadDecl>? Threads = null){public IReadOnlyList<FirmamentV2DataSymbolBinding> DataBindings { get; init; } = [];+ public IReadOnlyList<FirmamentGeometryAssertion> GeometryAssertions { get; init; } = [];public FirmamentV2SolidBinding Solid => Solids[^1];public FirmamentV2SideHoleIntent? SideHoleIntent => ModifyBlocks?.SelectMany(m => m.Regions.Select(r =>{diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csindex 74545196..4ee1b0a2 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -356,6 +356,16 @@ public static partial class FirmamentV2Parserprivate static FirmamentV2ParseResult CompleteAdmission(FirmamentV2ParseResult result, string originalSource){+ if (result.IsSuccess && result.Document is { } document+ && (document.VolumeAssertions?.Count ?? 0) + document.GeometryAssertions.Count == 0)+ {+ var unbound = FirmamentAssertionSyntax.Declarations(originalSource)+ .Concat(FirmamentAssertionSyntax.Declarations(result.DiagnosticSource ?? result.BoundSource ?? originalSource));+ if (unbound.Any())+ result = result with { IsSuccess = false, Disposition = FirmamentV2ParseDisposition.RecognizedInvalid,+ Diagnostics = [.. result.Diagnostics,+ $"firmament-v2-assert-owner-unsupported: The {result.ParserRoute} owner does not bind these part assertions. They cannot be ignored; use a qualified mechanical body owner or inspect the geometry separately."] };+ }if (result.IsSuccess && result.OwnsUnifiedAdmission && result.BoundSchema is null)result = result with { IsSuccess = false, Disposition = FirmamentV2ParseDisposition.RecognizedInvalid,Diagnostics = [.. result.Diagnostics, "firmament-v2-admission-domain-missing: The engineering binder did not identify its admitted frontend schema."] };@@ -1376,64 +1386,7 @@ public static partial class FirmamentV2Parserreturn selections;}- private static IReadOnlyList<FirmamentV2VolumeAssertion> ParseCanonicalVolumeAssertions(string source, List<string> diagnostics)- {- var assertions = new List<FirmamentV2VolumeAssertion>();- foreach (Match header in Regex.Matches(source, @"\bAssert\s+(?<kind>[A-Za-z_]\w*)\s+(?<target>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))- {- var kind = header.Groups["kind"].Value;- var target = header.Groups["target"].Value;- var open = source.IndexOf('{', header.Index);- var close = FindMatchingBrace(source, open);- if (close < 0) { diagnostics.Add($"{AssertVolumeMalformed}:{target}"); continue; }- if (!string.Equals(kind, "Volume", StringComparison.Ordinal)) { diagnostics.Add($"{AssertVolumeKindUnsupported}:{kind}:{target}"); continue; }-- var fields = new Dictionary<string, string>(StringComparer.Ordinal);- foreach (Match field in Regex.Matches(source[(open + 1)..close], @"(?m)^\s*(?<name>[A-Za-z_]\w*)\s*:\s*(?<value>[^\r\n]+?)\s*$", RegexOptions.CultureInvariant))- {- var name = field.Groups["name"].Value;- if (!fields.TryAdd(name, field.Groups["value"].Value.Trim())) diagnostics.Add($"{AssertVolumeMalformed}:{target}:duplicate-{name}");- }- if (fields.Keys.Any(name => name is not "Expected" and not "Tolerance" and not "Note") || !fields.TryGetValue("Expected", out var expectedRaw) || !fields.TryGetValue("Tolerance", out var toleranceRaw))- {- diagnostics.Add($"{AssertVolumeMalformed}:{target}");- continue;- }- if (!TryParseCubicMillimeters(expectedRaw, out var expected))- {- diagnostics.Add($"{AssertVolumeExpectedDimensionMismatch}:{target}:Volume:{DimensionName(expectedRaw)}");- continue;- }- if (!TryParseCubicMillimeters(toleranceRaw, out var tolerance))- {- diagnostics.Add($"{AssertVolumeToleranceDimensionMismatch}:{target}:Volume:{DimensionName(toleranceRaw)}");- continue;- }- if (tolerance < 0d) { diagnostics.Add($"{AssertVolumeToleranceNegative}:{target}"); continue; }- if (!double.IsFinite(expected) || !double.IsFinite(tolerance)) { diagnostics.Add($"{AssertVolumeMalformed}:{target}:non-finite"); continue; }- string? note = null;- if (fields.TryGetValue("Note", out var noteRaw))- {- if (noteRaw.Length < 2 || noteRaw[0] != '"' || noteRaw[^1] != '"') { diagnostics.Add($"{AssertVolumeMalformed}:{target}:Note"); continue; }- note = noteRaw[1..^1];- }- var span = new FirmamentV2SourceSpan(header.Index, close - header.Index + 1);- assertions.Add(new($"volume:{target}:{header.Index}", target, expected, tolerance, note, span));- }- return assertions;- }-- private static string RemoveCanonicalVolumeAssertions(string source)- {- var removals = Regex.Matches(source, @"\bAssert\s+[A-Za-z_]\w*\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant)- .Cast<Match>()- .Select(header => new { header.Index, Close = FindMatchingBrace(source, source.IndexOf('{', header.Index)) })- .Where(match => match.Close >= 0)- .OrderByDescending(match => match.Index)- .ToArray();- foreach (var removal in removals) source = source.Remove(removal.Index, removal.Close - removal.Index + 1);- return source;- }+ private static string RemoveCanonicalVolumeAssertions(string source) => FirmamentAssertionSyntax.Mask(source);private static FirmamentV2ParseResult AttachVolumeAssertionsAndSymbols(FirmamentV2ParseResult parsed, string source, FirmamentV2StaticAuthoringDocument? staticAuthoring, List<string> diagnostics){@@ -1441,7 +1394,8 @@ public static partial class FirmamentV2Parservar threads = ParseCanonicalThreads(source, diagnostics);if (threads is null)return FirmamentV2ParseResult.Failure(parsed.Diagnostics.Concat(diagnostics).Distinct(StringComparer.Ordinal).Order().ToArray(), FirmamentV2ParseDisposition.RecognizedInvalid);- var normalized = parsed.Document with { StaticAuthoring = staticAuthoring, VolumeAssertions = ParseCanonicalVolumeAssertions(source, diagnostics), Threads = threads };+ var assertions = FirmamentAssertionSyntax.Parse(source, diagnostics);+ var normalized = parsed.Document with { StaticAuthoring = staticAuthoring, VolumeAssertions = assertions.Volume, GeometryAssertions = assertions.Geometry, Threads = threads };normalized = BindSemanticConstraintProjections(normalized, diagnostics);if (diagnostics.Any(IsFatalDiagnosticCode))return FirmamentV2ParseResult.Failure(parsed.Diagnostics.Concat(diagnostics).Distinct(StringComparer.Ordinal).Order().ToArray(), FirmamentV2ParseDisposition.RecognizedInvalid);@@ -1495,22 +1449,6 @@ public static partial class FirmamentV2Parserreturn document with { StaticAuthoring = staticAuthoring with { SemanticConstraints = constraints }, PmiBlock = document.PmiBlock is null ? null : document.PmiBlock with { Records = records }, BoundPmi = bound };}- private static bool TryParseCubicMillimeters(string raw, out double value)- {- value = double.NaN;- var match = Regex.Match(raw, @"^(?<value>[-+0-9.eE]+)mm\^3$", RegexOptions.CultureInvariant);- return match.Success && double.TryParse(match.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out value);- }-- private static string DimensionName(string raw)- {- if (raw.EndsWith("mm^3", StringComparison.Ordinal)) return "InvalidVolume";- if (raw.EndsWith("mm^2", StringComparison.Ordinal)) return "Area";- if (raw.EndsWith("mm", StringComparison.Ordinal)) return "Length";- if (raw.EndsWith("deg", StringComparison.Ordinal)) return "Angle";- return "ScalarOrUnsupported";- }-private static void ValidateCanonicalSelectionSources(string body, IReadOnlyList<FirmamentV2SelectionDecl> selections,IEnumerable<string> profileNames, List<string> diagnostics){diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2VolumeAssertions.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2VolumeAssertions.csindex baac47dd..854b81e3 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2VolumeAssertions.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2VolumeAssertions.cs@@ -1,4 +1,5 @@using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Firmament.Analysis;namespace Aetheris.Kernel.Firmament.FirmamentV2;@@ -27,26 +28,44 @@ public sealed record FirmamentV2VolumeAssertionResult(bool MeasurementAuthoritative,string? Diagnostic,FirmamentV2SourceSpan SourceSpan,- string Provenance);+ string Provenance)+{+ public double? LowerBoundMm3 { get; init; }+ public double? UpperBoundMm3 { get; init; }+ public string VerificationStatus { get; init; } = "Unverified";+ public int? RegionsVisited { get; init; }+}public static class FirmamentV2VolumeAssertionComparer{public static FirmamentV2VolumeAssertionResult Compare(FirmamentV2VolumeAssertion assertion, BrepMassPropertiesResult mass){- ArgumentNullException.ThrowIfNull(assertion);ArgumentNullException.ThrowIfNull(mass);- if (mass.Status == BrepMassPropertiesStatus.Unavailable)- {- return new(assertion.Id, assertion.TargetBodyId, assertion.ExpectedMm3, null, null, null, assertion.ToleranceMm3, false,- assertion.Note, mass.EvaluationMethod, mass.ErrorBound, mass.IsAuthoritativeForVolumeAssertion,- $"firmament-v2-assert-volume-measurement-unavailable:{assertion.TargetBodyId}:{assertion.Id}", assertion.SourceSpan, assertion.Provenance);- }+ return Compare(assertion, new FirmamentVolumeMeasurement(mass.Status == BrepMassPropertiesStatus.Unavailable ? null : mass.AbsoluteVolume,+ mass.IsAuthoritativeForVolumeAssertion ? mass.AbsoluteVolume : null,+ mass.IsAuthoritativeForVolumeAssertion ? mass.AbsoluteVolume : null, mass.EvaluationMethod, mass.IsAuthoritativeForVolumeAssertion));+ }- var delta = mass.AbsoluteVolume - assertion.ExpectedMm3;- var absoluteDelta = double.Abs(delta);- var passed = absoluteDelta <= assertion.ToleranceMm3;- var diagnostic = passed ? null : $"firmament-v2-assert-volume-failed:target={assertion.TargetBodyId}:expectedMm3={assertion.ExpectedMm3:G17}:measuredMm3={mass.AbsoluteVolume:G17}:deltaMm3={delta:G17}:toleranceMm3={assertion.ToleranceMm3:G17}:method={mass.EvaluationMethod}:errorBoundMm3={mass.ErrorBound?.ToString("G17", System.Globalization.CultureInfo.InvariantCulture) ?? "unavailable"}";- return new(assertion.Id, assertion.TargetBodyId, assertion.ExpectedMm3, mass.AbsoluteVolume, delta, absoluteDelta, assertion.ToleranceMm3,- passed, assertion.Note, mass.EvaluationMethod, mass.ErrorBound, mass.IsAuthoritativeForVolumeAssertion, diagnostic, assertion.SourceSpan, assertion.Provenance);+ public static FirmamentV2VolumeAssertionResult Compare(FirmamentV2VolumeAssertion assertion, FirmamentVolumeMeasurement measurement)+ {+ var lo = measurement.LowerBoundMm3; var hi = measurement.UpperBoundMm3;+ var permittedMin = assertion.ExpectedMm3 - assertion.ToleranceMm3;+ var permittedMax = assertion.ExpectedMm3 + assertion.ToleranceMm3;+ var verified = measurement.Authoritative && lo.HasValue && hi.HasValue+ && double.IsFinite(lo.Value) && double.IsFinite(hi.Value) && lo.Value <= hi.Value;+ var passed = verified && lo >= permittedMin && hi <= permittedMax;+ var failed = verified && (hi < permittedMin || lo > permittedMax);+ var status = passed ? "Passed" : failed ? "Failed" : "Unverified";+ var code = failed ? "firmament-v2-assert-volume-failed" : "firmament-v2-assert-volume-unverified";+ string? diagnostic = null;+ if (!passed)+ diagnostic = measurement.Diagnostic ?? FormattableString.Invariant(+ $"{code}: target={assertion.TargetBodyId}; expectedMm3={assertion.ExpectedMm3:G17}; measuredMm3={measurement.ValueMm3:G17}; deltaMm3={measurement.ValueMm3 - assertion.ExpectedMm3:G17}; toleranceMm3={assertion.ToleranceMm3:G17}; intervalMm3=[{lo:G17},{hi:G17}]; method={measurement.Method}. ")+ + (failed ? "The measured interval lies outside the allowed range." : "No proof at the requested tolerance. Use 'aetheris measure' to inspect the measurement interval; do not copy an approximate value with zero tolerance.");+ return new(assertion.Id, assertion.TargetBodyId, assertion.ExpectedMm3, measurement.ValueMm3,+ measurement.ValueMm3 - assertion.ExpectedMm3, measurement.ValueMm3 is { } value ? Math.Abs(value - assertion.ExpectedMm3) : null,+ assertion.ToleranceMm3, passed, assertion.Note, measurement.Method, measurement.ErrorBoundMm3, measurement.Authoritative,+ diagnostic, assertion.SourceSpan, assertion.Provenance)+ { LowerBoundMm3 = lo, UpperBoundMm3 = hi, VerificationStatus = status, RegionsVisited = measurement.RegionsVisited };}}diff --git a/docs/development/FIRMAMENT-ASSERTIONS-2026-10-19.md b/docs/development/FIRMAMENT-ASSERTIONS-2026-10-19.mdnew file mode 100644index 00000000..ba7ce0c3--- /dev/null+++ b/docs/development/FIRMAMENT-ASSERTIONS-2026-10-19.md@@ -0,0 +1,187 @@+# Firmament assertion qualification — 2026-10-19++## Contract and ownership++`validate` and normal `build` enforce assertions after engineering materialization+and export. An unsupported measurement, insufficient numerical precision, or an+unidentified target rejects admission. A failed, non-authoritative mesh comparison+is no longer silently admitted.++The shared AST binds `Assert Volume`, `Assert Bounds`, and `Assert Topology` using+the existing field-consumption owner. Both camelCase fields and historical+PascalCase aliases work. Unknown fields, duplicates, invalid dimensions and+unsupported assertion kinds fail. Uninstantiated Template/Feature definitions are+not mistaken for executed body assertions. A dedicated frontend that does not bind+an authored assertion must reject it rather than erase it.++`FirmamentMeasurements` owns the common CLI/assertion measurements of the exported+STEP BRep. JudgmentEngine selects an admitted exact volume recognizer first, then+a qualified SDF interval. The existing mass-properties tessellator remains an+explicit diagnostic comparison. No display-mesh estimate is promoted to authority.++`aetheris measure part.firmament --json` is an explicit inspection boundary. It+still parses, binds and constructs geometry, but reports `MeasuredNotAsserted` and+`assertionsEvaluated: false`. It can inspect a failed numerical assertion without+pretending that validation succeeded. Its suggested assertions expose measured+values and numerical uncertainty; they are not manufacturing acceptance criteria.++## Reproduced defects and repairs++| Finding | Observed baseline | Repair / qualification |+| --- | --- | --- |+| Non-authoritative volume failure | Build discarded failed assertions unless `MeasurementAuthoritative` was true | Every failed/unverified assertion rejects normal compilation |+| Midpoint-only comparison | A numerical midpoint could fit a tolerance even when its uncertainty did not | Entire measured interval must fit expected ± tolerance |+| Volume field spelling | Regex owner recognized old PascalCase line-shaped fields | Shared AST fields, casing aliases, closed field consumption |+| Assertion target | One exported body was measured regardless of the requested name | Resolve admitted material symbols and require the identified exported product; executor Profile names do not replace enclosing Struct identities |+| SDF cone classification | Eight outside corners could hide a negative interior | Conservative center-distance ± half-diagonal interval for the finite-cone distance function |+| Bounds | No source assertion contract | Exact rectangular-stock or planar straight-edge extrema only; unsupported curved extrema fail |+| Topology | No source assertion contract | Counts come from exported/reimported BRep topology |+| Through-hole plate volume | General prism recognition declined the exported cylindrical seam | Reuse the drawing owner's complete rectangular-plate query: stock area minus disjoint circular holes, times thickness |+| Stackup authoring | Regex Between/Require fields, ignored extra fields and generated locations | Shared AST binding, closed fields, camelCase aliases and mapped source spans |+| Stackup failure output | Assembly STEP export replaced the original failure with generic text, even under `--json` | Preserve compilation diagnostics and structured JSON before attempting export |+| SDK severity | Validation severity `error` projected as Info | Project `error` as Fatal alongside `fatal` |++## SDF evidence and limits++The bounded estimator classifies cells with analytic field intervals. Interior+cells contribute their full volume; mixed cells contribute [0, cell volume]. It+refines the largest unresolved cell deterministically, with explicit region and+depth limits. It does not claim sampling convergence as a certified error bound.+The implementation includes roundoff guards; it is not formal outward-rounded+interval arithmetic.++For a radius-10 mm sphere, with `--sdf --error 50 --compare-mesh`:++| Measurement | Volume, mm³ |+| --- | ---: |+| Independent analytic 4πr³/3 | 4188.790204786391 |+| SDF midpoint | 4188.237190246582 |+| SDF lower / upper | 4109.301567069637 / 4267.172813423527 |+| SDF half-width | 78.93562317694523 |+| Old display-mesh estimate | 4070.552360820173 |++This reached the 1,000,001-region cap, so `budgetExhausted: true` is required:+the requested ±50 mm³ was not reached. The midpoint improves this example's error+from about 2.82% to 0.0132%, but the defensible SDF interval is about ±1.88%.+Increasing the cap from 100,001 narrowed the original ±252.26 mm³ envelope without+loosening the specimen's assertion. A ±200 mm³ assertion passes; a tight or zero+tolerance cannot pass merely because the midpoint looks plausible.++Compiler SDF volume admission currently covers single Box/Cylinder/Cone/Sphere/Torus+primitives whose retained field is tied to that same exported primitive. Display+qualification alone does not establish occupied-volume parity. Legacy Boolean+mirrors are excluded: their execution/placement compatibility paths need their own+parity qualification before they can certify exported material. Generic field+Boolean interval arithmetic is tested separately, including a spherical cavity.++## ToleranceStackup: no solver rearchitecture required++The existing Assembly compiler resolves a unique dimensional relation path and+sums nominal values and worst-case asymmetric intervals. Reversed traversal swaps+and negates lower/upper contributions. This pass changes authoring admission and+diagnostic propagation, preserving that solver and its contributor provenance.++Canonical spelling:++```firmament+Assert ToleranceStackup AxialReach {+ between: [BearingModule.FixedSupport.Housing.Datum, BearingModule.Rotor.Shaft.Shoulder]+ require: clearance >= 44.90mm+}+```++The bearing witness remains nominal 45 mm, minimum 44.92 mm, maximum 45.10 mm.+Reversed traversal yields [-45.10, -44.92] mm. Missing/ambiguous paths and an+unsatisfied minimum reject compilation. `aetheris asm inspect assembly.firmament+--json` exposes the same solver's numbers and complete signed contributor chain,+including failing results where the compiler retains IR. No duplicate solver or+statistical RSS interpretation is introduced. Relations must be explicitly+declared or supplied by admitted Interface fit evidence; proximity is not a chain.++The through-hole plate witness uses 80×50×8 mm stock and an 8 mm diameter hole.+The independently computed occupied volume is 32000−128π mm³, with unchanged+stock bounds [-40,-25,0]–[40,25,8] mm. Its source asserts that volume within+1e-8 mm³, bounds, and one shell. No mesh or construction-history formula supplies+the measurement: the existing BRep query first accounts for every exported face,+loop and edge and rejects intersecting, blind or overlapping holes.++## Historical fillet specimens++These six files remain unchanged under `fixtures/Regression/CanonicalGeometry/`:++- `profile-fillet-convex-two-segment-top.firmament`+- `profile-fillet-convex-two-segment-bottom.firmament`+- `profile-fillet-reflex-two-segment-top.firmament`+- `profile-fillet-reflex-two-segment-bottom.firmament`+- `profile-edgefinish-chimera-fillet.firmament`+- `profile-edgefinish-chimera-reflex-sphere-compat.firmament`++Their geometry is constructible, but their authored volume assertions lack an+admitted exact recognizer or matching retained SDF. Ordinary validation/build now+rejects them with `firmament-v2-assert-volume-measurement-unavailable`. This is an+intentional compatibility correction, not a geometry failure or a proved design+mismatch. The first complete regression run exposed eight old success assertions+across these six sources.++Their geometry tests now explicitly require that rejection, inspect the unchanged+specimen through `CompileForMeasurement`, and compare STEP bytes with an admitted+control that masks only assertion syntax. Existing manifold, orientation, surface+type and determinism checks remain. No expected volume, tolerance, topology count,+or source specimen was edited to make the new assertion gate pass. General curved+fillet volume authority remains a specific qualification gap.++## Qualification++Final results:++| Check | Result |+| --- | --- |+| Release solution build | Passed; 0 errors, 32 warnings |+| Focused assertion/stackup/fillet qualification | 57 passed |+| Focused CLI measurements and validate/build/inspect agreement | 5 passed |+| Focused bounded SDF tests | 6 passed |+| Fast Core lane | 1,087 passed |+| Complete solution lane | 5,695 passed, 0 failed, 20 suites |+| Complete Core suite, including slow corpus | 1,220 passed |+| Complete Firmament suite | 2,966 passed |+| Complete CLI suite | 631 passed |+| Sheet metal / editable V8 | 164 / 7 passed |+| Whitespace / source preservation | `git diff --check` passed; existing canonical and geometry-regression source files unchanged |+| Runtime-host cleanup | No dotnet, testhost, MSBuild or VBCSCompiler processes remained after qualification |++Raw logs and CLI JSON remain under ignored `artifacts/local/assert-*` paths.+The sphere interval and through-hole plate values above were also checked through+the built CLI. Assembly inspection of `template-block-pair.firmament` reports+TemplateFitTransition nominal/minimum/maximum 2 mm and the Interface-derived+contributor with its Template/Record/occurrence provenance. CLI regression tests+raise the requirement to 3 mm and verify rejection plus the authored assertion span+through all three normal commands. Part diagnostics retain their authored line+even when an unused Record is erased before lowering.++Reproduction commands (serial, with MSBuild node reuse and shared compilation off):++```powershell+$env:MSBUILDDISABLENODEREUSE='1'+$env:DOTNET_PROCESSOR_COUNT='2'+dotnet build Aetheris.slnx -c Release --no-restore -m:1 -nr:false -p:UseSharedCompilation=false+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build -m:1 --filter 'Category!=SlowCorpus'+dotnet test Aetheris.slnx -c Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll measure fixtures/Regression/Assertions/box.firmament --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll measure fixtures/Regression/Assertions/sphere.firmament --sdf --error 50 --compare-mesh --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll asm inspect fixtures/Canonical/Assembly/template-block-pair.firmament --json+```++The code-quality pass checks shared validate/build admission, no diagnostic+fatality allowlist, no new regex dispatch/rewrite, preserved geometry authority,+closed AST fields, and explicit numerical budgets. The exact-volume query reuses+the existing recognizers without running their mesh fallback. Existing full mass+queries retain their independent surface-area/centroid completion behavior.++## Verdict++**Success for this bounded assertion pass.** Volume, bounds and topology assertions+now gate the real engineering path, the CLI exposes the numbers and uncertainty,+and ToleranceStackup uses shared AST admission while preserving its existing+worst-case solver. Geometry qualification remains intact. Unsupported measurement+families reject honestly; this pass does not claim a general curved-BRep volume+integrator, Boolean-mirror parity, or dedicated-domain assertion support.diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex 6b5853f6..d566e87b 100644--- a/docs/public/firmament/syntax.md+++ b/docs/public/firmament/syntax.md@@ -1282,6 +1282,99 @@ existing qualified mechanism adapter for those relationships. A static STEPexport is the compiled engineering configuration; sampling a clip does notsilently replace it with a different posed artifact.+## Checking the compiled part++Part assertions below are bound by the mechanical primitive/Compose/profile-extrusion+owner. Dedicated domain owners, including Revolve, must reject unbound assertions;+they do not acquire support by accepting the same block spelling.+Assertions check the final exported engineering body. They do not alter geometry,+add PMI, or specify a manufacturing tolerance. Normal `validate` and `build` both+enforce them. A failed assertion or an assertion that cannot be verified rejects+the build; it is never a successful build with a hidden `passed: false` result.++**Complete file — exact dimensions and topology:**++```firmament+Model CheckedBox {+ units: mm+ Box Body { size: [10mm, 8mm, 6mm] }+ Assert Volume Body { expected: 480mm^3; tolerance: 0mm^3 }+ Assert Bounds Body {+ min: [-5mm, -4mm, 0mm]+ max: [5mm, 4mm, 6mm]+ tolerance: 0mm+ }+ Assert Topology Body { faces: 6; edges: 12; vertices: 8; shells: 1 }+}+```++`Assert Volume` accepts finite nonnegative `expected` and `tolerance` literals in+`mm^3`, plus an optional string `note`. Exact BRep recognizers take precedence.+Otherwise, a compiler-retained analytic SDF qualified against the exported primitive supplies an adaptive occupied+volume interval. The entire interval must lie inside `expected ± tolerance` to+pass. A disjoint interval fails; an overlapping but inconclusive interval rejects+as **unverified**, including when the deterministic subdivision budget runs out.+The midpoint is an estimate, not an exact volume. Display-mesh mass estimates do+not gate an assertion. A part without an admitted exact recognizer or complete+SDF reports that limitation instead of silently accepting its volume assertion.+The SDF assertion route currently covers single Box, Cylinder, Cone, Sphere and+Torus primitives. A display-only or legacy Boolean mirror is insufficient evidence+that the field matches exported material, and is not promoted to volume authority.++`Assert Bounds` compares exact world-space minima/maxima, using the optional+nonnegative length `tolerance` (default 0mm). Exact bounds currently cover qualified+rectangular plate/box stock with Z-through holes and planar straight-edge bodies.+It rejects other families rather than treating sampled points or a Boolean field's+conservative enclosing box as the actual extrema. `Assert Topology` checks one or+more nonnegative integer `faces`, `edges`, `vertices`, `shells` counts in the exported+BRep. Counts describe kernel topology, so use them deliberately when topology itself+is the regression contract. All three families accept `note`. Historical PascalCase+field aliases remain accepted; new source uses camelCase.++The target must name the uniquely identified exported product. Requesting an earlier+body in a multi-body program does not measure the last body under the earlier name.+Assembly `Assert ToleranceStackup` checks the worst-case minimum along a unique+dimensional relation path:++```firmament+// Inside an Assembly with these semantic endpoints and dimensional relations:+Assert ToleranceStackup AxialReach {+ between: [BearingModule.FixedSupport.Housing.Datum, BearingModule.Rotor.Shaft.Shoulder]+ require: clearance >= 44.90mm+}+```++The assembly compiler sums nominal values and asymmetric tolerance intervals,+reversing their signs when traversing a relation backwards. Unresolved endpoints,+missing or ambiguous paths, and a minimum below the requirement reject compilation.+This checks declared dimensional relations; it does not infer a tolerance chain+from spatial proximity, perform statistical RSS analysis, or create PMI. Use typed+dimensions and explicit PMI for manufacturing requirements. `Between`, `Require`+and `Clearance` remain compatibility aliases. Unknown or duplicate fields fail.+See [assembly authoring](assembly-authoring-foundation.md).++To discover measured values, including while fixing a failed assertion:++```sh+aetheris measure checked-box.firmament --json+aetheris measure sphere.firmament --sdf --error 50 --compare-mesh --json+```++`measure` admits and builds the geometry but explicitly reports `MeasuredNotAsserted`+and `assertionsEvaluated: false`. It prints measurement methods, volume interval and+uncertainty, exact bounds where available, topology counts, and copyable assertion+templates. `--error` is a requested absolute volume error in mm³, subject to the+bounded work budget (at most 1,000,001 field regions and 30 subdivision levels).+`budgetExhausted` discloses when the requested error could not be reached; the+reported interval remains usable at its actual uncertainty. Suggested tolerances cover numerical uncertainty; select the+design's acceptance range independently. `--compare-mesh` exposes the older mass+estimate for diagnosis, never as a substitute assertion authority.++For assembly values use `aetheris asm inspect assembly.firmament --json`; its+`assemblyIr.toleranceStackups` contains nominal/minimum/maximum, requirement,+pass/fail, and the signed contributor chain. Unlike `measure`, assembly inspection+evaluates declared stackup assertions and returns failure when one fails.+## Reading older sourceNew ordinary parts should use the forms at the top of this page. Historicaldiff --git a/fixtures/Regression/Assertions/README.md b/fixtures/Regression/Assertions/README.mdnew file mode 100644index 00000000..83c590fd--- /dev/null+++ b/fixtures/Regression/Assertions/README.md@@ -0,0 +1,18 @@+# Assertion witnesses++| Source | Normal admission | Evidence |+| --- | --- | --- |+| `box.firmament` | Accepted | Exact 480 mm³, world bounds [-5,-4,0]–[5,4,6] mm, 6/12/8/1 face/edge/vertex/shell counts |+| `through-hole-plate.firmament` | Accepted | 80×50×8 mm stock minus an 8 mm through-hole: 32000−128π mm³, unchanged outer bounds and one shell |+| `sphere.firmament` | Accepted | Analytic 4π·10³/3 mm³ lies inside the bounded SDF interval; ±200 mm³ assertion encloses it |+| `two-bodies.firmament` | Rejected | Existing multiple-material-body admission gate rejects independent outputs before assertion evaluation; never measure Second under First's name |++The tests mutate expected values, fields and topology to prove rejection without+changing these witnesses. `measure` explicitly builds without evaluating declared+assertions and reports that level; it is not a successful validation substitute.++Six historical curved-fillet volume specimens are preserved in+`../CanonicalGeometry/`. Their unsupported volume assertions now reject normal+compilation. Geometry qualification uses explicit measurement and an assertion-free+control, preserving deterministic STEP and topology checks. See+`docs/development/FIRMAMENT-ASSERTIONS-2026-10-19.md` for the full classification.diff --git a/fixtures/Regression/Assertions/box.firmament b/fixtures/Regression/Assertions/box.firmamentnew file mode 100644index 00000000..83576dad--- /dev/null+++ b/fixtures/Regression/Assertions/box.firmament@@ -0,0 +1,7 @@+Model AssertBox {+ units: mm+ Box Body { size: [10mm, 8mm, 6mm] }+ Assert Volume Body { expected: 480mm^3; tolerance: 0mm^3; note: "Exact rectangular stock." }+ Assert Bounds Body { min: [-5mm, -4mm, 0mm]; max: [5mm, 4mm, 6mm]; tolerance: 0mm }+ Assert Topology Body { faces: 6; edges: 12; vertices: 8; shells: 1 }+}diff --git a/fixtures/Regression/Assertions/sphere.firmament b/fixtures/Regression/Assertions/sphere.firmamentnew file mode 100644index 00000000..f1f66c2e--- /dev/null+++ b/fixtures/Regression/Assertions/sphere.firmament@@ -0,0 +1,6 @@+Model AssertSphere {+ units: mm+ Sphere Body { radius: 10mm }+ Assert Volume Body { expected: 4188.790204786391mm^3; tolerance: 200mm^3 }+ Assert Topology Body { shells: 1 }+}diff --git a/fixtures/Regression/Assertions/through-hole-plate.firmament b/fixtures/Regression/Assertions/through-hole-plate.firmamentnew file mode 100644index 00000000..1d71cfb9--- /dev/null+++ b/fixtures/Regression/Assertions/through-hole-plate.firmament@@ -0,0 +1,15 @@+Model CheckedPlate {+ units: mm+ Box Body { size: [80mm, 50mm, 8mm] }+ Modify Body {+ Hole<Shaft> Mount {+ on: +Z+ center: Point2(0mm, 0mm)+ diameter: 8mm+ end: ThroughAll+ }+ }+ Assert Volume Body { expected: 31597.876140340508mm^3; tolerance: 0.00000001mm^3 }+ Assert Bounds Body { min: [-40mm, -25mm, 0mm]; max: [40mm, 25mm, 8mm] }+ Assert Topology Body { shells: 1 }+}diff --git a/fixtures/Regression/Assertions/two-bodies.firmament b/fixtures/Regression/Assertions/two-bodies.firmamentnew file mode 100644index 00000000..002a9f79--- /dev/null+++ b/fixtures/Regression/Assertions/two-bodies.firmament@@ -0,0 +1,6 @@+Model WrongTarget {+ units: mm+ Box First { size: [20mm, 10mm, 6mm] }+ Box Second { size: [10mm, 8mm, 6mm] }+ Assert Volume First { expected: 480mm^3; tolerance: 0mm^3 }+}