Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Preserve STEP geometry, PMI, and import qualification
Yuechen Li9baf92d98166
diff --git a/Aetheris.CLI.Tests/FirmamentFixtureCorpusTests.cs b/Aetheris.CLI.Tests/FirmamentFixtureCorpusTests.csindex b1822397..5a4e90df 100644--- a/Aetheris.CLI.Tests/FirmamentFixtureCorpusTests.cs+++ b/Aetheris.CLI.Tests/FirmamentFixtureCorpusTests.cs@@ -480,7 +480,7 @@ public sealed class FirmamentFixtureCorpusTestsvar stdout = new StringWriter(); var stderr = new StringWriter();var args = new[] { "trace", "--fixture", fixturePath, "--json" }.Concat(extraArgs).ToArray();var exit = Aetheris.CLI.CliRunner.Run(args, stdout, stderr);- Assert.True(exit == 0, stderr.ToString());+ Assert.True(exit == 0, fixturePath + Environment.NewLine + stderr);return JsonDocument.Parse(stdout.ToString());}diff --git a/Aetheris.CLI.Tests/RuledStepProbeHarnessTests.cs b/Aetheris.CLI.Tests/RuledStepProbeHarnessTests.csindex b58747e1..babc64b8 100644--- a/Aetheris.CLI.Tests/RuledStepProbeHarnessTests.cs+++ b/Aetheris.CLI.Tests/RuledStepProbeHarnessTests.cs@@ -8,7 +8,7 @@ public sealed class RuledStepProbeHarnessTestsprivate static readonly string RepoRoot = FindRepoRoot();[Fact]- public void Harness_Workflow_Generates_Deterministic_Wrapper_And_Reimports_Ruled_Probe()+ public void OpenRuledProbeRemainsInspectableButCannotBeExportedAsAProductionSolid(){var sourceProbe = Path.Combine(RepoRoot, "testdata", "step242", "generated", "ruled-a2", "ellipse-linear-extrusion-production.step");Assert.True(File.Exists(sourceProbe), $"Expected ruled production probe at '{sourceProbe}'.");@@ -32,23 +32,27 @@ public sealed class RuledStepProbeHarnessTeststry{- var canon = RunCli("canon", rawProbeCopy, "--out", canonicalInput, "--mode", "production", "--json");- Assert.Equal(0, canon.ExitCode);- Assert.True(File.Exists(canonicalInput));-- var wrapper = BuildWrapperSource(probeName, Path.GetFileName(canonicalInput));+ foreach (var mode in new[] { "production", "deterministic" })+ {+ var canon = RunCli("canon", rawProbeCopy, "--out", canonicalInput, "--mode", mode, "--json");+ Assert.NotEqual(0, canon.ExitCode);+ Assert.Contains("brep-preflight-imported-shell-not-enclosed", canon.StdOut);+ Assert.False(File.Exists(canonicalInput));+ }+ var wrapper = BuildWrapperSource(probeName, originalProbeName);File.WriteAllText(wrapperPath, wrapper);Assert.Equal(Path.Combine(wrapperDir, "ellipseLinearExtrusionProduction.firm"), wrapperPath);Assert.Equal(Path.Combine(outputDir, "ellipseLinearExtrusionProduction.canonical.step"), outputStepPath);Assert.Contains("InlineStep", wrapper, StringComparison.Ordinal);- Assert.Contains("../input/ellipseLinearExtrusionProduction.canonical-input.step", wrapper, StringComparison.Ordinal);+ Assert.Contains("../input/" + originalProbeName, wrapper, StringComparison.Ordinal);var build = RunCli("build", wrapperPath, "--out", outputStepPath, "--json");- Assert.Equal(0, build.ExitCode);- Assert.True(File.Exists(outputStepPath));+ Assert.NotEqual(0, build.ExitCode);+ Assert.Contains("brep-preflight-imported-shell-not-enclosed", build.StdOut);+ Assert.False(File.Exists(outputStepPath));- var stepText = File.ReadAllText(outputStepPath);+ var stepText = File.ReadAllText(rawProbeCopy);Assert.Contains("SURFACE_OF_LINEAR_EXTRUSION", stepText, StringComparison.Ordinal);Assert.Contains("ELLIPSE", stepText, StringComparison.Ordinal);Assert.DoesNotContain("B_SPLINE_SURFACE_WITH_KNOTS", stepText, StringComparison.Ordinal);@@ -57,12 +61,9 @@ public sealed class RuledStepProbeHarnessTestsAssert.True(import.IsSuccess, string.Join(Environment.NewLine, import.Diagnostics.Select(d => $"{d.Source}: {d.Message}")));Assert.Contains(import.Value.Geometry.Surfaces, entry => entry.Value.Kind == Aetheris.Kernel.Core.Geometry.SurfaceGeometryKind.LinearExtrusion);- var reimportSmokePath = Path.Combine(outputDir, probeName + ".reimport-smoke.step");- var reimport = RunCli("canon", outputStepPath, "--out", reimportSmokePath, "--json");- Assert.Equal(0, reimport.ExitCode);- Assert.True(File.Exists(reimportSmokePath));-- var analyze = RunCli("analyze", outputStepPath, "--json");+ Assert.False(import.Value.ImportQualification!.Shells.Single().Enclosed);+ Assert.Equal(4, import.Value.ImportQualification.Shells.Single().BoundaryEdges);+ var analyze = RunCli("analyze", rawProbeCopy, "--json");using var doc = JsonDocument.Parse(analyze.StdOut);if (analyze.ExitCode == 0){@@ -85,6 +86,43 @@ public sealed class RuledStepProbeHarnessTests}}+ [Theory]+ [InlineData("production")]+ [InlineData("deterministic")]+ public void ClosedEllipsePartPassesTheSameStrictCanonBoundary(string mode)+ {+ var root = Path.Combine(RepoRoot, "artifacts", "local", "test", "closed-ruled", Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(root);+ var input = Path.Combine(root, "closed.step"); var output = Path.Combine(root, "canonical.step");+ var build = RunCli("build", Path.Combine(RepoRoot, "fixtures/Canonical/Boundary2/closed-ellipse-extrusion.firmament"), "--out", input, "--json");+ Assert.True(build.ExitCode == 0, build.StdOut + build.StdErr);+ var canon = RunCli("canon", input, "--out", output, "--mode", mode, "--json");+ Assert.True(canon.ExitCode == 0, canon.StdOut + canon.StdErr);+ var text = File.ReadAllText(output);+ Assert.Contains("SURFACE_OF_LINEAR_EXTRUSION", text); Assert.Contains("ELLIPSE", text);+ var imported = Step242Importer.ImportBody(text); Assert.True(imported.IsSuccess);+ Assert.True(imported.Value.ImportQualification!.Shells.Single().Enclosed);+ }++ [Theory]+ [InlineData("production")]+ [InlineData("deterministic")]+ public void CanonMetadataModeDoesNotDiscardSemanticPmi(string mode)+ {+ var root = Path.Combine(RepoRoot, "artifacts", "local", "test", "canon-pmi", Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(root);+ var input = Path.Combine(root, "part.step"); var output = Path.Combine(root, "canonical.step");+ var built = RunCli("build", Path.Combine(RepoRoot, "fixtures/Canonical/PMI/explicit-gdt.firmament"), "--out", input, "--json");+ Assert.True(built.ExitCode == 0, built.StdOut + built.StdErr);+ var result = RunCli("canon", input, "--out", output, "--mode", mode, "--json");+ Assert.True(result.ExitCode == 0, result.StdOut + result.StdErr);+ var pmi = Step242SemanticPmiInspector.Inspect(File.ReadAllText(output));+ Assert.Equal(3, pmi.DatumCount); Assert.Equal(3, pmi.GeometricToleranceCount);+ Assert.All(pmi.Items, item => Assert.NotEmpty(item.GeometricFaceEntityIds));+ using var report = JsonDocument.Parse(result.StdOut);+ Assert.Equal(JsonValueKind.Array, report.RootElement.GetProperty("diagnostics").ValueKind);+ }+[Fact]public void Harness_Documentation_And_Script_Are_Present_And_Reference_InlineStep(){diff --git a/Aetheris.CLI.Tests/SourceIntentClosureRegressionTests.cs b/Aetheris.CLI.Tests/SourceIntentClosureRegressionTests.csindex 7b503708..e759f12f 100644--- a/Aetheris.CLI.Tests/SourceIntentClosureRegressionTests.cs+++ b/Aetheris.CLI.Tests/SourceIntentClosureRegressionTests.cs@@ -40,9 +40,11 @@ public sealed class SourceIntentClosureRegressionTestsprivate static (int ExitCode, string Output) Validate(string source, string fixture){- // Keep the file beside the original so relative imports still resolve.- var directory = Path.GetDirectoryName(Path.Combine(RepoRoot(), "fixtures", "Canonical", fixture))!;- var path = Path.Combine(directory, $".closure-{Guid.NewGuid():N}.firmament");+ // These specimens are self-contained. Keep generated mutations out of the+ // canonical tree, which other parallel tests enumerate as durable source.+ var directory = Path.Combine(RepoRoot(), "artifacts", "local", "source-intent-closure");+ Directory.CreateDirectory(directory);+ var path = Path.Combine(directory, $"{Path.GetFileNameWithoutExtension(fixture)}-{Guid.NewGuid():N}.firmament");File.WriteAllText(path, source);try{diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 8e21ed21..7bc152ce 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -3070,7 +3070,8 @@ Model CanonicalPanel {return WriteCanonFailure(json, stdout, stderr, inputFullPath, outputFullPath, "io-read-failure", ex.Message);}- var importResult = Aetheris.Kernel.Core.Step242.Step242Importer.ImportBody(stepText);+ var importResult = Aetheris.Kernel.Core.Step242.Step242Importer.ImportBody(stepText,+ new Aetheris.Kernel.Core.Import.ImportPolicy(PreferredLane: Aetheris.Kernel.Core.Import.ImportLaneKind.ExactBRep));if (!importResult.IsSuccess){return WriteCanonFailure(@@ -3083,10 +3084,17 @@ Model CanonicalPanel {FormatKernelDiagnostics(importResult.Diagnostics));}+ var sourcePmi = Aetheris.Kernel.Core.Step242.Step242PmiTransfer.Read(stepText, importResult.Value);+ if (!sourcePmi.IsSuccess)+ return WriteCanonFailure(json, stdout, stderr, inputFullPath, outputFullPath, "pmi-transfer-failure", FormatKernelDiagnostics(sourcePmi.Diagnostics));+ var importedPmi = sourcePmi.Value.SemanticRecordCount > 0 ? sourcePmi.Value : null;var exportOptions = canonMode == Aetheris.Kernel.Core.Step242.Step242CanonMode.ProductionPreserveMetadata? Aetheris.Kernel.Core.Step242.Step242ExportOptions.FromSourceMetadata(Aetheris.Kernel.Core.Step242.Step242SourceMetadataReader.Read(stepText),- Aetheris.Kernel.Core.Step242.BrepExportPreflightPolicy.TrustedProductionRoute)- : new Aetheris.Kernel.Core.Step242.Step242ExportOptions();+ Aetheris.Kernel.Core.Step242.BrepExportPreflightPolicy.TrustedProductionRoute, importedPmi)+ : new Aetheris.Kernel.Core.Step242.Step242ExportOptions {+ ImportedPmi = importedPmi,+ BrepExportPreflightPolicy = Aetheris.Kernel.Core.Step242.BrepExportPreflightPolicy.TrustedProductionRoute,+ ImportedRecoveryToleranceMillimetres = .1 };var exportResult = Aetheris.Kernel.Core.Step242.Step242Exporter.ExportBody(importResult.Value, exportOptions);if (!exportResult.IsSuccess)@@ -3120,6 +3128,8 @@ Model CanonicalPanel {outputPath = outputFullPath,bodyCount = topology.Bodies.Count(),shellCount = topology.Shells.Count(),+ diagnostics = exportResult.Diagnostics.Select(d => new {+ code = d.Code.ToString(), severity = d.Severity.ToString(), message = d.Message, source = d.Source }),mode = canonMode == Aetheris.Kernel.Core.Step242.Step242CanonMode.ProductionPreserveMetadata ? "production" : "deterministic"}, JsonOptions));}@@ -3127,6 +3137,8 @@ Model CanonicalPanel {{stdout.WriteLine($"Canonical STEP written: {outputFullPath}");stdout.WriteLine($"Canon mode: {(canonMode == Aetheris.Kernel.Core.Step242.Step242CanonMode.ProductionPreserveMetadata ? "production" : "deterministic")}");+ foreach (var diagnostic in exportResult.Diagnostics.Where(d => d.Severity == Aetheris.Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Warning)+ .DistinctBy(d => d.Message)) stderr.WriteLine($"warning {diagnostic.Source}: {diagnostic.Message}");}return 0;diff --git a/Aetheris.Kernel.Core.Tests/Brep/BrepPathFeatureTests.cs b/Aetheris.Kernel.Core.Tests/Brep/BrepPathFeatureTests.csnew file mode 100644index 00000000..6d31e1c3--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Brep/BrepPathFeatureTests.cs@@ -0,0 +1,101 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Kernel.Core.Tests.Brep;++public sealed class BrepPathFeatureTests+{+ private static readonly BrepMassPropertiesOptions Accuracy = new(.002, double.Pi / 180, .01, 64, 128);+ [Theory]+ [InlineData(0, 8, 0, "dimensions")]+ [InlineData(3, 8, 30, "draft-collapse")]+ [InlineData(3, 8, -1, "dimensions")]+ [InlineData(100, 8, 0, "support")]+ public void UnconstructibleRibDoesNotProduceABody(double thickness, double height, double draft, string code)+ {+ var feature = new PlanarPathFeature("Web", true, PathSectionKind.Rectangular,+ new(PlanarGuideKind.Line, new(-10,0), new(10,0), default), thickness, height, draft);+ var rejected = BrepPlanarPathFeature.BuildBox(40, 30, 5, [feature]);+ Assert.False(rejected.IsSuccess); Assert.Contains(rejected.Diagnostics, d => d.Message.Contains(code, StringComparison.Ordinal));+ }+ [Fact]+ public void CutsCannotRemoveTheirFloorOrCrossEachOther()+ {+ var deep = new PlanarPathFeature("Cut", false, PathSectionKind.Rectangular,+ new(PlanarGuideKind.Line, new(-10,0), new(10,0), default), 3, 5);+ Assert.False(BrepPlanarPathFeature.BuildBox(40,30,5,[deep]).IsSuccess);+ Assert.False(BrepCircumferentialGroove.BuildCylinder(15,40,[new("Bore", PathSectionKind.Rectangular,4,5,0,true)],5).IsSuccess);+ Assert.False(BrepCircumferentialGroove.BuildCylinder(15,40,[+ new("A", PathSectionKind.Rectangular,4,1,0),new("B",PathSectionKind.Rectangular,4,1,1)]).IsSuccess);+ Assert.False(BrepCircumferentialGroove.BuildCylinder(15,40,[new("Unknown",(PathSectionKind)1234,4,1,0)]).IsSuccess);+ }+ [Theory]+ [InlineData(false, false, PathSectionKind.Rectangular)]+ [InlineData(false, false, PathSectionKind.Semicircular)]+ [InlineData(true, false, PathSectionKind.Rectangular)]+ [InlineData(true, false, PathSectionKind.Semicircular)]+ [InlineData(true, true, PathSectionKind.Rectangular)]+ [InlineData(true, true, PathSectionKind.Semicircular)]+ public void CylinderGrooveRetainsTheStockAndCaps(bool hollow, bool inner, PathSectionKind section)+ {+ var built = BrepCircumferentialGroove.BuildCylinder(15, 40,+ [new("Seal", section, 4, 2, 0, inner)], hollow ? 5 : null);+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));+ var mass = BrepMassProperties.Evaluate(built.Value.Body, Accuracy);+ var expected = double.Pi * 15 * 15 * 40 - (hollow ? double.Pi * 10 * 10 * 35 : 0) + built.Value.MaterialVolumeDelta;+ Assert.True(mass.IsEnclosed && mass.IsOrientationConsistent, string.Join("; ", mass.Diagnostics));+ Assert.InRange(mass.SignedVolume, expected * .999, expected * 1.001);+ var stockVolume = expected - built.Value.MaterialVolumeDelta;+ var deltaTolerance = double.Abs(built.Value.MaterialVolumeDelta) * .03;+ Assert.InRange(mass.SignedVolume - stockVolume, built.Value.MaterialVolumeDelta - deltaTolerance, built.Value.MaterialVolumeDelta + deltaTolerance);+ var step = Step242Exporter.ExportBody(built.Value.Body, new Step242ExportOptions { BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });+ Assert.True(step.IsSuccess, string.Join("; ", step.Diagnostics.Select(d => d.Message)));+ var again = Step242Importer.ImportBody(step.Value);+ Assert.True(again.IsSuccess, string.Join("; ", again.Diagnostics.Select(d => d.Message)));+ var after = BrepMassProperties.Evaluate(again.Value, Accuracy);+ Assert.True(after.IsEnclosed && after.IsOrientationConsistent);+ Assert.InRange(after.SignedVolume / mass.SignedVolume, .999, 1.001);+ }+ [Theory]+ [InlineData(PlanarGuideKind.Line, true, PathSectionKind.Rectangular, false)]+ [InlineData(PlanarGuideKind.Line, true, PathSectionKind.Rectangular, true)]+ [InlineData(PlanarGuideKind.Arc, true, PathSectionKind.Rectangular, false)]+ [InlineData(PlanarGuideKind.Circle, true, PathSectionKind.Rectangular, false)]+ [InlineData(PlanarGuideKind.Line, false, PathSectionKind.Rectangular, false)]+ [InlineData(PlanarGuideKind.Line, false, PathSectionKind.Rectangular, true)]+ [InlineData(PlanarGuideKind.Arc, false, PathSectionKind.Rectangular, false)]+ [InlineData(PlanarGuideKind.Circle, false, PathSectionKind.Rectangular, false)]+ [InlineData(PlanarGuideKind.Line, false, PathSectionKind.Semicircular, false)]+ [InlineData(PlanarGuideKind.Line, false, PathSectionKind.Semicircular, true)]+ [InlineData(PlanarGuideKind.Arc, false, PathSectionKind.Semicircular, false)]+ [InlineData(PlanarGuideKind.Circle, false, PathSectionKind.Semicircular, false)]+ public void LocalFeatureIsOneClosedAnalyticBody(PlanarGuideKind kind, bool add, PathSectionKind section, bool round)+ {+ var guide = new PlanarFeatureGuide(kind, new(-10, 0), new(10, 0), new(0, 0), 10, 0, double.Pi / 2);+ var feature = new PlanarPathFeature("Feature", add, section, guide, 4, section == PathSectionKind.Semicircular ? 2 : add ? 8 : 2, add ? 2 : 0, round);+ var built = BrepPlanarPathFeature.BuildBox(60, 50, 10, [feature]);+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));+ var body = built.Value.Body;+ var mass = BrepMassProperties.Evaluate(body, Accuracy);+ Assert.True(mass.IsEnclosed && mass.IsOrientationConsistent, string.Join("; ", mass.Diagnostics));+ Assert.InRange(mass.SignedVolume, (30000 + built.Value.MaterialVolumeDelta) * .995, (30000 + built.Value.MaterialVolumeDelta) * 1.005);+ // Bound the feature's effect, not just the much larger stock volume:+ // omitting a small channel must not fit inside the test tolerance.+ var deltaTolerance = double.Abs(built.Value.MaterialVolumeDelta) * .02;+ Assert.InRange(mass.SignedVolume - 30000, built.Value.MaterialVolumeDelta - deltaTolerance, built.Value.MaterialVolumeDelta + deltaTolerance);+ Assert.All(body.Topology.Edges, edge => Assert.Equal(2, body.Topology.Coedges.Count(c => c.EdgeId == edge.Id)));+ if (kind == PlanarGuideKind.Line && section == PathSectionKind.Semicircular && !round)+ Assert.False(BrepMassProperties.TryEvaluateExactVolume(body, out _)); // Must not masquerade as a convex quarter-cylinder fillet.+ Assert.All(body.Geometry.Surfaces, s => Assert.Null(s.Value.BSplineSurfaceWithKnots));+ var exported = Step242Exporter.ExportBody(body, new Step242ExportOptions { BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });+ Assert.True(exported.IsSuccess, string.Join("; ", exported.Diagnostics.Select(d => d.Message)));+ var imported = Step242Importer.ImportBody(exported.Value);+ Assert.True(imported.IsSuccess, string.Join("; ", imported.Diagnostics.Select(d => d.Message)));+ var again = BrepMassProperties.Evaluate(imported.Value, Accuracy);+ Assert.True(again.IsEnclosed && again.IsOrientationConsistent, string.Join("; ", again.Diagnostics));+ Assert.InRange(again.SignedVolume / mass.SignedVolume, .999, 1.001);+ }+}diff --git a/Aetheris.Kernel.Core.Tests/Geometry/BSpline3CurveBoundaryTests.cs b/Aetheris.Kernel.Core.Tests/Geometry/BSpline3CurveBoundaryTests.csnew file mode 100644index 00000000..ec0a1f94--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Geometry/BSpline3CurveBoundaryTests.cs@@ -0,0 +1,23 @@+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Kernel.Core.Tests.Geometry;++public sealed class BSpline3CurveBoundaryTests+{+ [Fact]+ public void NonClampedEndUsesTheBasisLimitForPositionAndDerivatives()+ {+ var curve = new BSpline3Curve(2, [new(0, 0, 0), new(1, 0, 0), new(3, 0, 0), new(6, 0, 0)],+ [1, 1, 1, 1, 1, 1, 1], [-2, -1, 0, 1, 2, 3, 4], "UNSPECIFIED", false, false, "UNSPECIFIED");+ // Uniform quadratic basis at u=2: half of each final control point.+ Assert.Equal(new Point3D(4.5, 0, 0), curve.Evaluate(curve.DomainEnd));+ Assert.Equal(new Vector3D(3, 0, 0), curve.EvaluateTangent(curve.DomainEnd));+ Assert.Equal(new Vector3D(1, 0, 0), curve.EvaluateSecondDerivative(curve.DomainEnd));+ Assert.Equal(curve.EvaluateRational([1, 1, 1, 1], curve.DomainEnd), curve.Evaluate(curve.DomainEnd));+ Assert.InRange((curve.Evaluate(curve.DomainEnd - 1e-8) - curve.Evaluate(curve.DomainEnd)).Length, 0, 1e-7);+ var cubic = new BSpline3Curve(3, [new(0, 0, 0), new(1, 0, 0), new(4, 0, 0), new(9, 0, 0), new(16, 0, 0)],+ Enumerable.Repeat(1, 9).ToArray(), [-3, -2, -1, 0, 1, 2, 3, 4, 5], "UNSPECIFIED", false, false, "UNSPECIFIED");+ Assert.Equal(new Vector3D(6, 0, 0), cubic.EvaluateTangent(cubic.DomainEnd));+ }+}diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242StrictImportedExportTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242StrictImportedExportTests.csnew file mode 100644index 00000000..b201d90c--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242StrictImportedExportTests.cs@@ -0,0 +1,107 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Kernel.Core.Tests.Step242;++public sealed class Step242StrictImportedExportTests+{+ [Theory, MemberData(nameof(Step242PmiTransferTests.NistFiles), MemberType = typeof(Step242PmiTransferTests)), Trait("Category", "SlowCorpus")]+ public void NistExactPartsPassStrictOutputWithoutRequiringCompleteSourceUvRecovery(string path)+ {+ var body = Step242Corpus.Body(path);+ var transfer = Step242PmiTransfer.Read(Step242Corpus.Text(path), body);+ Assert.True(transfer.IsSuccess, string.Join(";", transfer.Diagnostics.Select(d => d.Message)));+ var result = Step242Exporter.ExportBody(body, new Step242ExportOptions {+ ImportedPmi = transfer.Value, ImportedRecoveryToleranceMillimetres = .1,+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });+ Assert.True(result.IsSuccess, path + ": " + string.Join(";", result.Diagnostics.Select(d => d.Message)));+ Assert.DoesNotContain("RATIONAL_B_SPLINE_CURVE", result.Value, StringComparison.Ordinal);+ // Any rational surface emission must originate in a native ellipsoid patch.+ var parsed = Step242SubsetParser.Parse(result.Value).Value;+ Assert.Equal(body.Geometry.Surfaces.Count(s => s.Value.Ellipsoid is not null),+ parsed.Entities.Count(e => Step242SubsetDecoder.TryGetConstructor(e.Instance, "RATIONAL_B_SPLINE_SURFACE") is not null));+ var roundtrip = Step242Importer.ImportBody(result.Value);+ Assert.True(roundtrip.IsSuccess, string.Join(";", roundtrip.Diagnostics.Select(d => d.Message)));+ Assert.Equal(body.Topology.Faces.Count(), roundtrip.Value.Topology.Faces.Count());+ Assert.Equal(body.Topology.Edges.Count(), roundtrip.Value.Topology.Edges.Count());+ var before = Step242SemanticPmiInspector.Inspect(Step242Corpus.Text(path)); var after = Step242SemanticPmiInspector.Inspect(result.Value);+ Assert.Equal(before.DatumCount, after.DatumCount); Assert.Equal(before.DimensionCount, after.DimensionCount);+ Assert.Equal(before.GeometricToleranceCount, after.GeometricToleranceCount);+ if (result.Diagnostics.Any(d => d.Message.StartsWith("step-export-recovered-pcurves-omitted:", StringComparison.Ordinal)))+ Assert.DoesNotContain(parsed.Entities, e => e.Name is "SURFACE_CURVE" or "SEAM_CURVE");+ }++ [Fact]+ public void InvalidPhysicalBoundaryStillFailsStrictExport()+ {+ var box = BrepPrimitives.CreateBox(10, 10, 10).Value;+ var moved = box.Topology.Vertices.First().Id;+ var points = box.Topology.Vertices.ToDictionary(v => v.Id, v => { box.TryGetVertexPoint(v.Id, out var p); return v.Id == moved ? p + new Aetheris.Kernel.Core.Math.Vector3D(1, 0, 0) : p; });+ var damaged = new BrepBody(box.Topology, box.Geometry, box.Bindings, points);+ var result = Step242Exporter.ExportBody(damaged, new Step242ExportOptions {+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, d => d.Message.Contains("brep-preflight-", StringComparison.Ordinal));+ }+ [Fact]+ public void InvalidOptionalUvTraceIsOmittedWithoutMutatingTheBody()+ {+ var stock = BrepPrimitives.CreateBox(10, 10, 10).Value;+ var source = Step242Exporter.ExportBody(stock, [new Step242SemanticPmiGeometricTolerance("Seat", "Seat", "Flatness", .03, [])+ { GeometricFaceIds = [stock.Topology.Faces.First().Id.Value] }]).Value;+ var original = Step242Importer.ImportBody(source).Value;+ var transfer = Step242PmiTransfer.Read(source, original).Value;+ var face = original.Topology.Faces.First(); var coedge = original.Topology.GetLoop(face.LoopIds[0]).CoedgeIds[0];+ var surface = original.Bindings.GetFaceBinding(face.Id).SurfaceGeometryId;+ var bad = new CoedgePcurveBinding(coedge, face.Id, surface, PcurveGeometry.Line(new(0, 1), new(999, 999), new(1000, 999)));+ var bindings = new BrepBindingModel();+ foreach (var binding in original.Bindings.EdgeBindings) bindings.AddEdgeBinding(binding);+ foreach (var binding in original.Bindings.FaceBindings) bindings.AddFaceBinding(binding);+ foreach (var binding in original.Bindings.PcurveBindings) bindings.AddPcurveBinding(binding.CoedgeId == coedge ? bad : binding);+ var points = original.Topology.Vertices.ToDictionary(v => v.Id, v => { original.TryGetVertexPoint(v.Id, out var p); return p; });+ var box = new BrepBody(original.Topology, original.Geometry, bindings, points, shellRepresentation: original.ShellRepresentation,+ faceOrientationReport: original.FaceOrientationReport) { ImportQualification = original.ImportQualification };+ var result = Step242Exporter.ExportBody(box, new Step242ExportOptions { ImportedPmi = transfer,+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce, BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });+ Assert.True(result.IsSuccess, string.Join(";", result.Diagnostics.Select(d => d.Message)));+ Assert.Contains(result.Diagnostics, d => d.Message.StartsWith("step-export-recovered-pcurves-omitted:", StringComparison.Ordinal));+ Assert.DoesNotContain(Step242SubsetParser.Parse(result.Value).Value.Entities, e => e.Name == "PCURVE");+ Assert.Contains(bad, box.Bindings.PcurveBindings);+ var control = Assert.Single(Step242SemanticPmiInspector.Inspect(result.Value).Items, item => item.Kind == "Flatness");+ Assert.Equal(.03, control.Value); Assert.Single(control.GeometricFaceEntityIds);+ }+ [Fact]+ public void NativeEllipsoidHasTheExplicitRationalProjectionException()+ {+ var body = EllipsoidPrimitive.Create(10, 8, 6).Value;+ var result = Step242Exporter.ExportBody(body, new Step242ExportOptions {+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce, BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });+ Assert.True(result.IsSuccess, string.Join(";", result.Diagnostics.Select(d => d.Message)));+ var parsed = Step242SubsetParser.Parse(result.Value).Value;+ Assert.Equal(8, parsed.Entities.Count(e => Step242SubsetDecoder.TryGetConstructor(e.Instance, "RATIONAL_B_SPLINE_SURFACE") is not null));+ var again = Step242Importer.ImportBody(result.Value);+ Assert.True(again.IsSuccess); Assert.All(again.Value.Geometry.Surfaces, surface => Assert.NotNull(surface.Value.Ellipsoid));+ }+ [Fact]+ public void AnnotationDependenciesCannotBypassTheRationalGeometryGuard()+ {+ var box = BrepPrimitives.CreateBox(10, 10, 10).Value;+ var source = Step242Exporter.ExportBody(box, [new Step242SemanticPmiGeometricTolerance("Seat", "Seat", "Flatness", .03, [])+ { GeometricFaceIds = [box.Topology.Faces.First().Id.Value] }]).Value;+ var parsed = Step242SubsetParser.Parse(source).Value;+ var control = parsed.Entities.Single(e => Step242PmiTransfer.GeometricTolerance(e) is not null);+ var aspect = ((Step242EntityReference)Step242PmiTransfer.GeometricTolerance(control)!.Arguments[3]).TargetId;+ var points = parsed.Entities.Where(e => e.Name == "CARTESIAN_POINT").Take(2).ToArray();+ var fresh = parsed.Entities.Max(e => e.Id) + 1;+ var context = parsed.Entities.First(e => Step242SubsetDecoder.TryGetConstructor(e.Instance, "GLOBAL_UNIT_ASSIGNED_CONTEXT") is not null).Id;+ source = source.Insert(source.LastIndexOf("ENDSEC;", StringComparison.Ordinal),+ $"#{fresh}=PROPERTY_DEFINITION('auxiliary',$,#{aspect});\n#{fresh+1}=PROPERTY_DEFINITION_REPRESENTATION(#{fresh},#{fresh+2});\n"+ + $"#{fresh+2}=REPRESENTATION('',(#{fresh+3}),#{context});\n#{fresh+3}=(B_SPLINE_CURVE(1,(#{points[0].Id},#{points[1].Id}),.UNSPECIFIED.,.F.,.F.)B_SPLINE_CURVE_WITH_KNOTS((2,2),(0.,1.),.UNSPECIFIED.)CURVE()GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_CURVE((1.,2.))REPRESENTATION_ITEM('auxiliary'));\n");+ var body = Step242Importer.ImportBody(source).Value; var transfer = Step242PmiTransfer.Read(source, body);+ Assert.True(transfer.IsSuccess, string.Join(";", transfer.Diagnostics.Select(d => d.Message)));+ var result = Step242Exporter.ExportBody(body, new Step242ExportOptions { ImportedPmi = transfer.Value,+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce, BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });+ Assert.False(result.IsSuccess); Assert.Contains(result.Diagnostics, d => d.Message.Contains("pmi-source-rational-geometry-not-canonical", StringComparison.Ordinal));+ }+}diff --git a/Aetheris.Kernel.Core/Brep/BrepExportPreflight.cs b/Aetheris.Kernel.Core/Brep/BrepExportPreflight.csindex 506b4660..13633a3f 100644--- a/Aetheris.Kernel.Core/Brep/BrepExportPreflight.cs+++ b/Aetheris.Kernel.Core/Brep/BrepExportPreflight.cs@@ -73,6 +73,9 @@ public static class BrepExportPreflightvar checkedEdges = new HashSet<EdgeId>();var checkedFaces = 0;var checkedLoops = 0;+ foreach (var shell in body.ImportQualification?.Shells ?? [])+ if (!shell.Enclosed)+ AddError("brep-preflight-imported-shell-not-enclosed", "shell", $"Imported shell {shell.ShellId} has not proved a connected closed manifold: components={shell.ConnectedComponents}, boundaryEdges={shell.BoundaryEdges}, nonManifoldEdges={shell.NonManifoldEdges}.");foreach (var face in model.Faces.OrderBy(face => face.Id.Value)){@@ -199,6 +202,9 @@ public static class BrepExportPreflightvar isClosedSpline = curve.BSpline3 is { } closedSpline && closedSpline.ClosedCurve &&(closedSpline.Evaluate(binding.TrimInterval.Value.Start) -closedSpline.Evaluate(binding.TrimInterval.Value.End)).Length <= Tolerances.Linear;+ if (curve.BSpline3 is { } bounded && (binding.TrimInterval.Value.Start < bounded.DomainStart - 1e-12+ || binding.TrimInterval.Value.End > bounded.DomainEnd + 1e-12))+ AddError("brep-preflight-edge-trim-outside-domain", "edge", "Spline edge trim lies outside its basis domain.", edgeId: edge.Id.Value);if (edge.StartVertexId == edge.EndVertexId &&curve.Kind is not CurveGeometryKind.Circle3 and not CurveGeometryKind.Ellipse3 && !isClosedSpline)AddError("brep-preflight-edge-degenerate", "edge", "Non-periodic edge uses the same topology vertex at both endpoints.", edgeId: edge.Id.Value);diff --git a/Aetheris.Kernel.Core/Brep/Features/BrepCircumferentialGroove.cs b/Aetheris.Kernel.Core/Brep/Features/BrepCircumferentialGroove.csnew file mode 100644index 00000000..cf410161--- /dev/null+++ b/Aetheris.Kernel.Core/Brep/Features/BrepCircumferentialGroove.cs@@ -0,0 +1,147 @@+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Core.Brep.Features;++public sealed record CircumferentialGroove(string Name, PathSectionKind Section, double Width,+ double Depth, double Station, bool Inner = false);++/// <summary>Exact stock-owned rotational boundary. A groove replaces a finite+/// cylindrical band with shoulders/floor or a toroidal meridian. No Boolean tool+/// bodies or general intersections are involved. Coordinates are centered on Z.</summary>+public static class BrepCircumferentialGroove+{+ public static KernelResult<PathFeatureBody> BuildCylinder(double radius, double height,+ IReadOnlyList<CircumferentialGroove> grooves, double? wallThickness = null)+ {+ if (!double.IsFinite(radius + height) || radius <= 0 || height <= 0+ || wallThickness is { } wall && (!double.IsFinite(wall) || wall <= 0 || wall >= radius || wall >= height))+ return BrepPlanarPathFeature.Failure("dimensions", "Cylinder dimensions and optional top-open vessel wall must be finite and positive.");+ var innerRadius = wallThickness is { } w ? radius - w : 0;+ var bottom = -height / 2; var top = height / 2; var floor = bottom + (wallThickness ?? 0);+ var names = new HashSet<string>();+ foreach (var g in grooves)+ {+ var half = g.Width / 2;+ if (!names.Add(g.Name)) return BrepPlanarPathFeature.Failure("duplicate", $"Duplicate groove '{g.Name}'.");+ if (!Enum.IsDefined(g.Section) || !double.IsFinite(g.Width + g.Depth + g.Station) || g.Width <= 0 || g.Depth <= 0+ || g.Section == PathSectionKind.Semicircular && double.Abs(g.Width - 2 * g.Depth) > 1e-9)+ return BrepPlanarPathFeature.Failure("dimensions", $"{g.Name}: positive dimensions are required; a semicircle has width = 2 × depth.");+ if (g.Inner && wallThickness is null) return BrepPlanarPathFeature.Failure("support", $"{g.Name}: InnerWall requires a hollow cylindrical host.");+ if (g.Station - half <= (g.Inner ? floor : bottom) + 1e-8 || g.Station + half >= top - 1e-8+ || g.Depth >= (wallThickness ?? radius) - 1e-8)+ return BrepPlanarPathFeature.Failure("floor", $"{g.Name}: leave positive material at both axial ends and beneath the groove.");+ }+ var sorted = grooves.OrderBy(g => g.Station).ToArray();+ for (var i = 1; i < sorted.Length; i++)+ if (sorted[i].Station - sorted[i].Width / 2 <= sorted[i - 1].Station + sorted[i - 1].Width / 2 + 1e-8)+ return BrepPlanarPathFeature.Failure("junction-unqualified", "Groove axial envelopes overlap; intersecting inner/outer or repeated grooves require a junction plan.");++ var b = new TopologyBuilder(); var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel();+ var points = new Dictionary<VertexId, Point3D>(); var rings = new Dictionary<(double Radius, double Z), (VertexId V, EdgeId E)>();+ var faces = new List<FaceId>(); var roles = new Dictionary<string, IReadOnlyList<FaceId>>();+ int nextCurve = 0, nextSurface = 0;+ var zAxis = BrepPlanarPathFeature.Z; var xAxis = BrepPlanarPathFeature.X;+ void Curve(EdgeId edge, CurveGeometry c, ParameterInterval interval)+ { var id = new CurveGeometryId(++nextCurve); geometry.AddCurve(id, c); bindings.AddEdgeBinding(new(edge, id, interval)); }+ (VertexId V, EdgeId E) Ring(double r, double z)+ {+ if (rings.TryGetValue((r, z), out var existing)) return existing;+ var v = b.AddVertex(); points[v] = new(r, 0, z); var e = b.AddEdge(v, v);+ Curve(e, CurveGeometry.FromCircle(new(new(0, 0, z), zAxis, r, xAxis)), new(0, 2 * double.Pi));+ return rings[(r, z)] = (v, e);+ }+ LoopId Loop(params (EdgeId Edge, bool Reverse)[] uses)+ {+ var loop = b.AllocateLoopId(); var ids = uses.Select(_ => b.AllocateCoedgeId()).ToArray();+ for (var i = 0; i < ids.Length; i++) b.AddCoedge(new(ids[i], uses[i].Edge, loop, ids[(i + 1) % ids.Length], ids[(i + ids.Length - 1) % ids.Length], uses[i].Reverse));+ b.AddLoop(new Loop(loop, ids)); return loop;+ }+ FaceId Face(SurfaceGeometry support, bool aligned, params LoopId[] loops)+ {+ var f = b.AddFace(loops); faces.Add(f); var id = new SurfaceGeometryId(++nextSurface);+ geometry.AddSurface(id, support); bindings.AddFaceBinding(new(f, id, aligned));+ for (var i = 0; i < loops.Length; i++) bindings.AddFaceBoundaryRoleBinding(new(f, loops[i], i == 0 ? FaceBoundaryRole.Outer : FaceBoundaryRole.Inner));+ return f;+ }+ FaceId Band(double ra, double za, double rb, double zb, bool inner, CircumferentialGroove? round = null)+ {+ var a = Ring(ra, za); var c = Ring(rb, zb);+ if (za == zb)+ {+ var normal = BrepPlanarPathFeature.D(new(0, 0, rb < ra ? 1 : -1));+ var outer = ra > rb ? Loop((a.E, false)) : Loop((c.E, true));+ var innerLoop = ra > rb ? Loop((c.E, true)) : Loop((a.E, false));+ return Face(SurfaceGeometry.FromPlane(new(new(0, 0, za), normal, xAxis)), true, outer, innerLoop);+ }+ var seam = b.AddEdge(a.V, c.V);+ SurfaceGeometry support; bool aligned;+ if (round is not null)+ {+ var circle = new Circle3Curve(new(ra, 0, round.Station), BrepPlanarPathFeature.D(new(0, 1, 0)), round.Depth,+ BrepPlanarPathFeature.D(new(0, 0, inner ? 1 : -1)));+ Curve(seam, CurveGeometry.FromCircle(circle), new(0, double.Pi));+ support = SurfaceGeometry.FromTorus(new(new(0, 0, round.Station), zAxis, ra, round.Depth, xAxis)); aligned = false;+ }+ else+ {+ var delta = points[c.V] - points[a.V];+ Curve(seam, CurveGeometry.FromLine(new(points[a.V], BrepPlanarPathFeature.D(delta))), new(0, delta.Length));+ if (double.Abs(ra - rb) < 1e-12)+ { support = SurfaceGeometry.FromCylinder(new(new(0, 0, za), zAxis, ra, xAxis)); aligned = !inner; }+ else+ {+ var normal = BrepPlanarPathFeature.D(new(0, 0, rb < ra ? 1 : -1));+ support = SurfaceGeometry.FromPlane(new(new(0, 0, za), normal, xAxis)); aligned = true;+ }+ }+ return Face(support, aligned, Loop((a.E, false), (seam, false), (c.E, true), (seam, true)));+ }+ void Wall(double r, double from, double to, bool inner)+ {+ var position = from;+ foreach (var g in grooves.Where(g => g.Inner == inner).OrderBy(g => inner ? -g.Station : g.Station))+ {+ var start = g.Station + (inner ? 1 : -1) * g.Width / 2;+ var end = g.Station - (inner ? 1 : -1) * g.Width / 2;+ Band(r, position, r, start, inner);+ var ids = new List<FaceId>();+ if (g.Section == PathSectionKind.Semicircular) ids.Add(Band(r, start, r, end, inner, g));+ else+ {+ var reduced = r + (inner ? g.Depth : -g.Depth);+ ids.Add(Band(r, start, reduced, start, inner));+ ids.Add(Band(reduced, start, reduced, end, inner));+ ids.Add(Band(reduced, end, r, end, inner));+ }+ roles[g.Name] = ids; position = end;+ }+ Band(r, position, r, to, inner);+ }+ Wall(radius, bottom, top, false);+ Face(SurfaceGeometry.FromPlane(new(new(0, 0, bottom), BrepPlanarPathFeature.D(new(0, 0, -1)), xAxis)), true, Loop((Ring(radius, bottom).E, true)));+ if (wallThickness is null)+ Face(SurfaceGeometry.FromPlane(new(new(0, 0, top), zAxis, xAxis)), true, Loop((Ring(radius, top).E, false)));+ else+ {+ Wall(innerRadius, top, floor, true);+ Face(SurfaceGeometry.FromPlane(new(new(0, 0, top), zAxis, xAxis)), true, Loop((Ring(radius, top).E, false)), Loop((Ring(innerRadius, top).E, true)));+ Face(SurfaceGeometry.FromPlane(new(new(0, 0, floor), zAxis, xAxis)), true, Loop((Ring(innerRadius, floor).E, false)));+ }+ b.AddBody([b.AddShell(faces)]);+ var body = new BrepBody(b.Model, geometry, bindings, points);+ body.PcurveRecoveryReport = BrepPcurveRecovery.Populate(body.Topology, geometry, bindings);+ var validation = BrepBindingValidator.Validate(body, requireAllEdgeAndFaceBindings: true);+ if (!validation.IsSuccess) return KernelResult<PathFeatureBody>.Failure(validation.Diagnostics);+ var preflight = BrepExportPreflight.Validate(body);+ if (!preflight.IsValid) return BrepPlanarPathFeature.Failure("boundary", string.Join("; ", preflight.Diagnostics.Where(d => d.Severity == BrepExportPreflightSeverity.Error).Select(d => d.Message)));+ var removed = grooves.Sum(g => g.Section == PathSectionKind.Rectangular+ ? 2 * double.Pi * g.Width * ((g.Inner ? innerRadius : radius) * g.Depth + (g.Inner ? 1 : -1) * g.Depth * g.Depth / 2)+ : double.Pi * double.Pi * (g.Inner ? innerRadius : radius) * g.Depth * g.Depth + (g.Inner ? 1 : -1) * 4 * double.Pi * double.Pow(g.Depth, 3) / 3);+ return KernelResult<PathFeatureBody>.Success(new(body, roles, -removed));+ }+}diff --git a/Aetheris.Kernel.Core/Brep/Features/BrepPlanarPathFeature.cs b/Aetheris.Kernel.Core/Brep/Features/BrepPlanarPathFeature.csnew file mode 100644index 00000000..32ce6863--- /dev/null+++ b/Aetheris.Kernel.Core/Brep/Features/BrepPlanarPathFeature.cs@@ -0,0 +1,312 @@+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Core.Brep.Features;++public enum PathSectionKind { Rectangular, Semicircular }+public enum PlanarGuideKind { Line, Arc, Circle }+public sealed record PlanarFeatureGuide(PlanarGuideKind Kind, ProfilePoint2D Start, ProfilePoint2D End,+ ProfilePoint2D Center, double Radius = 0, double StartAngle = 0, double Sweep = 0);+public sealed record PlanarPathFeature(string Name, bool Add, PathSectionKind Section, PlanarFeatureGuide Guide,+ double Width, double Extent, double DraftDegrees = 0, bool RoundEnds = false);+public sealed record PathFeatureBody(BrepBody Body, IReadOnlyDictionary<string, IReadOnlyList<FaceId>> Faces,+ double MaterialVolumeDelta);++/// <summary>Analytic local bands on a Box top. Footprints are integrated into the+/// support face, not emitted as intersecting tool solids. Disjoint bounds are a+/// conservative admission proof; crossing or adjoining features require a junction plan.</summary>+public static class BrepPlanarPathFeature+{+ public static KernelResult<PathFeatureBody> BuildBox(double x, double y, double z, IReadOnlyList<PlanarPathFeature> features)+ {+ if (!double.IsFinite(x + y + z) || x <= 0 || y <= 0 || z <= 0) return Failure("dimensions", "Box dimensions must be finite and positive.");+ var source = BrepPrimitives.CreateBox(x, y, z);+ if (!source.IsSuccess) return KernelResult<PathFeatureBody>.Failure(source.Diagnostics);+ var p = new AnalyticPatchBuilder(source.Value);+ var support = source.Value.Topology.Faces.Single(f => source.Value.Geometry.GetSurface(source.Value.Bindings.GetFaceBinding(f.Id).SurfaceGeometryId).Plane is { } plane+ && plane.Normal.Z > .9);+ var supportLoops = support.LoopIds.ToList();+ var footprints = new List<(double MinX, double MinY, double MaxX, double MaxY)>();+ var faces = new Dictionary<string, IReadOnlyList<FaceId>>(StringComparer.Ordinal);+ double volume = 0;+ foreach (var f in features)+ {+ if (!double.IsFinite(f.Width + f.Extent + f.DraftDegrees) || f.Width <= 0 || f.Extent <= 0 || f.DraftDegrees < 0 || f.DraftDegrees >= 89)+ return Failure("dimensions", $"{f.Name}: width/height/depth must be positive; draft must be in [0deg,89deg).");+ if (!Enum.IsDefined(f.Guide.Kind) || !Enum.IsDefined(f.Section)+ || !double.IsFinite(f.Guide.Start.X + f.Guide.Start.Y + f.Guide.End.X + f.Guide.End.Y + f.Guide.Center.X + f.Guide.Center.Y))+ return Failure("guide", $"{f.Name}: guide kind and coordinates must be finite and admitted.");+ if (faces.ContainsKey(f.Name)) return Failure("duplicate", $"Duplicate path feature '{f.Name}'.");+ if (f.Section == PathSectionKind.Semicircular && (f.Add || double.Abs(f.Extent - f.Width / 2) > 1e-9 || f.DraftDegrees != 0))+ return Failure("section", $"{f.Name}: semicircular removal requires depth = radius = width/2 and no draft.");+ if (!f.Add && (f.Extent >= z - 1e-8 || f.DraftDegrees != 0)) return Failure("floor", $"{f.Name}: groove must leave a positive floor; groove draft is unsupported.");+ if (f.Guide.Kind != PlanarGuideKind.Line && (f.Guide.Radius <= f.Width / 2 + 1e-8+ || !double.IsFinite(f.Guide.Radius + f.Guide.StartAngle + f.Guide.Sweep)))+ return Failure("offset-collapse", $"{f.Name}: guide radius must exceed half the section width.");+ if (f.Guide.Kind == PlanarGuideKind.Arc && (f.RoundEnds || f.Guide.Sweep <= 0 || f.Guide.Sweep > double.Pi))+ return Failure("arc", $"{f.Name}: open arcs currently require Flat ends and a positive sweep no greater than 180deg.");+ if (f.Guide.Kind == PlanarGuideKind.Circle && f.RoundEnds) return Failure("ends", $"{f.Name}: closed guides have no end caps.");+ var widthTop = f.Width - 2 * f.Extent * double.Tan(f.DraftDegrees * double.Pi / 180);+ if (widthTop <= 1e-8) return Failure("draft-collapse", $"{f.Name}: draft collapses the rib top; reduce draft/height or increase thickness.");+ var baseOutline = Outline(f.Guide, f.Width / 2, f.RoundEnds);+ if (baseOutline is null) return Failure("guide", $"{f.Name}: line guide must have nonzero finite length.");+ var bounds = Bounds(baseOutline);+ if (bounds.MinX <= -x / 2 + 1e-8 || bounds.MaxX >= x / 2 - 1e-8 || bounds.MinY <= -y / 2 + 1e-8 || bounds.MaxY >= y / 2 - 1e-8)+ return Failure("support", $"{f.Name}: complete footprint must remain strictly inside the Box top.");+ if (footprints.Any(b => bounds.MinX <= b.MaxX + 1e-8 && bounds.MaxX >= b.MinX - 1e-8 && bounds.MinY <= b.MaxY + 1e-8 && bounds.MaxY >= b.MinY - 1e-8))+ return Failure("junction-unqualified", $"{f.Name}: feature bounds overlap another path feature. Crossing, touching and nested footprint arrangements require a qualified junction plan.");+ footprints.Add(bounds);+ var firstFace = p.AddedFaces.Count;+ var baseEdges = baseOutline.Select(loop => p.Edges(loop, z / 2)).ToArray();+ supportLoops.Add(p.Loop(baseEdges[0].Select(e => (e, true)).Reverse().ToArray()));+ if (baseEdges.Length == 2) p.Face([p.Loop(baseEdges[1].Select(e => (e, true)).Reverse().ToArray())],+ SurfaceGeometry.FromPlane(new(new(f.Guide.Center.X, f.Guide.Center.Y, z / 2), Z, X)), true, f.Name + ".SupportIsland");+ var level = z / 2 + (f.Add ? f.Extent : -f.Extent);+ if (f.Section == PathSectionKind.Rectangular)+ {+ var topOutline = Outline(f.Guide, widthTop / 2, f.RoundEnds)!;+ var topEdges = topOutline.Select(loop => p.Edges(loop, level)).ToArray();+ for (var loop = 0; loop < baseOutline.Count; loop++)+ {+ var connectors = baseOutline[loop].Select((edge, i) => p.Line(p.Start(baseEdges[loop][i]), p.Start(topEdges[loop][i]))).ToArray();+ for (var i = 0; i < baseOutline[loop].Count; i++)+ {+ var j = (i + 1) % baseOutline[loop].Count;+ var edge = baseOutline[loop][i]; var top = topOutline[loop][i];+ SurfaceGeometry surface; bool aligned = true;+ if (edge.Radius == 0)+ {+ var a = p.Point(p.Start(baseEdges[loop][i])); var b = p.Point(p.End(baseEdges[loop][i]));+ var c = p.Point(p.End(connectors[i]));+ surface = SurfaceGeometry.FromPlane(new(a, D((b - a).Cross(c - a)), D(b - a)));+ }+ else+ {+ var center = new Point3D(edge.Cx, edge.Cy, z / 2);+ var slope = (top.Radius - edge.Radius) / (level - z / 2);+ surface = double.Abs(slope) < 1e-12+ ? SurfaceGeometry.FromCylinder(new(center, Z, edge.Radius, X))+ : SurfaceGeometry.FromCone(new(center + new Vector3D(0, 0, -edge.Radius / slope), slope > 0 ? Z : D(new(0, 0, -1)), double.Atan(double.Abs(slope)), X));+ aligned = (edge.Sweep > 0) == f.Add;+ }+ p.Face([p.Loop([(baseEdges[loop][i], false), (connectors[j], false), (topEdges[loop][i], true), (connectors[i], true)])], surface, aligned, f.Name + ".Side" + loop + "_" + i);+ }+ }+ p.Face(topEdges.Select(edges => p.Loop(edges.Select(e => (e, false)).ToArray())).ToArray(),+ SurfaceGeometry.FromPlane(new(new(0, 0, level), Z, X)), true, f.Name + (f.Add ? ".Top" : ".Floor"));+ var length = Length(f.Guide);+ volume += (f.Add ? 1 : -1) * f.Extent * (length * (f.Width + widthTop) / 2+ + (f.RoundEnds ? double.Pi * (f.Width * f.Width + f.Width * widthTop + widthTop * widthTop) / 12 : 0));+ }+ else+ {+ BuildSemicircle(p, f, baseEdges, z / 2);+ volume -= Length(f.Guide) * double.Pi * f.Width * f.Width / 8+ + (f.RoundEnds ? 2 * double.Pi * double.Pow(f.Width / 2, 3) / 3 : 0);+ }+ faces.Add(f.Name, p.AddedFaces.Skip(firstFace).ToArray());+ }+ p.ReplaceFace(support with { LoopIds = supportLoops });+ var body = p.Build();+ body.PcurveRecoveryReport = BrepPcurveRecovery.Populate(body.Topology, body.Geometry, body.Bindings);+ var binding = BrepBindingValidator.Validate(body, requireAllEdgeAndFaceBindings: true);+ if (!binding.IsSuccess) return KernelResult<PathFeatureBody>.Failure(binding.Diagnostics);+ var preflight = BrepExportPreflight.Validate(body);+ if (!preflight.IsValid) return Failure("boundary", string.Join("; ", preflight.Diagnostics.Where(d => d.Severity == BrepExportPreflightSeverity.Error).Select(d => d.Code + ": " + d.Message)));+ return KernelResult<PathFeatureBody>.Success(new(body, faces, volume));+ }++ private static void BuildSemicircle(AnalyticPatchBuilder p, PlanarPathFeature f, EdgeId[][] baseEdges, double z)+ {+ var g = f.Guide; var r = f.Width / 2;+ if (g.Kind == PlanarGuideKind.Circle)+ {+ var outer = baseEdges[0][0]; var inner = baseEdges[1][0];+ var seam = p.Circle(new(g.Center.X + g.Radius, g.Center.Y, z), D(new(0, 1, 0)), r, X, 0, double.Pi);+ p.Face([p.Loop([(outer, false), (seam, false), (inner, false), (seam, true)])],+ SurfaceGeometry.FromTorus(new(new(g.Center.X, g.Center.Y, z), Z, g.Radius, r, X)), false, f.Name + ".Bottom");+ return;+ }+ var outline = baseEdges[0];+ var a = p.Point(p.Start(outline[0])); var b = p.Point(p.End(outline[0]));+ var c = p.Point(p.Start(outline[2])); var d = p.Point(p.End(outline[2]));+ var startCenter = Mid(a, b); var endCenter = Mid(c, d);+ // Round end boundaries have their endpoints on the same diameter.+ var across = D(b - a); var tangent = D(endCenter - startCenter);+ EdgeId startArc, endArc;+ var startTangent = tangent; var endTangent = tangent;+ SurfaceGeometry bottom;+ if (g.Kind == PlanarGuideKind.Line)+ {+ startArc = p.Circle(startCenter, D(-tangent.ToVector()), r, D(a - startCenter), 0, double.Pi);+ endArc = p.Circle(endCenter, D(-tangent.ToVector()), r, D(d - endCenter), 0, double.Pi);+ bottom = SurfaceGeometry.FromCylinder(new(startCenter, tangent, r, D(a - startCenter)));+ }+ else+ {+ var radialA = D(new(double.Cos(g.StartAngle), double.Sin(g.StartAngle), 0));+ var radialB = D(new(double.Cos(g.StartAngle + g.Sweep), double.Sin(g.StartAngle + g.Sweep), 0));+ var ta = D(Z.ToVector().Cross(radialA.ToVector())); var tb = D(Z.ToVector().Cross(radialB.ToVector()));+ startTangent = ta; endTangent = tb;+ startArc = p.Circle(startCenter, D(-ta.ToVector()), r, D(a - startCenter), 0, double.Pi);+ endArc = p.Circle(endCenter, D(-tb.ToVector()), r, D(d - endCenter), 0, double.Pi);+ bottom = SurfaceGeometry.FromTorus(new(new(g.Center.X, g.Center.Y, z), Z, g.Radius, r, X));+ }+ p.Face([p.Loop([(outline[1], false), (endArc, true), (outline[3], false), (startArc, false)])], bottom, false, f.Name + ".Bottom");+ var startSurface = f.RoundEnds ? SurfaceGeometry.FromSphere(new(startCenter, Z, r, X))+ : SurfaceGeometry.FromPlane(new(startCenter, startTangent, across));+ var endSurface = f.RoundEnds ? SurfaceGeometry.FromSphere(new(endCenter, Z, r, X))+ : SurfaceGeometry.FromPlane(new(endCenter, D(-endTangent.ToVector()), D(c - endCenter)));+ p.Face([p.Loop([(outline[0], false), (startArc, true)])], startSurface, !f.RoundEnds, f.Name + ".Start");+ p.Face([p.Loop([(outline[2], false), (endArc, false)])], endSurface, !f.RoundEnds, f.Name + ".End");+ }++ private static Point3D Mid(Point3D a, Point3D b) => a + (b - a) * .5;+ internal static Direction3D D(Vector3D v) => Direction3D.Create(v);+ internal static readonly Direction3D Z = D(new(0, 0, 1)), X = D(new(1, 0, 0));+ internal static KernelResult<PathFeatureBody> Failure(string code, string message) => KernelResult<PathFeatureBody>.Failure([+ new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, "path-feature-" + code + ": " + message, "Brep.PathFeature")]);+ private static double Length(PlanarFeatureGuide g) => g.Kind == PlanarGuideKind.Line+ ? double.Sqrt(double.Pow(g.End.X - g.Start.X, 2) + double.Pow(g.End.Y - g.Start.Y, 2)) : g.Radius * (g.Kind == PlanarGuideKind.Circle ? 2 * double.Pi : g.Sweep);++ // CCW outer footprint, optional clockwise inner footprint. Offsets are exact;+ // no sampling is used to decide topology or intersections.+ private static List<List<BandEdge>>? Outline(PlanarFeatureGuide g, double half, bool round)+ {+ if (g.Kind == PlanarGuideKind.Line)+ {+ var l = Length(g); if (!double.IsFinite(l) || l <= 1e-8) return null;+ var dx = (g.End.X - g.Start.X) / l; var dy = (g.End.Y - g.Start.Y) / l;+ var a = new ProfilePoint2D(g.Start.X - dy * half, g.Start.Y + dx * half);+ var b = new ProfilePoint2D(g.Start.X + dy * half, g.Start.Y - dx * half);+ var c = new ProfilePoint2D(g.End.X + dy * half, g.End.Y - dx * half);+ var d = new ProfilePoint2D(g.End.X - dy * half, g.End.Y + dx * half);+ return [[round ? BandEdge.Arc(g.Start.X, g.Start.Y, half, double.Atan2(dx, -dy), double.Pi) : new(a, b), new(b, c),+ round ? BandEdge.Arc(g.End.X, g.End.Y, half, double.Atan2(-dx, dy), double.Pi) : new(c, d), new(d, a)]];+ }+ if (g.Kind == PlanarGuideKind.Circle)+ return [[BandEdge.Arc(g.Center.X, g.Center.Y, g.Radius + half, 0, 2 * double.Pi)], [BandEdge.Arc(g.Center.X, g.Center.Y, g.Radius - half, 0, -2 * double.Pi)]];+ var outer = BandEdge.Arc(g.Center.X, g.Center.Y, g.Radius + half, g.StartAngle, g.Sweep);+ var inner = BandEdge.Arc(g.Center.X, g.Center.Y, g.Radius - half, g.StartAngle + g.Sweep, -g.Sweep);+ return [[new(inner.End, outer.Start), outer, new(outer.End, inner.Start), inner]];+ }+ private static (double MinX, double MinY, double MaxX, double MaxY) Bounds(List<List<BandEdge>> outline)+ {+ var points = outline.SelectMany(l => l).SelectMany(e => e.Extrema()).ToArray();+ return (points.Min(p => p.X), points.Min(p => p.Y), points.Max(p => p.X), points.Max(p => p.Y));+ }+ internal sealed record BandEdge(ProfilePoint2D Start, ProfilePoint2D End, double Cx = 0, double Cy = 0, double Radius = 0, double Angle = 0, double Sweep = 0)+ {+ internal static BandEdge Arc(double x, double y, double r, double a, double s)+ {+ a = double.Ieee754Remainder(a, 2 * double.Pi);+ return new(new(x + r * double.Cos(a), y + r * double.Sin(a)), new(x + r * double.Cos(a + s), y + r * double.Sin(a + s)), x, y, r, a, s);+ }+ internal IEnumerable<ProfilePoint2D> Extrema()+ {+ yield return Start; yield return End;+ if (Radius > 0)+ {+ var lo = double.Min(Angle, Angle + Sweep); var hi = double.Max(Angle, Angle + Sweep);+ for (var i = double.Ceiling(lo / (double.Pi / 2)); i <= double.Floor(hi / (double.Pi / 2)); i++)+ { var angle = i * double.Pi / 2; yield return new(Cx + Radius * double.Cos(angle), Cy + Radius * double.Sin(angle)); }+ }+ }+ }+}++/// <summary>Local analytic patch assembly preserving untouched source IDs.+/// Shared vertices/edges are reused; caps replace support regions.</summary>+internal sealed class AnalyticPatchBuilder+{+ private readonly BrepBody source;+ private readonly TopologyModel additions = new();+ private readonly BrepGeometryStore geometry;+ private readonly BrepBindingModel bindings;+ private readonly Dictionary<VertexId, Point3D> points;+ private readonly Dictionary<FaceId, Face> replacements = [];+ private int vertex, edge, coedge, loop, face, curve, surface;+ internal List<FaceId> AddedFaces { get; } = [];+ internal Dictionary<string, List<FaceId>> Roles { get; } = [];+ internal AnalyticPatchBuilder(BrepBody source)+ {+ this.source = source; geometry = source.Geometry.Clone(); bindings = source.Bindings.Clone();+ points = source.Topology.Vertices.Where(v => source.TryGetVertexPoint(v.Id, out _))+ .ToDictionary(v => v.Id, v => { source.TryGetVertexPoint(v.Id, out var p); return p; });+ foreach (var e in source.Topology.Edges)+ {+ var binding = source.Bindings.GetEdgeBinding(e.Id);+ var c = source.Geometry.GetCurve(binding.CurveGeometryId); var trim = binding.TrimInterval!.Value;+ points.TryAdd(e.StartVertexId, BrepPcurveValidator.Evaluate(c, binding.OrientedEdgeSense ? trim.Start : trim.End)!.Value);+ points.TryAdd(e.EndVertexId, BrepPcurveValidator.Evaluate(c, binding.OrientedEdgeSense ? trim.End : trim.Start)!.Value);+ }+ vertex = source.Topology.Vertices.Max(v => v.Id.Value); edge = source.Topology.Edges.Max(e => e.Id.Value);+ coedge = source.Topology.Coedges.Max(c => c.Id.Value); loop = source.Topology.Loops.Max(l => l.Id.Value); face = source.Topology.Faces.Max(f => f.Id.Value);+ curve = geometry.Curves.Max(c => c.Key.Value); surface = geometry.Surfaces.Max(s => s.Key.Value);+ }+ internal Point3D Point(VertexId id) => points[id];+ internal VertexId Start(EdgeId id) => additions.GetEdge(id).StartVertexId;+ internal VertexId End(EdgeId id) => additions.GetEdge(id).EndVertexId;+ private VertexId Vertex(Point3D p)+ {+ foreach (var item in points) if ((item.Value - p).Length < 1e-9) return item.Key;+ var id = new VertexId(++vertex); additions.AddVertex(new(id)); points[id] = p; return id;+ }+ internal EdgeId Line(VertexId a, VertexId b)+ {+ var delta = Point(b) - Point(a);+ return Edge(a, b, CurveGeometry.FromLine(new(Point(a), BrepPlanarPathFeature.D(delta))), new(0, delta.Length));+ }+ internal EdgeId Circle(Point3D center, Direction3D normal, double radius, Direction3D reference, double from, double sweep)+ {+ var c = new Circle3Curve(center, normal, radius, reference);+ var positive = sweep > 0;+ var lo = positive ? from : from + sweep; var hi = positive ? from + sweep : from;+ return Edge(Vertex(c.Evaluate(from)), Vertex(c.Evaluate(from + sweep)), CurveGeometry.FromCircle(c), new(lo, hi), positive);+ }+ private EdgeId Edge(VertexId a, VertexId b, CurveGeometry c, ParameterInterval trim, bool sense = true)+ {+ var id = new EdgeId(++edge); additions.AddEdge(new(id, a, b));+ var cid = new CurveGeometryId(++curve); geometry.AddCurve(cid, c); bindings.AddEdgeBinding(new(id, cid, trim, sense)); return id;+ }+ internal EdgeId[] Edges(List<BrepPlanarPathFeature.BandEdge> outline, double z) => outline.Select(e => e.Radius == 0+ ? Line(Vertex(new(e.Start.X, e.Start.Y, z)), Vertex(new(e.End.X, e.End.Y, z)))+ : Circle(new(e.Cx, e.Cy, z), BrepPlanarPathFeature.Z, e.Radius, BrepPlanarPathFeature.X, e.Angle, e.Sweep)).ToArray();+ internal LoopId Loop((EdgeId Edge, bool Reverse)[] uses)+ {+ var id = new LoopId(++loop); var ids = uses.Select(_ => new CoedgeId(++coedge)).ToArray();+ for (var i = 0; i < ids.Length; i++) additions.AddCoedge(new(ids[i], uses[i].Edge, id, ids[(i + 1) % ids.Length], ids[(i + ids.Length - 1) % ids.Length], uses[i].Reverse));+ additions.AddLoop(new(id, ids)); return id;+ }+ internal FaceId Face(LoopId[] loops, SurfaceGeometry support, bool aligned, string role)+ {+ var id = new FaceId(++face); var sid = new SurfaceGeometryId(++surface);+ geometry.AddSurface(sid, support); additions.AddFace(new(id, loops)); bindings.AddFaceBinding(new(id, sid, aligned)); AddedFaces.Add(id);+ for (var i = 0; i < loops.Length; i++) bindings.AddFaceBoundaryRoleBinding(new(id, loops[i], i == 0 ? FaceBoundaryRole.Outer : FaceBoundaryRole.Inner));+ if (!Roles.TryGetValue(role, out var list)) Roles[role] = list = []; list.Add(id); return id;+ }+ internal void ReplaceFace(Face f)+ {+ replacements[f.Id] = f;+ for (var i = 0; i < f.LoopIds.Count; i++)+ if (!bindings.TryGetFaceBoundaryRoleBinding(f.LoopIds[i], out _)) bindings.AddFaceBoundaryRoleBinding(new(f.Id, f.LoopIds[i], i == 0 ? FaceBoundaryRole.Outer : FaceBoundaryRole.Inner));+ }+ internal BrepBody Build()+ {+ var topology = new TopologyModel();+ foreach (var v in source.Topology.Vertices.Concat(additions.Vertices)) topology.AddVertex(v);+ foreach (var e in source.Topology.Edges.Concat(additions.Edges)) topology.AddEdge(e);+ foreach (var c in source.Topology.Coedges.Concat(additions.Coedges)) topology.AddCoedge(c);+ foreach (var l in source.Topology.Loops.Concat(additions.Loops)) topology.AddLoop(l);+ foreach (var f in source.Topology.Faces) topology.AddFace(replacements.GetValueOrDefault(f.Id, f));+ foreach (var f in additions.Faces) topology.AddFace(f);+ foreach (var s in source.Topology.Shells) topology.AddShell(s with { FaceIds = s.FaceIds.Concat(AddedFaces).ToArray() });+ foreach (var b in source.Topology.Bodies) topology.AddBody(b);+ return new(topology, geometry, bindings, points);+ }+}diff --git a/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs b/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.csindex dad9c5fe..9fe00236 100644--- a/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs+++ b/Aetheris.Kernel.Core/Brep/Verification/BrepMassProperties.cs@@ -526,6 +526,9 @@ public static class BrepMassProperties}var cylinder = cylinders[0];+ var cylinderFace = faces.Single(face => body.TryGetFaceSurfaceGeometry(face.Id, out var support) && support?.Cylinder is not null);+ if (!body.Bindings.GetFaceBinding(cylinderFace.Id).Orientation.IsAlignedWithSurface)+ return false; // Concave channels are not convex stock-corner fillets.var axis = cylinder.Axis.ToVector();var axisIsX = System.Math.Abs(System.Math.Abs(axis.X) - 1d) <= 1e-8 && System.Math.Abs(axis.Y) <= 1e-8 && System.Math.Abs(axis.Z) <= 1e-8;var axisIsY = System.Math.Abs(System.Math.Abs(axis.Y) - 1d) <= 1e-8 && System.Math.Abs(axis.X) <= 1e-8 && System.Math.Abs(axis.Z) <= 1e-8;@@ -534,6 +537,19 @@ public static class BrepMassPropertiesreturn false;}+ var crossCoordinate = axisIsX ? cylinder.Origin.Y : cylinder.Origin.X;+ var crossMinimum = axisIsX ? minY : minX; var crossMaximum = axisIsX ? maxY : maxX;+ if (!(Near(crossCoordinate, crossMinimum + cylinder.Radius) || Near(crossCoordinate, crossMaximum - cylinder.Radius))+ || !(Near(cylinder.Origin.Z, minZ + cylinder.Radius) || Near(cylinder.Origin.Z, maxZ - cylinder.Radius)))+ return false;+ bool Near(double a, double b) => System.Math.Abs(a - b) <= tolerance;++ var circularTrims = body.Bindings.EdgeBindings.Where(binding =>+ body.Geometry.GetCurve(binding.CurveGeometryId).Kind == CurveGeometryKind.Circle3).ToArray();+ if (circularTrims.Length != 2 || circularTrims.Any(binding => binding.TrimInterval is not { } trim+ || System.Math.Abs(trim.End - trim.Start - System.Math.PI / 2) > 1e-8))+ return false;+var endpointCircles = body.Bindings.EdgeBindings.Select(binding => body.Geometry.TryGetCurve(binding.CurveGeometryId, out var curve) ? curve : null).Where(curve => curve?.Kind == CurveGeometryKind.Circle3 && curve.Circle3.HasValue)diff --git a/Aetheris.Kernel.Core/Geometry/Curves/BSpline3Curve.cs b/Aetheris.Kernel.Core/Geometry/Curves/BSpline3Curve.csindex fe2e2906..c093fed2 100644--- a/Aetheris.Kernel.Core/Geometry/Curves/BSpline3Curve.cs+++ b/Aetheris.Kernel.Core/Geometry/Curves/BSpline3Curve.cs@@ -94,11 +94,10 @@ public readonly record struct BSpline3Curvevar p = Degree;var u = ClampToDomain(parameter);- if (double.Abs(u - DomainEnd) <= 1e-12d)- {+ // At a non-clamped/periodic domain end the limit is a basis-weighted+ // point, not the last control point. FindSpan already handles that end.+ if (KnotMultiplicities[^1] >= Degree + 1 && double.Abs(u - DomainEnd) <= 1e-12d)return ControlPoints[^1];- }-var span = FindSpan(u);var d = new Point3D[p + 1];for (var j = 0; j <= p; j++)@@ -177,7 +176,7 @@ public readonly record struct BSpline3Curvevar span = FindSpan(derivativePoints.Length, derivativeDegree, knots, u);return derivativePoints[span];}- if (double.Abs(u - DomainEnd) <= 1e-12d) return derivativePoints[^1];+ if (KnotMultiplicities[^1] >= Degree + 1 && double.Abs(u - DomainEnd) <= 1e-12d) return derivativePoints[^1];var derivativeSpan = FindSpan(derivativePoints.Length, derivativeDegree, knots, u);var d = new Vector3D[derivativeDegree + 1];for (var j = 0; j <= derivativeDegree; j++) d[j] = derivativePoints[derivativeSpan - derivativeDegree + j];@@ -218,7 +217,7 @@ public readonly record struct BSpline3Curveprivate Vector3D EvaluateVectorSpline(IReadOnlyList<Vector3D> controls,int degree,IReadOnlyList<double> knots,double u){if(degree==0)return controls[FindSpan(controls.Count,degree,knots,u)];- if(double.Abs(u-DomainEnd)<=1e-12)return controls[^1];+ if(KnotMultiplicities[^1]>=Degree+1 && double.Abs(u-DomainEnd)<=1e-12)return controls[^1];var span=FindSpan(controls.Count,degree,knots,u);var d=new Vector3D[degree+1];for(var j=0;j<=degree;j++)d[j]=controls[span-degree+j];for(var r=1;r<=degree;r++)for(var j=degree;j>=r;j--){var left=knots[span-degree+j];var right=knots[span+1+j-r];var denominator=right-left;var alpha=double.Abs(denominator)<=1e-15?0d:(u-left)/denominator;d[j]=d[j-1]+(d[j]-d[j-1])*alpha;}diff --git a/Aetheris.Kernel.Core/Import/BrepImportQualification.cs b/Aetheris.Kernel.Core/Import/BrepImportQualification.csindex 8e10b24b..319db2bc 100644--- a/Aetheris.Kernel.Core/Import/BrepImportQualification.cs+++ b/Aetheris.Kernel.Core/Import/BrepImportQualification.cs@@ -28,6 +28,8 @@ public sealed record BrepImportQualificationReport({public ImportDisplayStatus DisplayStatus { get; init; } = ImportDisplayStatus.NotAssessed;public IReadOnlyList<ImportQualificationReason> DisplayReasons { get; init; } = [];+ /// <summary>Disclosed deterministic source repairs, separate from qualification failures.</summary>+ public IReadOnlyList<ImportQualificationReason> Repairs { get; init; } = [];}/// <summary>Import evidence is separate from parser success and from display preparation.</summary>diff --git a/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs b/Aetheris.Kernel.Core/Step242/Step242ExportOptions.csindex 453a1695..8f5d91eb 100644--- a/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs+++ b/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs@@ -36,11 +36,18 @@ public sealed class Step242ExportOptionspublic Step242HeaderMetadata HeaderMetadata { get; init; } = Step242HeaderMetadata.Deterministic;+ private BrepExportPreflightMode? preflightMode;+/// <summary>- /// Audit is the compatibility default while legacy producers are being remediated.- /// Enforce is the fail-fast production policy once their audit corpus is clean.+ /// Production policy defaults to Enforce. Legacy interchange defaults to Audit;+ /// an explicit override is available for diagnostic callers./// </summary>- public BrepExportPreflightMode BrepExportPreflightMode { get; init; } = BrepExportPreflightMode.Audit;+ public BrepExportPreflightMode BrepExportPreflightMode+ {+ get => preflightMode ?? (BrepExportPreflightPolicy == BrepExportPreflightPolicy.TrustedProductionRoute+ ? BrepExportPreflightMode.Enforce : BrepExportPreflightMode.Audit);+ init => preflightMode = value;+ }/// <summary>/// TrustedProductionRoute rejects rational B-spline supports and pcurves in@@ -67,11 +74,16 @@ public sealed class Step242ExportOptionspublic static Step242ExportOptions FromSourceMetadata(Step242SourceMetadata metadata,BrepExportPreflightPolicy preflightPolicy = BrepExportPreflightPolicy.LegacyRoute)+ => FromSourceMetadata(metadata, preflightPolicy, null);++ public static Step242ExportOptions FromSourceMetadata(Step242SourceMetadata metadata,+ BrepExportPreflightPolicy preflightPolicy, Step242PmiTransfer? importedPmi){static string Coalesce(string? value, string fallback) => string.IsNullOrWhiteSpace(value) ? fallback : value!;return new Step242ExportOptions{+ ImportedPmi = importedPmi,BrepExportPreflightPolicy = preflightPolicy,ImportedRecoveryToleranceMillimetres = preflightPolicy == BrepExportPreflightPolicy.TrustedProductionRoute ? .1d : null,ProductName = Coalesce(metadata.ProductName, "AetherisBody"),diff --git a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs b/Aetheris.Kernel.Core/Step242/Step242Exporter.csindex 9a337b62..ba0a7f39 100644--- a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs@@ -32,6 +32,11 @@ public static class Step242Exporterreturn Failure($"pmi-geometric-target-unresolved: '{control.Name}' requires proved face associations.", "Step242.Pmi");}IReadOnlyList<KernelDiagnostic> normalizationDiagnostics = [];+ if (options.BrepExportPreflightPolicy == BrepExportPreflightPolicy.TrustedProductionRoute)+ {+ var bindings = BrepBindingValidator.Validate(body);+ if (!bindings.IsSuccess) return KernelResult<string>.Failure(bindings.Diagnostics);+ }if (options.BrepExportPreflightPolicy == BrepExportPreflightPolicy.TrustedProductionRoute&& options.ImportedRecoveryToleranceMillimetres is { } normalizationBudget&& (body.Geometry.Surfaces.Any(s => s.Value.BSplineSurfaceWithKnots?.IsRational == true)@@ -116,7 +121,14 @@ public static class Step242Exporter// Pure exact planar projections are deterministically derivable from the// emitted geometry. Preserve the compact canonical legacy normal form when// no source/recovered parameter trace needs serialization.- var pcurveContextId = options.EmitQualifiedPcurves && body.Bindings.PcurveBindings.Any(binding =>+ // UV traces are optional STEP acceleration data. Never serialize a failed+ // recovered set as authority over a valid 3D boundary. Edits which require+ // those traces are admitted separately by their operation owners.+ var omitUnqualifiedPcurves = options.BrepExportPreflightPolicy == BrepExportPreflightPolicy.TrustedProductionRoute+ && (body.PcurveRecoveryReport is { IsSuccess: false }+ || body.Bindings.PcurveBindings.Any() && !BrepPcurveValidator.Validate(body,+ options.ImportedRecoveryToleranceMillimetres ?? 1e-6).IsValid);+ var pcurveContextId = options.EmitQualifiedPcurves && !omitUnqualifiedPcurves && body.Bindings.PcurveBindings.Any(binding =>binding.Qualification?.Origin != PcurveBindingOrigin.DerivedAnalytic&& (body.PcurveRecoveryReport is not { IsSuccess: false }|| binding.SourceStepPcurveEntityId is not null))@@ -189,15 +201,23 @@ public static class Step242ExporterIReadOnlyDictionary<string, string>? importedDatumEntities = null;if (options.ImportedPmi is { } importedPmi){- var transferred = importedPmi.Emit(writer, body, shapeId, shapeRepresentationId, repContextId, lengthUnitId, brepId, advancedFaceIds, edgeCurveIds, out importedDatumEntities);+ var transferred = importedPmi.Emit(writer, body, shapeId, shapeRepresentationId, repContextId, lengthUnitId, brepId, advancedFaceIds, edgeCurveIds,+ options.BrepExportPreflightPolicy == BrepExportPreflightPolicy.TrustedProductionRoute, out importedDatumEntities);if (!transferred.IsSuccess) return KernelResult<string>.Failure(transferred.Diagnostics);importedPmiDiagnostics = transferred.Diagnostics;}EmitSemanticPmi(writer, shapeId, shapeRepresentationId, repContextId, lengthUnitId, advancedFaceIds, semanticPmi, importedDatumEntities);+ var repairDiagnostics = options.BrepExportPreflightPolicy == BrepExportPreflightPolicy.TrustedProductionRoute+ ? (body.ImportQualification?.Repairs ?? []).Select(repair => new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Warning, repair.Code + ": " + repair.Message, $"Step242.Import.Entity:{repair.StepEntityId}")) : [];+ IReadOnlyList<KernelDiagnostic> trimDiagnostics = omitUnqualifiedPcurves+ ? [new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Warning,+ "step-export-recovered-pcurves-omitted: Unqualified UV traces were not emitted; STEP boundaries use their 3D curves and vertices. Source trim qualification has not been promoted.", "Step242.Export")]+ : [];return KernelResult<string>.Success(writer.Build(options.HeaderMetadata),- normalizationDiagnostics.Concat(importedPmiDiagnostics).Concat(preflight is null ? [] : ToKernelDiagnostics(preflight, errorsAsWarnings: true)).ToArray());+ normalizationDiagnostics.Concat(importedPmiDiagnostics).Concat(repairDiagnostics).Concat(trimDiagnostics).Concat(preflight is null ? [] : ToKernelDiagnostics(preflight, errorsAsWarnings: true)).ToArray());}private static void EmitAuxiliaryVertexPointForVertexlessAnalyticBody(Step242TextWriter writer, BrepBody body, TopologyModel model)diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.csindex 02784c09..34094e95 100644--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs@@ -192,6 +192,7 @@ public static class Step242Importer&& !string.Equals(brepEntity.Name, "BREP_WITH_VOIDS", StringComparison.OrdinalIgnoreCase))return Step242ImportSharedUtilities.NotImplementedFailure<BrepBody>($"Entity #{rigidRootEntityId} is not an exact rigid BRep root.", "Importer.Assembly.ProductDefinitionGeometry");var shellRoleDiagnostics = new List<KernelDiagnostic>();+ var importRepairs = new List<Aetheris.Kernel.Core.Import.ImportQualificationReason>();// Surface binding reports what it did with each spline face (recovered as a primitive, or retained); those// findings are the record of how faithfully the file was read, so they travel with the imported body.var surfaceBindingDiagnostics = new List<KernelDiagnostic>();@@ -525,6 +526,25 @@ public static class Step242Importer}}+ if (hasDisconnectedCoedgeGap && TryOrderUniqueDirectedCycle(loopCoedges, builder.Model, out var ordered))+ {+ loopCoedges = ordered;+ loopSamples.Clear(); hasDisconnectedCoedgeGap = false;+ for (var i = 0; i < loopCoedges.Count; i++)+ {+ var coedge = loopCoedges[i];+ var sample = SampleCoedgePoints(bindings.GetEdgeBinding(coedge.EdgeId), geometry, coedge.IsReversed,+ faceEntity.Id, loopId.Value, coedge.Id.Value, coedge.EdgeId.Value);+ if (!sample.IsSuccess) return KernelResult<BrepBody>.Failure(sample.Diagnostics);+ hasDisconnectedCoedgeGap |= AppendLoopSamples(loopSamples, sample.Value, bindSurfaceResult.Value.SurfaceGeometry,+ faceEntity.Id, loopId.Value, coedge.Id.Value, i > 0 ? loopCoedges[i - 1].Id.Value : null) == LoopCoedgeGapClassification.Disconnected;+ }+ var message = $"EDGE_LOOP #{loopEntityResult.Value.Id} reordered by its unique directed vertex cycle; no vertices, edges or edge senses changed.";+ importRepairs.Add(new("step-import-loop-order-recovered", message, StepEntityId: faceEntity.Id));+ shellRoleDiagnostics.Add(new(KernelDiagnosticCode.Unknown, KernelDiagnosticSeverity.Info,+ "step-import-loop-order-recovered: " + message, $"Entity:{faceEntity.Id}"));+ }+var closingGap = ClassifyCoedgeGap(loopSamples[^1], loopSamples[0], bindSurfaceResult.Value.SurfaceGeometry);ReportCoedgeGapDiagnostic(new LoopRoleCoedgeGapDiagnostic(FaceEntityId: faceEntity.Id,@@ -748,7 +768,7 @@ public static class Step242Importer}orientation.Value.ImportQualification = BrepImportQualification.Evaluate(orientation.Value, faceEntityIds.Count,- document.SourceDistanceAccuracyMillimetres, document.PcurveQualificationToleranceMillimetres, qualificationEvidence);+ document.SourceDistanceAccuracyMillimetres, document.PcurveQualificationToleranceMillimetres, qualificationEvidence) with { Repairs = importRepairs };return KernelResult<BrepBody>.Success(orientation.Value, validation.Diagnostics.Concat(shellRoleDiagnostics).Concat(surfaceBindingDiagnostics)@@ -1156,7 +1176,7 @@ public static class Step242Importer{return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((CurveGeometry.FromBSpline(splineResult.Value),- explicitTrim ?? new ParameterInterval(splineResult.Value.DomainStart, splineResult.Value.DomainEnd)));+ explicitTrim ?? InferSplineEdgeTrim(splineResult.Value, startPoint, endPoint, edgeSameSense)));}var recoveryDecision = Step242BsplineCurveRecoveryLane.Decide(curveEntity, splineResult.Value, weights);@@ -1193,7 +1213,7 @@ public static class Step242Importerreturn KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Success((CurveGeometry.FromBSpline(splineResult.Value),- explicitTrim ?? new ParameterInterval(splineResult.Value.DomainStart, splineResult.Value.DomainEnd)));+ explicitTrim ?? InferSplineEdgeTrim(splineResult.Value, startPoint, endPoint, edgeSameSense)));}if (string.Equals(curveEntity.Name, "AETHERIS_PLANAR_UNSUPPORTED_CURVE", StringComparison.OrdinalIgnoreCase))@@ -1206,6 +1226,64 @@ public static class Step242Importerreturn FailureCurveBinding($"EDGE_CURVE geometry '{curveEntity.Name}' is unsupported.", SourceFor(curveEntity.Id, "Importer.EntityFamily"));}+ private static bool TryOrderUniqueDirectedCycle(IReadOnlyList<Coedge> source, TopologyModel topology, out List<Coedge> ordered)+ {+ ordered = [];+ var outgoing = source.GroupBy(c => DirectedEdgeUse.Resolve(topology.GetEdge(c.EdgeId), c).StartVertexId).ToArray();+ if (outgoing.Any(group => group.Count() != 1)) return false;+ var byStart = outgoing.ToDictionary(group => group.Key, group => group.Single());+ var used = new HashSet<CoedgeId>(); var next = source[0];+ while (used.Add(next.Id))+ {+ ordered.Add(next);+ if (!byStart.TryGetValue(DirectedEdgeUse.Resolve(topology.GetEdge(next.EdgeId), next).EndVertexId, out next!)) return false;+ }+ if (next.Id != source[0].Id || ordered.Count != source.Count || ordered.Select(c => c.Id).SequenceEqual(source.Select(c => c.Id))) return false;+ for (var i = 0; i < ordered.Count; i++) ordered[i] = ordered[i] with {+ NextCoedgeId = ordered[(i + 1) % ordered.Count].Id, PrevCoedgeId = ordered[(i + ordered.Count - 1) % ordered.Count].Id };+ return true;+ }++ // EDGE_CURVE vertices trim a basis spline even without a TRIMMED_CURVE wrapper.+ // Accept only unique, measured endpoint inverses; unresolved cases stay importable+ // with their original interval and are rejected by enforced export preflight.+ private static ParameterInterval InferSplineEdgeTrim(BSpline3Curve curve, Point3D start, Point3D end, bool sameSense)+ {+ var domain = new ParameterInterval(curve.DomainStart, curve.DomainEnd);+ const double tolerance = 1e-6;+ if (!Find(sameSense ? start : end, domain.Start, out var a)+ || !Find(sameSense ? end : start, domain.End, out var b) || b <= a) return domain;+ return new(a, b);++ bool Find(Point3D point, double preferred, out double parameter)+ {+ parameter = preferred;+ if ((curve.Evaluate(preferred) - point).Length <= tolerance) return true;+ var candidates = new List<double>();+ double Error(double t) => (curve.Evaluate(t) - point).Length;+ foreach (var span in curve.GetNonZeroKnotSpans(domain))+ {+ const int divisions = 16;+ var samples = Enumerable.Range(0, divisions + 1).Select(i => span.Start + (span.End - span.Start) * i / divisions).ToArray();+ var errors = samples.Select(Error).ToArray();+ for (var i = 0; i <= divisions; i++)+ {+ if (i > 0 && errors[i] > errors[i - 1] || i < divisions && errors[i] > errors[i + 1]) continue;+ var lo = samples[System.Math.Max(0, i - 1)]; var hi = samples[System.Math.Min(divisions, i + 1)];+ const double ratio = .6180339887498949;+ var l = hi - (hi - lo) * ratio; var r = lo + (hi - lo) * ratio;+ for (var iteration = 0; iteration < 64; iteration++)+ if (Error(l) <= Error(r)) { hi = r; r = l; l = hi - (hi - lo) * ratio; }+ else { lo = l; l = r; r = lo + (hi - lo) * ratio; }+ var t = (lo + hi) / 2;+ if (Error(t) <= tolerance && !candidates.Any(c => double.Abs(c - t) <= (domain.End - domain.Start) * 1e-7)) candidates.Add(t);+ }+ }+ if (candidates.Count != 1) return false;+ parameter = candidates[0]; return true;+ }+ }+private static KernelResult<ParameterInterval> ReadParameterTrim(Step242Value startValue,Step242Value endValue,diff --git a/Aetheris.Kernel.Core/Step242/Step242PmiTransfer.cs b/Aetheris.Kernel.Core/Step242/Step242PmiTransfer.csindex 5f0f83bb..a59025e3 100644--- a/Aetheris.Kernel.Core/Step242/Step242PmiTransfer.cs+++ b/Aetheris.Kernel.Core/Step242/Step242PmiTransfer.cs@@ -121,7 +121,7 @@ public sealed class Step242PmiTransferinternal KernelResult<bool> Emit(Step242TextWriter writer, BrepBody body, string shape, string representation,string context, string millimetreUnit, string brep, IReadOnlyDictionary<FaceId, string> faces, IReadOnlyDictionary<EdgeId, string> edges,- out IReadOnlyDictionary<string, string> emittedDatums)+ bool requireNonRationalAuxiliaryGeometry, out IReadOnlyDictionary<string, string> emittedDatums){emittedDatums = new Dictionary<string, string>();if (!Unchanged(body)) return Failure<bool>("pmi-source-body-changed", "Imported semantic PMI requires unchanged geometry and topology. Rebind annotations explicitly after editing, or request geometryOnly before editing.");@@ -146,6 +146,9 @@ public sealed class Step242PmiTransferthrow new PmiTransferException($"Source geometry #{id} ({entity.Name}) has no proved topology correspondence.");}var copied = selected.Where(id => !mapping.ContainsKey(id)).Order().ToArray();+ if (requireNonRationalAuxiliaryGeometry && copied.FirstOrDefault(id => Has(entities[id], "RATIONAL_B_SPLINE_SURFACE")+ || Has(entities[id], "RATIONAL_B_SPLINE_CURVE")) is var rational && rational != 0)+ throw new PmiTransferException($"pmi-source-rational-geometry-not-canonical: Auxiliary annotation geometry #{rational} requires analytic or non-rational recovery before production export.");if (document.SourceMillimetresPerUnit != 1d && copied.Any(id => entities[id].Name == "PCURVE"))throw new PmiTransferException("pmi-source-auxiliary-pcurve-units-unsupported: Auxiliary PMI surfaces carry non-metric pcurves whose length domains cannot yet be normalized safely.");for (var i = 0; i < copied.Length; i++) mapping[copied[i]] = $"#{writer.EntityCount + i + 1}";@@ -167,7 +170,9 @@ public sealed class Step242PmiTransfer&& witness.Topology.Bodies.SequenceEqual(body.Topology.Bodies)&& witness.Geometry.Curves.SequenceEqual(body.Geometry.Curves) && witness.Geometry.Surfaces.SequenceEqual(body.Geometry.Surfaces)&& witness.Bindings.FaceBindings.SequenceEqual(body.Bindings.FaceBindings) && witness.Bindings.EdgeBindings.SequenceEqual(body.Bindings.EdgeBindings)- && witness.Bindings.PcurveBindings.SequenceEqual(body.Bindings.PcurveBindings)+ // Optional UV acceleration may be omitted/reconstructed by strict export.+ // The topology, 3D curves/supports, edge trims and face associations above+ // remain the identity witness for semantic PMI.&& witness.Topology.Vertices.All(v => witness.TryGetVertexPoint(v.Id, out var before) == body.TryGetVertexPoint(v.Id, out var after) && before == after);internal static Step242EntityConstructor? GeometricTolerance(Step242ParsedEntity entity) =>diff --git a/Aetheris.Kernel.Core/Step242/Step242ProductionNormalization.cs b/Aetheris.Kernel.Core/Step242/Step242ProductionNormalization.csindex c15c4e3d..8bc297f3 100644--- a/Aetheris.Kernel.Core/Step242/Step242ProductionNormalization.cs+++ b/Aetheris.Kernel.Core/Step242/Step242ProductionNormalization.cs@@ -15,8 +15,8 @@ public static class Step242ProductionNormalizationArgumentNullException.ThrowIfNull(source);if (!double.IsFinite(maximumDeviationMillimetres) || maximumDeviationMillimetres is <= 0d or > .1d)throw new ArgumentOutOfRangeException(nameof(maximumDeviationMillimetres));- if (source.ImportQualification is { GeometryStatus: not ImportQualificationStatus.Qualified })- return Failure("Source engineering geometry is not qualified for production normalization.");+ var sourceBindings = BrepBindingValidator.Validate(source);+ if (!sourceBindings.IsSuccess) return KernelResult<BrepBody>.Failure(sourceBindings.Diagnostics);var geometry = new BrepGeometryStore();var changed = new HashSet<SurfaceGeometryId>();var diagnostics = new List<KernelDiagnostic>();@@ -50,15 +50,18 @@ public static class Step242ProductionNormalizationvar tolerance = source.ImportQualification?.PcurveToleranceMillimetres ?? 1e-3d;body.PcurveRecoveryReport = BrepPcurveRecovery.Populate(body.Topology, geometry, bindings, tolerance);var evidence = BrepPcurveValidator.Validate(body, tolerance, requireEveryCoedge: true);- if (!body.PcurveRecoveryReport.IsSuccess || !evidence.IsValid)- return Failure("Normalized engineering pcurves failed: " + string.Join("; ",- body.PcurveRecoveryReport.Diagnostics.Select(d => d.Message).Concat(evidence.Diagnostics).Take(8)));+ // Qualification of optional reconstructed UV data does not establish or+ // invalidate the normalized 3D boundary. Strict export omits a failed set.+ var preflight = BrepExportPreflight.Validate(body, maximumDeviationMillimetres);+ if (!preflight.IsValid)+ return Failure("Normalized engineering boundary failed: " + string.Join("; ",+ preflight.Diagnostics.Where(d => d.Severity == BrepExportPreflightSeverity.Error).Select(d => d.Code + ": " + d.Message).Take(8)));if (source.ImportQualification is { } report){body.ImportQualification = BrepImportQualification.Evaluate(body, report.ExpectedFaces,- report.SourceDistanceAccuracyMillimetres, tolerance, evidence);- if (body.ImportQualification.GeometryStatus != ImportQualificationStatus.Qualified)- return Failure("Normalized engineering topology did not remain qualified.");+ report.SourceDistanceAccuracyMillimetres, tolerance, evidence) with { Repairs = report.Repairs };+ if (body.ImportQualification.Shells.Any(shell => !shell.Enclosed))+ return Failure("Normalized engineering topology is not an enclosed manifold.");}return KernelResult<BrepBody>.Success(body, diagnostics);}diff --git a/Aetheris.Kernel.Firmament.Tests/ExplicitGdtTests.cs b/Aetheris.Kernel.Firmament.Tests/ExplicitGdtTests.csindex 197ef480..e69df177 100644--- a/Aetheris.Kernel.Firmament.Tests/ExplicitGdtTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/ExplicitGdtTests.cs@@ -1,4 +1,5 @@using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Firmament.FirmamentV2;using Aetheris.Kernel.Firmament.Visualization;@@ -13,6 +14,29 @@ public sealed class ExplicitGdtTestsreturn Path.Combine(directory!.FullName, relative);}private static string Source() => File.ReadAllText(Fixture("fixtures/Canonical/PMI/explicit-gdt.firmament"));+ public static IEnumerable<object[]> NistSources() => Directory.GetFiles(Fixture("testdata/step242/nist"), "*.stp", SearchOption.AllDirectories)+ .Order().Select(path => new object[] { Path.GetRelativePath(Fixture("."), path).Replace('\\', '/') });+ [Theory, MemberData(nameof(NistSources)), Trait("Category", "SlowCorpus")]+ public void PinnedNistSourceUsesRealCompilerAdmissionAndPreservesItsPmi(string relativePath)+ {+ // A fresh import here is intentional: this qualifies compiler resource loading,+ // source-pin verification and its exact-lane policy, beyond the core body cache.+ var sourceText = File.ReadAllText(Fixture(relativePath));+ var normalized = sourceText.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n');+ var pin = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(normalized))).ToLowerInvariant();+ var program = $"Model CorpusPart {{ units: mm InlineStep Source {{ path: \"{relativePath}\" textSha256: \"{pin}\" importTolerance: 0.1mm }} }}";+ var result = FirmamentBuildAndExport.CompileSource(program, Fixture("."));+ if (relativePath.EndsWith("-tg.stp", StringComparison.Ordinal))+ {+ Assert.False(result.IsSuccess); Assert.Contains(result.Diagnostics, d => d.Message.Contains("firmament-inline-step-import-failed", StringComparison.Ordinal));+ return;+ }+ Assert.True(result.IsSuccess, relativePath + ": " + string.Join(";", result.Diagnostics.Select(d => d.Message)));+ var before = Step242SemanticPmiInspector.Inspect(sourceText); var after = Step242SemanticPmiInspector.Inspect(result.Value.StepText);+ Assert.Equal(before.DatumCount, after.DatumCount); Assert.Equal(before.DimensionCount, after.DimensionCount);+ Assert.Equal(before.GeometricToleranceCount, after.GeometricToleranceCount);+ Assert.True(BrepExportPreflight.Validate(result.Value.RuntimeBody!, .1).IsValid);+ }[Fact]public void ImportedNistPmiSurvivesAndAuthoredControlReusesItsExistingDatums(){@@ -27,14 +51,19 @@ public sealed class ExplicitGdtTestsAssert.NotEmpty(added.GeometricFaceEntityIds); Assert.Contains("FREE_STATE", added.Modifiers);}[Fact]- public void UnqualifiedImportedGeometryRemainsRejectedIndependentlyOfAuthoredPmi()+ public void UnchangedPmiExportUsesStrictPhysicalBoundaryChecksInsteadOfAggregateUvStatus(){- var path = Fixture("fixtures/Invalid/InlineStep/nist-ftc11-pmi-unqualified-geometry.invalid.firmfixture");+ var path = Fixture("fixtures/Canonical/PMI/nist-ftc11-passthrough.firmament");var source = File.ReadAllText(path);foreach (var specimen in new[] { source, source[..source.IndexOf(" Pmi {", StringComparison.Ordinal)] + "}" }){var build = FirmamentBuildAndExport.CompileSource(specimen, Path.GetDirectoryName(path));- Assert.False(build.IsSuccess); Assert.Contains(build.Diagnostics, d => d.Message.Contains("firmament-inline-step-import-unqualified"));+ Assert.True(build.IsSuccess, string.Join(";", build.Diagnostics.Select(d => d.Message)));+ Assert.NotEqual(Aetheris.Kernel.Core.Import.ImportQualificationStatus.Qualified, build.Value.RuntimeBody!.ImportQualification!.GeometryStatus);+ Assert.Contains(build.Diagnostics, d => d.Message.StartsWith("step-export-recovered-pcurves-omitted:", StringComparison.Ordinal));+ var inspection = Step242SemanticPmiInspector.Inspect(build.Value.StepText);+ Assert.Equal(2, inspection.DatumCount); Assert.Equal(6, inspection.DimensionCount);+ Assert.Equal(specimen == source ? 5 : 4, inspection.GeometricToleranceCount);}}[Fact]diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentPathFeatureTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentPathFeatureTests.csnew file mode 100644index 00000000..766c93e2--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentPathFeatureTests.cs@@ -0,0 +1,159 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentPathFeatureTests+{+ private static string Root+ {+ get+ {+ var root = new DirectoryInfo(AppContext.BaseDirectory);+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx"))) root = root.Parent;+ return root!.FullName;+ }+ }+ private static string Fixture(string file) => File.ReadAllText(Path.Combine(Root, "fixtures/Canonical/Features/PathFeatures", file));+ private static FirmamentV2ValidationReport Validate(string source) => FirmamentBuildAdmissionValidation.Admit(+ FirmamentV2ValidationReportBuilder.Build(FirmamentV2Parser.Parse(source), "path-feature.firmament", sourceText: source), source);+ private static string Messages<T>(Aetheris.Kernel.Core.Results.KernelResult<T> result) => string.Join("; ", result.Diagnostics.Select(d => d.Message));++ [Theory]+ [InlineData("manual-rib.firmament", "Stiffener", 16)]+ [InlineData("plate-seal-groove.firmament", "SealSeat", 8)]+ [InlineData("shaft-seal-groove.firmament", "SealSeat", 40)]+ [InlineData("bore-seal-groove.firmament", "SealSeat", 40)]+ [InlineData("arc-rib.firmament", "Stiffener", 14)]+ public void AuthoredFeatureBuildsThroughUnifiedAdmission(string fixture, string name, double maximumZ)+ {+ var source = Fixture(fixture); var validated = Validate(source);+ Assert.Equal("valid", validated.Status); Assert.Equal("Built", validated.ValidationLevel);+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.Equal("UnifiedMechanical", parsed.ParserRoute);+ var declared = Assert.Single(parsed.Document!.PathFeatures);+ Assert.EndsWith(fixture is "manual-rib.firmament" or "arc-rib.firmament" ? "Spine" : "Seal", declared.GuideReference);+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, Messages(built));+ Assert.Equal(parsed.Document.ModelName, built.Value.ExportedFeatureId);+ Assert.Equal(name, Assert.Single(built.Value.MaterializedFeatures).Name);+ Assert.NotEmpty(built.Value.RuntimeCorrespondence!.Descendants);+ Assert.Equal(declared.GuideReference, Assert.Single(built.Value.EngineeringFeatures!).Profile);+ Assert.All(built.Value.RuntimeCorrespondence.Descendants, d => Assert.Contains(name, d.StableId));+ var body = built.Value.RuntimeBody!;+ var points = body.Topology.Vertices.Select(v => { Assert.True(body.TryGetVertexPoint(v.Id, out var p)); return p; }).ToArray();+ Assert.Equal(0, points.Min(p => p.Z), 8); Assert.Equal(maximumZ, points.Max(p => p.Z), 8);+ Assert.True(BrepExportPreflight.Validate(body).IsValid);+ Assert.DoesNotContain("B_SPLINE_SURFACE", built.Value.StepText, StringComparison.Ordinal);+ Assert.All(body.Geometry.Curves, c => Assert.Null(c.Value.BSpline3));+ var imported = Step242Importer.ImportBody(built.Value.StepText);+ Assert.True(imported.IsSuccess, Messages(imported));+ var mass = BrepMassProperties.Evaluate(imported.Value);+ Assert.True(mass.IsEnclosed && mass.IsOrientationConsistent);+ }++ [Fact]+ public void TwoDifferentChannelSectionsBuildWithoutDroppingEither()+ {+ var source = Fixture("plate-channels.firmament"); Assert.Equal("valid", Validate(source).Status);+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, Messages(built)); Assert.Equal(2, built.Value.MaterializedFeatures.Count);+ Assert.Contains(built.Value.RuntimeBody!.Geometry.Surfaces, s => s.Value.Cylinder is not null);+ Assert.Contains(built.Value.RuntimeBody!.Geometry.Surfaces, s => s.Value.Sphere is not null);+ Assert.True(BrepMassProperties.Evaluate(built.Value.RuntimeBody!).IsEnclosed);+ }++ [Theory]+ [InlineData("shaft-seal-groove.firmament", "station: 20mm", "station: 1mm")]+ [InlineData("shaft-seal-groove.firmament", "radius: 15mm }", "radius: 14mm }")]+ [InlineData("bore-seal-groove.firmament", "radius: 2mm", "radius: 5mm")]+ [InlineData("plate-seal-groove.firmament", "radius: 1.5mm", "radius: 1.5mm; depth: 2mm")]+ public void GrooveContractsRejectWithoutWritingPartialGeometry(string fixture, string before, string after)+ {+ var source = Fixture(fixture).Replace(before, after, StringComparison.Ordinal);+ Assert.Equal("invalid", Validate(source).Status);+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);+ }++ [Theory]+ [InlineData("thickness: 3mm", "thikness: 3mm", "canonical-field-unknown")]+ [InlineData("draft: 2deg", "draft: 30deg", "draft-collapse")]+ [InlineData("height: 10mm", "height: 0mm", "dimensions")]+ [InlineData("height: 10mm", "height: 10deg", "unit-mismatch")]+ [InlineData("on: face(Plate.Top)", "on: +X", "contract")]+ [InlineData("on XY", "on XZ", "frame")]+ [InlineData("path: Layout.Spine", "path: Missing", "guide")]+ [InlineData("Rib<Rectangular>", "Rib<Semicircular>", "contract")]+ [InlineData("ends: Round", "ends: Guess", "contract")]+ public void UnsupportedIntentNeverValidatesOrBuilds(string before, string after, string code)+ {+ var source = Fixture("manual-rib.firmament").Replace(before, after, StringComparison.Ordinal);+ var validated = Validate(source); var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.Equal("invalid", validated.Status); Assert.False(built.IsSuccess);+ Assert.Contains(validated.Diagnostics, d => d.Code.Contains(code, StringComparison.Ordinal));+ Assert.Contains(validated.Diagnostics, d => d.SourceSpan is not null && d.Line > 0);+ }++ [Fact]+ public void ScalarBindingsAndOpenPathRetainTheirEngineeringMeaning()+ {+ const string source = """+ Model ParameterizedRib {+ units: mm+ Static H: Length = 8mm+ Path Spine { start: Point2(-15mm,0mm); heading: 0deg; Line Run { length: 30mm } }+ Box Plate { size: [50mm,40mm,5mm] }+ Modify Plate { Rib<Rectangular> Web { on: +Z; path: Spine; thickness: 3mm; height: H; draft: 1deg } }+ }+ """;+ var result = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(result.IsSuccess, Messages(result));+ var body = result.Value.RuntimeBody!;+ var top = body.Topology.Vertices.Select(v => { body.TryGetVertexPoint(v.Id, out var p); return p.Z; }).Max();+ Assert.Equal(13, top, 8);+ }++ [Fact]+ public void MultipleManualRibsRemainNamedAfterReordering()+ {+ const string prefix = """+ Model Ribs {+ units: mm+ Path Left { start: Point2(-15mm,-8mm); heading: 0deg; Line RunL { length: 30mm } }+ Path Right { start: Point2(-15mm,8mm); heading: 0deg; Line RunR { length: 30mm } }+ Box Plate { size: [50mm,40mm,5mm] }+ Modify Plate {+ """;+ const string a = "Rib<Rectangular> Alpha { on: +Z; path: Left; thickness: 3mm; height: 8mm }";+ const string b = "Rib<Rectangular> Beta { on: +Z; path: Right; thickness: 3mm; height: 8mm }";+ var first = FirmamentBuildAndExport.CompileSource(prefix + a + b + "}}");+ var second = FirmamentBuildAndExport.CompileSource(prefix + b + a + "}}");+ Assert.True(first.IsSuccess, Messages(first)); Assert.True(second.IsSuccess, Messages(second));+ Assert.Equal(first.Value.RuntimeCorrespondence!.Descendants.Select(d => d.StableId).Order(),+ second.Value.RuntimeCorrespondence!.Descendants.Select(d => d.StableId).Order());+ Assert.Equal(2, second.Value.MaterializedFeatures.Count);+ Assert.Equal(BrepMassProperties.Evaluate(first.Value.RuntimeBody!).SignedVolume,+ BrepMassProperties.Evaluate(second.Value.RuntimeBody!).SignedVolume, 6);+ var crossing = prefix.Replace("Point2(-15mm,8mm)", "Point2(-15mm,-8mm)", StringComparison.Ordinal) + a + b + "}}";+ var rejected = FirmamentBuildAndExport.CompileSource(crossing);+ Assert.False(rejected.IsSuccess); Assert.Contains("junction-unqualified", Messages(rejected));+ }++ [Fact]+ public void QualifiedGuideCannotCaptureAnotherLayoutsPointDependencies()+ {+ var source = Fixture("manual-rib.firmament").Replace("Box Plate", """+ Concept Struct Other on XY {+ Point2 Start { position: [1mm,1mm] }+ Point2 End { position: [2mm,1mm] }+ }+ Box Plate+ """, StringComparison.Ordinal);+ Assert.Equal("invalid", Validate(source).Status);+ var rejected = FirmamentBuildAndExport.CompileSource(source);+ Assert.False(rejected.IsSuccess); Assert.Contains("guide-ambiguous", Messages(rejected));+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.csindex 41e17f6a..e3118a7d 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentSemanticSchemaTests.cs@@ -12,9 +12,9 @@ public sealed class FirmamentSemanticSchemaTests["Appearance", "FrameTransform", "Placement", "Pmi", "Note", "Provenance","Box", "Circle2", "Compose", "Base", "Concept", "Points", "Door", "Drape", "EdgeFinish", "Ellipsoid", "Extrude", "Fabric", "FigureFit", "Fitting", "Garment",- "Helix", "Hole", "Interface<Fixed>", "Interface<Prismatic>", "Interface<Revolute>",+ "Groove", "Helix", "Hole", "Interface<Fixed>", "Interface<Prismatic>", "Interface<Revolute>","Interface<Stitch>", "Inventory", "Joint", "Loft", "Panel", "Perforation", "Material", "Linear", "Series", "Polyhedron", "Pose", "PoseTransition",- "Profile", "Rect2", "Room", "RoundedRect2", "Scene", "Camera", "Section", "Slot2", "Thread", "Window", "Follow", "WireRoute",+ "Profile", "Rect2", "Rib", "Room", "RoundedRect2", "Scene", "Camera", "Section", "Slot2", "Thread", "Window", "Follow", "WireRoute",];Assert.Equal(expectedNames, FirmamentSemanticSchemas.All.Select(schema => schema.Name));var hole = Assert.IsType<FirmamentConstructSchema>(FirmamentSemanticSchemas.Get("Hole"));diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2InlineStepTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2InlineStepTests.csindex 8292609c..2c20bb12 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2InlineStepTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2InlineStepTests.cs@@ -72,6 +72,7 @@ public sealed class FirmamentV2InlineStepTestsvar result = FirmamentBuildAndExport.Run(Path.Combine(repo, FixturePath), outputPath);Assert.True(result.IsSuccess, string.Join(Environment.NewLine, result.Diagnostics.Select(d => $"{d.Source}: {d.Message}")));+ Assert.Contains(result.Diagnostics, d => d.Message.StartsWith("step-import-loop-order-recovered:", StringComparison.Ordinal));Assert.True(File.Exists(outputPath));Assert.Equal("inline-step", result.Value.Export.ExportedBodyCategory);Assert.Equal("aetheris-canonical-ap242", result.Value.Export.ExportedFeatureKind);diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 608fc542..cd548025 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -566,6 +566,8 @@ public static partial class FirmamentBuildAndExport{return KernelResult<FirmamentStepExportResult>.Failure(dfm.Diagnostics);}+ if (v2Parse.Document.PathFeatures.Count > 0)+ return ExportPathFeatures(v2Parse.Document);if (v2Parse.Document.Solids.Any(s => s.InlineStep?.SourceHashPin is not null)&& (v2Parse.Document.Solids.Count != 1 || v2Parse.Document.Replacements is { Count: > 0 } || v2Parse.Document.Removals.Count > 0@@ -2356,15 +2358,16 @@ public static partial class FirmamentBuildAndExport}var stepText = inlineStep.SourceText ?? File.ReadAllText(inlineStep.NormalizedPath, Encoding.UTF8);- var import = inlineStep.RuntimeBody is { } admitted ? KernelResult<BrepBody>.Success(admitted.Clone()) : Step242Importer.ImportBody(stepText);+ var import = inlineStep.RuntimeBody is { } admitted ? KernelResult<BrepBody>.Success(admitted.Clone())+ : Step242Importer.ImportBody(stepText, new Aetheris.Kernel.Core.Import.ImportPolicy(PreferredLane: Aetheris.Kernel.Core.Import.ImportLaneKind.ExactBRep));if (!import.IsSuccess){return KernelResult<FirmamentStepExportResult>.Failure(import.Diagnostics);}- if (inlineStep.SourceHashPin is not null && import.Value.ImportQualification?.GeometryStatus != Aetheris.Kernel.Core.Import.ImportQualificationStatus.Qualified)- return KernelResult<FirmamentStepExportResult>.Failure([new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,- "firmament-inline-step-import-unqualified: Pinned re-export requires qualified imported trims.", "FirmamentV2.InlineStep")]);+ // A source pin proves identity, not complete UV reconstruction. Unchanged+ // annotation/re-export is admitted by strict output preflight below.+ // Topology edits retain their operation-specific qualified-trim guards.var semanticPmiValidation = ValidateV2PmiExportSupport(document);if (!semanticPmiValidation.IsSuccess){@@ -2391,8 +2394,9 @@ public static partial class FirmamentBuildAndExportProductName = solid.Name,ApplicationName = "Aetheris.Firmament.InlineStep",ImportedPmi = importedPmi,- BrepExportPreflightMode = inlineStep.SourceHashPin is null ? BrepExportPreflightMode.Audit : BrepExportPreflightMode.Enforce,- ImportedRecoveryToleranceMillimetres = inlineStep.ImportToleranceMillimetres ?? .001+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,+ ImportedRecoveryToleranceMillimetres = double.Min(.1, inlineStep.ImportToleranceMillimetres ?? .001)});if (!export.IsSuccess){@@ -2408,11 +2412,11 @@ public static partial class FirmamentBuildAndExportinlineStep.CanonicalInput ? "aetheris-canonical-ap242" : "qualified-import-ap242",DatumInspection: document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.DatumPlane).Select(p => new FirmamentPmiInspectionDatum(p.Name, "planar", p.Target)).ToArray() ?? [],DimensionInspection: document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.HoleDiameter).Select(p => new FirmamentPmiInspectionDimension("Diameter", p.Target, null, p.Value ?? 0d, "explicit-v2-record-pmi", p.Name)).ToArray() ?? [],- InlineStepMigration: InlineStepMigrationReportBuilder.Build(document, solid, emissionStrategy: inlineStep.CanonicalInput ? "canonical-reexport" : "qualified-import-reexport", residualSurgery: false),+ InlineStepMigration: InlineStepMigrationReportBuilder.Build(document, solid, emissionStrategy: inlineStep.CanonicalInput ? "canonical-reexport" : "strict-import-reexport", residualSurgery: false),InlineStepReplacementAssist: InlineStepReplacementAssistReportBuilder.Build(document)){ RuntimeBody = import.Value, RuntimeBodySourceName = solid.Name, RuntimeAdmissionDocument = document },- inlineStep.GeometryOnly ? [new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Warning,- "firmament-inline-step-source-semantics-excluded: geometryOnly explicitly excludes source annotations; geometry remains unchanged.", "FirmamentV2.InlineStep")] : export.Diagnostics);+ export.Diagnostics.Concat(inlineStep.GeometryOnly ? [new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Warning,+ "firmament-inline-step-source-semantics-excluded: geometryOnly explicitly excludes source annotations; geometry remains unchanged.", "FirmamentV2.InlineStep")] : []).ToArray());}private static KernelResult<FirmamentStepExportResult>? TryExportV2ControlledSideHoleBody(FirmamentV2Document document)diff --git a/Aetheris.Kernel.Firmament/FirmamentPathFeatureExport.cs b/Aetheris.Kernel.Firmament/FirmamentPathFeatureExport.csnew file mode 100644index 00000000..5774c881--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentPathFeatureExport.cs@@ -0,0 +1,57 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.Execution;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament;++public static partial class FirmamentBuildAndExport+{+ private static KernelResult<FirmamentStepExportResult> ExportPathFeatures(FirmamentV2Document document)+ {+ var stock = document.Solid;+ KernelResult<PathFeatureBody> built; double height;+ if (stock.Box is { } box)+ {+ height = box.Size[2];+ built = BrepPlanarPathFeature.BuildBox(box.Size[0], box.Size[1], height, document.PathFeatures.Select(f => f.Feature).ToArray());+ }+ else+ {+ var cylinder = stock.Cylinder!; height = cylinder.Height;+ built = BrepCircumferentialGroove.BuildCylinder(cylinder.Radius, height, document.PathFeatures.Select(f =>+ new CircumferentialGroove(f.Feature.Name, f.Feature.Section, f.Feature.Width, f.Feature.Extent, f.Station - height / 2, f.Support == "InnerWall")).ToArray(), stock.Hollow?.WallThickness);+ }+ if (!built.IsSuccess)+ return KernelResult<FirmamentStepExportResult>.Failure(built.Diagnostics.Select(d =>+ {+ var operation = document.PathFeatures.FirstOrDefault(f => d.Message.Contains(f.Feature.Name + ":", StringComparison.Ordinal));+ var span = operation?.SourceSpan ?? stock.SourceSpan;+ return d with { SourceSpan = span is null ? null : new(span.Start, span.Length)+ { LocationNote = operation is null ? "Enclosing material host; no unique individual feature location was supplied." : null } };+ }).ToArray());+ var body = FirmamentPrimitiveExecutionTranslation.TranslateBody(built.Value.Body, new(0, 0, height / 2));+ var annotations = BuildV2SemanticPmi(document, [], stock.Name, body: body);+ var exported = Step242Exporter.ExportBody(body, annotations, new Step242ExportOptions {+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });+ if (!exported.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(exported.Diagnostics);+ var descendants = document.PathFeatures.SelectMany(f => built.Value.Faces[f.Feature.Name].Select((face, i) =>+ new SemanticTopologyDescendant($"{f.Host}.{f.Feature.Name}.Face{i}", "Face", SemanticTopologyRole.PathFeatureFace,+ f.Host + "." + f.Feature.Name, Face: face, ParentStableId: f.Host,+ Addressability: SemanticTopologyAddressability.DerivedStable))).ToArray();+ return KernelResult<FirmamentStepExportResult>.Success(new(exported.Value, document.ModelName, 0, "path-feature", "AnalyticPathFeature") {+ RuntimeBody = body, RuntimeBodySourceName = stock.Name,+ RuntimeCorrespondence = new(stock.Name, descendants, ["UnifiedAst", "ConceptGuide", "AnalyticPathFeature"],+ document.PathFeatures.ToDictionary(f => f.Host + "." + f.Feature.Name, f => f.SourceSpan)),+ MaterializedFeatures = document.PathFeatures.Select(f => new FirmamentFeatureReceipt(f.Host, f.Feature.Add ? "Rib" : "Groove", f.Feature.Name)).ToArray(),+ EngineeringFeatures = document.PathFeatures.Select(f => new FirmamentEngineeringFeatureReport(+ f.Feature.Name, f.Feature.Add ? "Rib" : "Groove", f.Host + "." + f.Feature.Name, f.Host, f.Support,+ f.GuideReference, f.Feature.Extent, f.Feature.Add ? "Height" : "Depth", f.Feature.Add ? "Add" : "Remove",+ PolicySource: "ManualConceptGuide", MaterializationRoute: "AnalyticPathFeature",+ ToolFamily: f.Feature.Section.ToString(), Direction: f.Feature.Add ? "OutOfSupport" : "IntoSupport")).ToArray()+ }, exported.Diagnostics);+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.csindex 5512a6ed..f1d6bf38 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<FirmamentV2PathFeature> PathFeatures { get; init; } = [];public IReadOnlyList<FirmamentGeometryAssertion> GeometryAssertions { get; init; } = [];public IReadOnlyList<FirmamentV2RemovalDecl> Removals { get; init; } = [];public FirmamentV2SolidBinding Solid => Solids[^1];diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.csindex 9a831c0a..fb481f96 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs@@ -38,7 +38,8 @@ public static partial class FirmamentV2Parserprivate static FirmamentV2ParseResult BindMechanicalModel(DocumentSyntax syntax, DeclarationSyntax model,string source, List<string> diagnostics, string? sourceDirectory,IReadOnlyList<ConceptIrTemplateInstantiation>? templateInstantiations, FirmamentCompileTimeValues? compileTime = null,- IReadOnlyDictionary<string, string>? resources = null)+ IReadOnlyDictionary<string, string>? resources = null, IReadOnlyList<FirmamentV2ClosedBoundary2Decl>? boundaries = null,+ DocumentSyntax? authoredSyntax = null){if (model.Body is null || model.Name is null) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);if (model.Clauses.Count > 0 || model.Type.Arguments.Count > 0)@@ -161,6 +162,7 @@ public static partial class FirmamentV2Parser}if (solids.Count == 0) diagnostics.Add(MissingSolid);var modifies = new List<FirmamentV2ModifyBlock>();+ var pathFeatures = new List<FirmamentV2PathFeature>();foreach (var modify in declarations.Where(d => d.Type.Name.Text == "Modify")){if (modify.Clauses.Count > 0 || modify.Type.Arguments.Count > 0) diagnostics.Add(CanonicalModifyMalformed);@@ -185,18 +187,37 @@ public static partial class FirmamentV2Parsercase "Perforation":if (BindMechanicalPerforation(fields, diagnostics) is { } perforation) perforations.Add(perforation);break;+ case "Rib" or "Groove":+ if (BindPathFeature(fields, solid.Name, source, diagnostics, compileTime, boundaries ?? [], authoredSyntax ?? syntax) is { } pathFeature) pathFeatures.Add(pathFeature);+ break;default: diagnostics.Add($"{CanonicalDeclarationUnknown}:Modify:{feature.Type.Name.Text}"); break;}fields.Complete();CaptureFieldDiagnostics(feature, diagnosticStart);}if (holes.Count > 0 && solid.Box is null) diagnostics.Add(ModifyTargetNotSolid);- if (solid.ConstructionPolicy == FirmamentV2ConstructionPolicy.Hollow &&+ if (solid.ConstructionPolicy == FirmamentV2ConstructionPolicy.Hollow && !pathFeatures.Any(f => f.Host == solid.Name) &&(solid.Cylinder is null || holes.Count > 0 || finishes.Count > 0 || perforations.Count != 1 ||perforations.Any(p => p.SupportFace != "OuterWall" || p.Layout is not ("CylindricalGrid" or "CylindricalStaggered"))))diagnostics.Add("firmament-v2-hollow-modify-unsupported");modifies.Add(new(solid.Name, [], holes, finishes, perforations));}+ if (pathFeatures.Count > 0)+ {+ var stock = solids.Values.SingleOrDefault();+ if (stock is null || stock.Box is null && stock.Cylinder is null+ || modifies.Any(m => m.SemanticHoles.Count > 0 || m.EdgeFinishes?.Count > 0 || m.Perforations?.Count > 0)+ || declarations.Any(d => d.Type.Name.Text == "Thread"))+ diagnostics.Add("firmament-path-feature-host: Use direct Box or Cylinder stock without Hole, EdgeFinish, Perforation or Thread operations.");+ else if (stock.Box is not null && pathFeatures.Any(f => f.Support != "+Z") || stock.Cylinder is not null+ && pathFeatures.Any(f => f.Feature.Add || f.Support is not ("OuterWall" or "InnerWall")+ || f.Feature.Guide.Kind != Aetheris.Kernel.Core.Brep.Features.PlanarGuideKind.Circle+ || double.Abs(f.Feature.Guide.Center.X) + double.Abs(f.Feature.Guide.Center.Y) > 1e-9+ || double.Abs(f.Feature.Guide.Radius - (stock.Cylinder.Radius - (f.Support == "InnerWall" ? stock.Hollow?.WallThickness ?? 0 : 0))) > 1e-8))+ diagnostics.Add("firmament-path-feature-support: Box supports +Z; cylindrical grooves require a coaxial Circle2 on OuterWall or InnerWall with the support radius and an explicit station.");+ if (stock?.Hollow is { } shell && (shell.BottomBlendRadius != 0 || shell.Openings.Count != 1 || shell.Openings[0] != "Top"))+ diagnostics.Add("firmament-path-feature-hollow: Cylindrical grooves currently support only top-open hollow stock without a bottom blend.");+ }if (UniformStockFilletAdmission.Error(solids.Values.ToArray(), modifies,declarations.Any(d => d.Type.Name.Text is "Thread" or "Replace")) is { } stockError){@@ -219,7 +240,7 @@ public static partial class FirmamentV2Parserreturn FirmamentV2ParseResult.Success(new(model.Name!.Text, "mm", solids.Values.ToArray(), modifies,Pmi: pmi, RecognizedRegions: recognized, Replacements: replacements, PmiBlock: pmiBlock, BoundPmi: boundPmi, Selections: selections,Lets: staticValues.Declarations, BoundLets: staticValues.Values,- TemplateInstantiations: templateInstantiations is { Count: > 0 } ? templateInstantiations : null) { Removals = removals },+ TemplateInstantiations: templateInstantiations is { Count: > 0 } ? templateInstantiations : null) { Removals = removals, PathFeatures = pathFeatures },diagnostics.Append("firmament-v2-unified-canonical-parsed").Append("firmament-v2-parse-succeeded").Distinct(StringComparer.Ordinal).Order().ToArray())with { SyntaxDiagnostics = locatedDiagnostics };}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csindex 1c2d0da5..a778645a 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -612,7 +612,7 @@ public static partial class FirmamentV2Parserif (!syntax.IsSuccess)return FirmamentV2ParseResult.Failure(diagnostics.Concat(syntax.Diagnostics.Select(d => d.Code)).ToArray(), FirmamentV2ParseDisposition.RecognizedInvalid)with { ParserRoute = "UnifiedMechanical", OwnsUnifiedAdmission = true, SyntaxDiagnostics = syntax.Diagnostics };- var parsed = Recognized(BindMechanicalModel(syntax.Document, modelSyntax, source, diagnostics, sourceDirectory, templateExpansion.Instantiations, compileTime, resources))+ var parsed = Recognized(BindMechanicalModel(syntax.Document, modelSyntax, source, diagnostics, sourceDirectory, templateExpansion.Instantiations, compileTime, resources, polygonExpansion.Boundaries, authoredSyntax.Document))with { DiagnosticSource = source };if (parsed.Document is null) return parsed with { ParserRoute = "UnifiedMechanical", OwnsUnifiedAdmission = true };if (domainDeclarations.Any(d => d.Type.Name.Text == "Plateau"))@@ -1161,7 +1161,8 @@ public static partial class FirmamentV2Parserif (sourceHashPin is not null){var imported = Aetheris.Kernel.Core.Step242.Step242Importer.ImportBody(stepText,- new Aetheris.Kernel.Core.Import.ImportPolicy(PcurveQualificationToleranceMillimetres: importTolerance ?? 1e-3));+ new Aetheris.Kernel.Core.Import.ImportPolicy(PreferredLane: Aetheris.Kernel.Core.Import.ImportLaneKind.ExactBRep,+ PcurveQualificationToleranceMillimetres: importTolerance ?? 1e-3));if (!imported.IsSuccess) { diagnostics.AddRange(imported.Diagnostics.Select(d => "firmament-inline-step-import-failed: " + d.Message)); return null; }runtimeBody = imported.Value;}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2PathFeatures.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2PathFeatures.csnew file mode 100644index 00000000..b0e6be01--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2PathFeatures.cs@@ -0,0 +1,103 @@+using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++public sealed record FirmamentV2PathFeature(string Host, string Support, string GuideReference,+ PlanarPathFeature Feature, FirmamentV2SourceSpan SourceSpan, double Station = 0);++public static partial class FirmamentV2Parser+{+ private static FirmamentV2PathFeature? BindPathFeature(FirmamentSyntaxFields fields,+ string host, string source, List<string> diagnostics, FirmamentCompileTimeValues? values,+ IReadOnlyList<FirmamentV2ClosedBoundary2Decl> boundaries, DocumentSyntax authoredSyntax)+ {+ var declaration = fields.Declaration;+ var add = declaration.Type.Name.Text == "Rib";+ var variant = declaration.Type.Arguments.Count == 1 ? FirmamentSyntaxValues.Reference(declaration.Type.Arguments[0].Value) : null;+ var supportExpression = fields.Take("On");+ var support = supportExpression is CallSyntax { Target: ReferenceSyntax { Name.Text: "face" }, Arguments.Count: 1 } call+ ? FirmamentSyntaxValues.Reference(call.Arguments[0].Value) : FirmamentSyntaxValues.Reference(supportExpression);+ if (support == host + ".Top" || support == "Top") support = "+Z";+ if (support == host + ".OuterWall") support = "OuterWall";+ if (support == host + ".InnerWall") support = "InnerWall";+ var guideReference = fields.Reference("Path");+ var semicircle = variant == "Semicircular";+ var width = semicircle ? fields.Number("Radius", "mm") * 2 : fields.Number(add ? "Thickness" : "Width", "mm");+ var extent = semicircle ? width / 2 : fields.Number(add ? "Height" : "Depth", "mm");+ var draft = add ? fields.Number("Draft", "deg", 0) : 0;+ var endsExpression = fields.Take("Ends");+ var ends = endsExpression is null ? "Flat" : FirmamentSyntaxValues.Reference(endsExpression);+ var station = support is "OuterWall" or "InnerWall" ? fields.Number("Station", "mm") : 0;+ if (declaration.Name is null || variant is not ("Rectangular" or "Semicircular") || add && semicircle+ || support is not ("+Z" or "OuterWall" or "InnerWall") || guideReference is null || ends is not ("Flat" or "Round"))+ {+ diagnostics.Add("firmament-path-feature-contract: Use Rib<Rectangular> or Groove<Rectangular|Semicircular>, an explicit supported on face, and a named path; ends is Flat or Round.");+ return null;+ }+ var construction = ProfileAuthoringParser.InspectConstruction(source, values ?? new(source));+ diagnostics.AddRange(construction.Diagnostics);+ var authoredDeclarations = FirmamentSyntaxTraversal.Declarations(authoredSyntax).ToArray();+ // The legacy guide owner also stores point dependencies by leaf name.+ // A qualified Line2 must not accidentally consume another layout's Start/End.+ var duplicatePoint = authoredDeclarations.Where(d => d.Type.Name.Text == "Point2" && d.Name is not null)+ .GroupBy(d => d.Name!.Text, StringComparer.Ordinal).FirstOrDefault(group => group.Count() > 1);+ if (duplicatePoint is not null)+ diagnostics.Add("firmament-path-feature-guide-ambiguous: Named Point2 '" + duplicatePoint.Key+ + "' is declared in multiple scopes. The current guide owner requires unique construction point names.");+ var guideParts = guideReference.Split('.');+ var explicitOwner = authoredDeclarations.Where(d => d.Type.Name.Text == "Struct" && d.Name?.Text == guideParts[0]+ && d.Modifiers.Any(m => m.Name.Text == "Concept")).ToArray();+ var rootName = explicitOwner.Length == 1 && guideParts.Length > 1 ? guideParts[1] : guideParts[0];+ var guideDeclarations = authoredDeclarations.Where(d => d.Name?.Text == rootName+ && d.Type.Name.Text is "Line2" or "Arc2" or "Circle2" or "Rect2" or "Path").ToArray();+ if (guideDeclarations.Length > 1)+ diagnostics.Add("firmament-path-feature-guide-ambiguous: Reused guide names are not yet scope-qualified by the legacy guide owner. Use unique guide names.");+ foreach (var owner in authoredDeclarations.Where(d => d.Type.Name.Text == "Struct" && d.Modifiers.Any(m => m.Name.Text == "Concept")+ && guideDeclarations.Any(guide => guide.Span.Start > d.Span.Start && guide.Span.Start < d.Span.Start + d.Span.Length)))+ if (owner.Clauses.Any(c => c.Kind != ClauseKind.On || FirmamentSyntaxValues.Reference(c.Value) != "XY"))+ diagnostics.Add("firmament-path-feature-frame: This feature consumes XY support-local construction coordinates; other construction frames are not admitted.");+ var guideKey = guideReference;+ // The existing guide owner publishes leaf names for legacy Concept Structs.+ // Resolve the qualifier against that actual declaration, rejecting ambiguity.+ if (explicitOwner.Length == 1 && guideParts.Length > 1)+ {+ var members = explicitOwner[0].Body?.Statements.OfType<DeclarationSyntax>().Where(d => d.Name?.Text == rootName).ToArray() ?? [];+ if (members.Length != 1)+ {+ diagnostics.Add("firmament-path-feature-guide: '" + guideReference + "' does not identify one member of its Concept Struct.");+ return null;+ }+ if (!construction.Guides.ContainsKey(guideKey)) guideKey = string.Join('.', guideParts.Skip(1));+ }+ LineArcProfileCurve2D? curve = construction.Guides.GetValueOrDefault(guideKey);+ if (curve is null)+ {+ // ClosedBoundary2 owns the dimensions erased by its earlier expansion.+ // Consume its typed result, never infer generated declaration spellings.+ var shapes = boundaries.Where(b => b.Name == guideKey && b.ShapeType == "Circle2").ToArray();+ if (shapes.Length == 1) curve = new LineArcFullCircle2D((shapes[0].CenterX, shapes[0].CenterY), shapes[0].Dimensions["Radius"]);+ }+ if (curve is null)+ {+ var path = ProfileAuthoringParser.ResolveConceptPath(source, guideReference, out var reported);+ if (path?.Segments.Count == 1) curve = path.Segments[0].Geometry;+ else diagnostics.Add("firmament-path-feature-guide: Path '" + guideReference + "' must resolve to one line, arc or circle. Multi-segment junctions are not yet admitted. " + string.Join("; ", reported));+ }+ PlanarFeatureGuide? guide = curve switch+ {+ LineArcLineSegment2D line => new(PlanarGuideKind.Line, new(line.Start.X, line.Start.Y), new(line.End.X, line.End.Y), default),+ LineArcCircularArc2D arc => new(PlanarGuideKind.Arc, default, default, new(arc.Center.X, arc.Center.Y), arc.Radius, arc.StartAngleRadians, arc.SweepAngleRadians),+ LineArcFullCircle2D circle => new(PlanarGuideKind.Circle, default, default, new(circle.Center.X, circle.Center.Y), circle.Radius),+ _ => null+ };+ if (guide is null) { diagnostics.Add("firmament-path-feature-guide: Only analytic line, arc and circle guides are admitted."); return null; }+ if (guide.Kind == PlanarGuideKind.Circle && endsExpression is not null)+ diagnostics.Add("firmament-path-feature-ends: Closed guides have no end condition; omit ends.");+ if (!double.IsFinite(width + extent + draft + station) || width <= 0 || extent <= 0 || draft < 0)+ diagnostics.Add("firmament-path-feature-dimensions: Section dimensions must be finite and positive; draft must be nonnegative.");+ return new(host, support!, guideReference, new(declaration.Name.Text, add,+ semicircle ? PathSectionKind.Semicircular : PathSectionKind.Rectangular, guide, width, extent, draft, ends == "Round"), declaration.Span, station);+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.csindex 3bdcdd48..17cb74cd 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs@@ -554,8 +554,8 @@ public static class ProfileAuthoringParservar content = declaration.Body.ContentSpan;var pathBody = source.Substring(content.Start, content.Length);var pathFields = new FirmamentSyntaxFields(declaration with { Modifiers = [] }, diagnostics);- pathFields.Take("Start");- pathFields.Take("Heading");+ var startExpression = pathFields.Take("Start");+ var headingExpression = pathFields.Take("Heading");var recognizedSteps = FindPathSteps(pathBody).Select(s => content.Start + s.Index).ToHashSet();var steps = declaration.Body.Statements.Where(s => s is DeclarationSyntax d && recognizedSteps.Contains(d.Span.Start)|| s is ExpressionStatementSyntax).ToHashSet();@@ -576,12 +576,11 @@ public static class ProfileAuthoringParser}continue;}- var startMatch = Regex.Match(pathBody, @"\bStart\s*:\s*Point2\s*\(\s*(?<x>[-+.\deE]+)mm\s*,\s*(?<y>[-+.\deE]+)mm\s*\)", RegexOptions.CultureInvariant);- if (!startMatch.Success || !TryNumber(startMatch.Groups["x"].Value, out var sx) || !TryNumber(startMatch.Groups["y"].Value, out var sy)) { diagnostics.Add($"concept-path-start-invalid:{name}"); continue; }+ if (!FirmamentSyntaxValues.Vector(startExpression, "mm", out var startCoordinates) || startCoordinates.Length != 2+ || startCoordinates.Any(n => !double.IsFinite(n))) { diagnostics.Add($"concept-path-start-invalid:{name}"); continue; }var heading = 0d;- var headingMatch = Regex.Match(pathBody, @"\bHeading\s*:\s*(?<value>[-+.\deE]+)deg", RegexOptions.CultureInvariant);- if (headingMatch.Success && (!TryNumber(headingMatch.Groups["value"].Value, out heading) || !double.IsFinite(heading))) { diagnostics.Add($"concept-path-heading-invalid:{name}"); continue; }- var path = new BoundPath(name, (sx, sy), heading, []);+ if (headingExpression is not null && (!FirmamentSyntaxValues.TryMeasure(headingExpression, "deg", out heading) || !double.IsFinite(heading))) { diagnostics.Add($"concept-path-heading-invalid:{name}"); continue; }+ var path = new BoundPath(name, (startCoordinates[0], startCoordinates[1]), heading, []);if (points.ContainsKey($"{name}.Start") || guides.ContainsKey(name)) { diagnostics.Add($"concept-path-name-collision:{name}"); continue; }points[$"{name}.Start"] = path.Start;var current = path.Start;@@ -749,15 +748,26 @@ public static class ProfileAuthoringParsercurves = [new LineArcLineSegment2D(current, endpoint)]; headingDegrees = Heading(current, endpoint); return true;}var body = step.Body;+ Dictionary<string, string?>? boundFields = null;if (step.Kind is "Line" or "Span" or "Arc"){- // Segment bodies are read by name; reject anything the binder would silently ignore.+ // Read the same AST fields after compile-time serialization as before it.+ // Casing and whitespace must not change path geometry or drop a value.string[] allowed = step.Kind == "Arc" ? ["Radius", "Turn"] : ["Turn", "Heading", "Length", "To"];- var unknown = Regex.Matches(body ?? string.Empty, @"(?<![\w.])(?<n>[A-Za-z_]\w*)\s*:", RegexOptions.CultureInvariant)- .Select(m => m.Groups["n"].Value).FirstOrDefault(n => !allowed.Contains(n, StringComparer.Ordinal));+ var syntax = FirmamentSyntaxParser.Parse("Step PathStep {" + body + "}");+ var declaration = syntax.Document.Statements.OfType<DeclarationSyntax>().SingleOrDefault();+ if (!syntax.IsSuccess || declaration?.Body is null || declaration.Body.Statements.Any(s => s is not FieldSyntax))+ { diagnostic = prefix + ":expected-field-body"; return false; }+ var unknown = declaration.Body.Statements.OfType<FieldSyntax>().Select(f => f.Name.Text)+ .FirstOrDefault(n => !allowed.Any(a => FirmamentSyntaxFields.SameField(n, a)));if (unknown is not null) { diagnostic = $"concept-path-field-unknown:{path}:{step.Name}:{unknown}:allowed={string.Join(",", allowed)}"; return false; }+ var fieldDiagnostics = new List<string>(); var fields = new FirmamentSyntaxFields(declaration, fieldDiagnostics);+ boundFields = allowed.ToDictionary(n => n, n => fields.Take(n) is { } value ? FirmamentSyntaxWriter.Expression(value) : null);+ fields.Complete();+ if (fieldDiagnostics.Count > 0) { diagnostic = prefix + ":" + string.Join("; ", fieldDiagnostics); return false; }}- var turn = Property(body, "Turn"); var absolute = Property(body, "Heading"); var length = Property(body, "Length"); var to = Property(body, "To");+ string? Read(string name) => boundFields is null ? Property(body, name) : boundFields.GetValueOrDefault(name);+ var turn = Read("Turn"); var absolute = Read("Heading"); var length = Read("Length"); var to = Read("To");if (step.Kind is "Line" or "Span"){if (turn is not null && absolute is not null) { diagnostic = $"concept-path-turn-and-heading:{path}:{step.Name}"; return false; }@@ -779,7 +789,7 @@ public static class ProfileAuthoringParserif (!TrySemanticFeature(path, step, current, headingDegrees, out curves, out endpoint, out diagnostic)) return false;return true;}- var radiusText = Property(body, "Radius");+ var radiusText = Read("Radius");if (step.Kind != "Arc" || radiusText is null || turn is null || absolute is not null || length is not null || to is not null || !TryMeasure(radiusText, "mm", out var radius) || radius <= 0 || !TryMeasure(turn, "deg", out var sweepDegrees) || !double.IsFinite(sweepDegrees) || Math.Abs(sweepDegrees) <= Tolerance || Math.Abs(sweepDegrees) >= 360d - Tolerance){ diagnostic = $"concept-path-arc-invalid:{path}:{step.Name}"; return false; }var headingRadians = DegreesToRadians(headingDegrees); var sweepRadians = DegreesToRadians(sweepDegrees); var sign = Math.Sign(sweepRadians);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.csindex f97f4608..4978ad17 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.cs@@ -6,6 +6,25 @@ namespace Aetheris.Kernel.Firmament.FirmamentV2;[FirmamentField("Bounds", "Bounds", FirmamentSchemaValueKind.Box3, Description = "A semantic Box3 bound instead of Size.")]public static class BoxSemanticDeclaration { }+[FirmamentConstruct("Rib", "Rib", Context = "Modify Box top", Entry = "Rib<Rectangular> Stiffener { on: +Z; path: Layout.Guide; thickness: 3mm; height: 8mm; draft: 2deg }", Description = "Manual analytic reinforcement following a named line, arc or circle; integrated into the host.")]+[FirmamentField("On", "On", FirmamentSchemaValueKind.FaceSelector, Required = true, Description = "Qualified support face; currently +Z on direct Box stock.")]+[FirmamentField("Path", "Path", FirmamentSchemaValueKind.ConstructReference, Required = true, Description = "Named Concept line, arc, circle, or single-segment Path.")]+[FirmamentField("Thickness", "Thickness", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Required = true, Description = "Full thickness at the attachment plane; centered on the guide.")]+[FirmamentField("Height", "Height", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Required = true, Description = "Positive height above the support.")]+[FirmamentField("Draft", "Draft", FirmamentSchemaValueKind.Angle, Unit = FirmamentUnitKind.Angle, Default = "0deg", Description = "Nonnegative side draft; positive angles narrow the top.")]+[FirmamentField("Ends", "Ends", FirmamentSchemaValueKind.Choice, Choices = ["Flat", "Round"], Default = "Flat", Description = "Open-guide end treatment. Round is admitted on straight guides; omit for closed guides.")]+public static class RibSemanticDeclaration { }++[FirmamentConstruct("Groove", "Groove", Context = "Modify Box top or cylindrical wall", Entry = "Groove<Semicircular> Channel { on: +Z; path: Layout.Guide; radius: 2mm }", Description = "Analytic rectangular or semicircular local channel; leaves positive material beneath the cut.")]+[FirmamentField("On", "On", FirmamentSchemaValueKind.FaceSelector, Required = true, Description = "Qualified support face.")]+[FirmamentField("Path", "Path", FirmamentSchemaValueKind.ConstructReference, Required = true, Description = "Named Concept line, arc, circle, or single-segment Path.")]+[FirmamentField("Width", "Width", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Variants = ["Rectangular"], Description = "Rectangular opening width, centered on the guide.")]+[FirmamentField("Depth", "Depth", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Variants = ["Rectangular"], Description = "Positive rectangular removal depth into the host.")]+[FirmamentField("Radius", "Radius", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Variants = ["Semicircular"], Description = "Semicircle radius; opening width is twice radius and depth equals radius.")]+[FirmamentField("Ends", "Ends", FirmamentSchemaValueKind.Choice, Choices = ["Flat", "Round"], Default = "Flat", Description = "Open-guide end treatment; omit for closed guides.")]+[FirmamentField("Station", "Station", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Description = "Axial station for a qualified circumferential cylindrical groove.")]+public static class GrooveSemanticDeclaration { }+[FirmamentConstruct("Ellipsoid", "Ellipsoid", Context = "Model or Struct", Entry = "Ellipsoid Body { radii: [18mm, 12mm, 25mm] }", Description = "Exact centered ellipsoid; radii are local X/Y/Z semiaxes.")][FirmamentField("Radii", "Radii", FirmamentSchemaValueKind.Vector, Unit = FirmamentUnitKind.Length, Required = true, Description = "Three positive X/Y/Z semiaxes, not diameters.")]public static class EllipsoidSemanticDeclaration { }diff --git a/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs b/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.csindex ad97cde3..6cd5f76d 100644--- a/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs+++ b/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs@@ -7,7 +7,7 @@ using Aetheris.Semantics;namespace Aetheris.Kernel.Firmament.Materializer;/// <summary>Stable roles assigned while an authoritative plan is materialized. These are not geometric queries.</summary>-public enum SemanticTopologyRole { Unknown, ProfileVertex, VerticalExtrusionEdge, LocalStartBoundary, LocalEndBoundary, LocalStartCapLoop, LocalEndCapLoop, TopBoundary, BottomBoundary, ExtrusionSideFace, TopFaceBoundaryLoop, BottomFaceBoundaryLoop, HoleEntryLoop, HoleExitLoop, HoleWallFace, HoleShaftToDrillPointLoop, HoleShaftToDrillPointEdge, HoleDrillPointFace, HoleTipVertex, HoleCounterboreMouthLoop, HoleCounterboreWallFace, HoleCounterboreShoulderLoop, HoleCounterboreShaftWallFace, SlotEntryLoop, SlotExitLoop, SlotWallFace, SlotStraightWallFace, SlotEndWallFace, ComposeTransition, EdgeFinishReplacementFace, FilletSurface, ConvexJunctionPatch, ReflexJunctionPatch, CapContactEdge, SideContactEdge, JunctionToRollA, JunctionToRollB, JunctionCapContact, JunctionSideAContact, JunctionSideBContact, StartTerminationFace, EndTerminationFace, StartEndpointArc, EndEndpointArc, RetainedStartSharpEdge, RetainedEndSharpEdge, BoxFace, BoxEdge, ThreadRootFace, ThreadLeadingFlank, ThreadTrailingFlank, ThreadCrest, ThreadStartCap, ThreadEndCap, ThreadBoundaryEdge, HoleCountersinkWallFace }+public enum SemanticTopologyRole { Unknown, ProfileVertex, VerticalExtrusionEdge, LocalStartBoundary, LocalEndBoundary, LocalStartCapLoop, LocalEndCapLoop, TopBoundary, BottomBoundary, ExtrusionSideFace, TopFaceBoundaryLoop, BottomFaceBoundaryLoop, HoleEntryLoop, HoleExitLoop, HoleWallFace, HoleShaftToDrillPointLoop, HoleShaftToDrillPointEdge, HoleDrillPointFace, HoleTipVertex, HoleCounterboreMouthLoop, HoleCounterboreWallFace, HoleCounterboreShoulderLoop, HoleCounterboreShaftWallFace, SlotEntryLoop, SlotExitLoop, SlotWallFace, SlotStraightWallFace, SlotEndWallFace, ComposeTransition, EdgeFinishReplacementFace, FilletSurface, ConvexJunctionPatch, ReflexJunctionPatch, CapContactEdge, SideContactEdge, JunctionToRollA, JunctionToRollB, JunctionCapContact, JunctionSideAContact, JunctionSideBContact, StartTerminationFace, EndTerminationFace, StartEndpointArc, EndEndpointArc, RetainedStartSharpEdge, RetainedEndSharpEdge, BoxFace, BoxEdge, ThreadRootFace, ThreadLeadingFlank, ThreadTrailingFlank, ThreadCrest, ThreadStartCap, ThreadEndCap, ThreadBoundaryEdge, HoleCountersinkWallFace, PathFeatureFace }public enum SemanticTopologyAddressability { AuthoredStable, DerivedStable, ImportedStable, RuntimeOnly, Ambiguous, Unstable }public enum SemanticSelectionRequirement { ExactlyOne, OneOrMore, ConnectedChain, ClosedLoop, NonEmptyFaceSet }public enum SemanticSelectionFailure { None, SemanticSourceNotFound, NoMaterializedDescendants, AmbiguousBodyContext, SelectionCardinalityMismatch, DescendantsNotConnected, DescendantsBranch, DescendantsDoNotClose, MixedBoundaryRoles, UnsupportedTopologyChange, SelectionConsumerMismatch }diff --git a/docs/development/implementation/ruled-tooling-a0-inline-step-probe-harness.md b/docs/development/implementation/ruled-tooling-a0-inline-step-probe-harness.mdindex ba32277b..b8f83718 100644--- a/docs/development/implementation/ruled-tooling-a0-inline-step-probe-harness.md+++ b/docs/development/implementation/ruled-tooling-a0-inline-step-probe-harness.md@@ -4,6 +4,14 @@`tools/Run-RuledStepProbe.ps1` is a tooling only harness for ruled and swept STEP experiments. It does not add Firmament syntax, geometry support, AIR nodes, or production routing.+Current admission requires a closed solid for this production round trip. The+historical `ellipse-linear-extrusion-production.step` is actually an open surface+with four boundary edges; it remains inspectable and now correctly rejects+canonical solid export. For a closed witness, first build+`fixtures/Canonical/Boundary2/closed-ellipse-extrusion.firmament` into an ignored+local STEP file, then pass that STEP to the harness. The open probe is retained+as regression evidence rather than edited to disguise its missing closure.+The harness lets a small STEP probe travel through a real Aetheris round trip:```textdiff --git a/docs/development/reports/2026-10/manual-ribs-and-grooves.md b/docs/development/reports/2026-10/manual-ribs-and-grooves.mdnew file mode 100644index 00000000..0fec5d3d--- /dev/null+++ b/docs/development/reports/2026-10/manual-ribs-and-grooves.md@@ -0,0 +1,143 @@+# Manual ribs and bounded grooves++Date: 2026-10-27++## Result++Manual `Rib<Rectangular>` and `Groove<Rectangular|Semicircular>` consume named+Concept guides or one-segment Paths through the unified mechanical AST owner.+The compiler constructs one integrated exact boundary and uses enforced+production STEP export. Validate uses that same construction path.++The old surface-feature descriptors and evidence generator were planning+scaffolds, explicitly claiming no materialization. They are not used as evidence+that the new features work. PlasticShell AutoRib remains unchanged; manual+placement and geometry qualification precede any expansion of automated network+selection.++## Geometry and admission++- Box-top bands follow lines, circular arcs and circles. Rectangular ribs have+ explicit base thickness, height and nonnegative narrowing side draft.+- Rectangular channels have exact planar/cylindrical sides and planar floors.+ Semicircular channels use cylinders or tori; rounded straight ends use spheres.+- Circumferential grooves replace cylindrical bands with shoulders/floor or a+ toroidal meridian, on solid shafts and top-open hollow cylinders. Inner grooves+ cut outward into the wall. The original stock radius, height, base and cavity+ floor remain construction authority.+- Shared topology replaces the support footprint. No overlapping rib solids,+ general Boolean tools, faceted geometry or spline support approximations are+ emitted. Optional STEP UV data may use non-rational polynomial pcurves.+- Construction receipts, named feature identities, source spans, guide+ references and topology descendants survive materialization. The engineering+ inventory uses the existing report contract.+- Dimensions, wall/floor margins, draft collapse, missing/ambiguous guides,+ unknown fields, unsupported frames and unsupported feature combinations+ reject. Planar bounding-box disjointness is a conservative admission proof;+ it is deliberately reported as a missing junction plan rather than falsely+ asserting that every rejected pair intersects.++## Existing Path debt repaired++Scalar serialization exposed two pre-existing assumptions in the Path owner:+literal-only unit-whitespace matching for Start/Heading, and PascalCase-only+step fields. Header values and simple Line/Span/Arc fields now use the existing+AST dimensional and closed-field readers. No new regular expression, document+dispatch, expression evaluator or global source rewrite was added.++Tighter material-effect witnesses also caught a pre-existing exact-volume+recognizer which accepted any nine-face box/cylinder arrangement as a convex+quarter-cylinder fillet. It now requires outward convex support, quarter-circle+end trims and the actual stock-corner cylinder placement. A concave semicircular+channel explicitly rejects that exact recognizer. The same witnesses caught+and corrected the new Flat-ended semicircular channel's end-cap normals.+The effect tolerance is relative to the feature volume, so an omitted small+channel cannot hide inside a large stock-volume allowance.++Circle guides consume the existing ClosedBoundary2 typed dimensions after+lowering erases their original surface syntax. Qualifiers are checked against+authored Concept members. Duplicate guide names are explicitly unqualified;+the legacy leaf-name guide dictionary is not allowed to silently choose one.+The same refusal covers duplicate Point2 dependencies across Concept Structs:+a qualified line must not capture another layout's Start/End coordinates.++Repeated full qualification exposed a fixture-reader race: one CLI regression+created and deleted temporary mutation files under the canonical source tree+while another enumerated it. Those self-contained generated specimens now live+under ignored artifacts/local, fixing the creating owner rather than weakening+the corpus reader or suppressing missing-file errors.++## Qualification++Persistent core witnesses cover twelve planar combinations and six rotational+combinations, closed/orientation-consistent topology, analytic support families,+strict export, reimport, and independent volume comparison. Additional core+negatives cover failed dimensions, collapsed draft, support escape, lost floors+and overlapping cuts.++Frontend tests cover real admission/build agreement, all fixture families,+scalar parameters, single-segment Paths, source locations, unknown fields,+unsupported frames/sections, mixed channel sections and name stability after+manual rib reordering. The fixtures are under+`fixtures/Canonical/Features/PathFeatures/`. Raw generated evidence defaults to+ignored `artifacts/local/path-feature-*`.++Final evidence against the completed implementation:++- Complete Release solution build: zero errors, 37 warnings.+- Core fast lane: 1,164 passed.+- Complete solution regression: 6,279 passed, zero failed, two skipped, twenty+ test assemblies. The skips require an optional external PDF renderer.+- Core suite includes all twenty-three new path-feature geometry/negative cases;+ frontend coverage includes twenty-two path-feature cases. The focused schema+ and feature lane passed all thirty-four cases.+- All six canonical fixtures passed real CLI validate, build and output analyze.+ STEP artifacts and JSON evidence are in artifacts/local/path-features.+- Rebuilt managed/WASM browser SDK and passed all nineteen JavaScript SDK tests.+- Existing canonical/interchange tests passed without refreshing any geometry+ baselines during this pass. Only the schema inventory gained the two admitted+ construct names.+- Dedicated quality review checked closed field ownership, scoped guide capture,+ feature accounting, geometric end-cap orientation, material-effect tolerances,+ compatibility, source locations, and generated-file placement. No parser+ routes, diagnostic-code allowlists or regular expressions were added.+- Git diff whitespace checks passed; no task-owned .NET/test hosts remained.++Real CLI dogfooding also ran `measure --sdf --error 5 --compare-mesh` on the manual+rib. Geometry builds, but authoritative volume is explicitly unavailable: this+new composite construction does not retain a qualified CIR field and is outside+the existing exact volume recognizers. Topology and the numerical mesh comparison+remain available. The compiler does not promote the planned volume delta or mesh+estimate into assertion authority. Qualifying the composite CIR/volume witness+is a separate measurement integration boundary, recorded rather than patched+with a misleading primitive-parity flag.++## Deliberate limits and next ownership boundary++This is manual construction, not injection-molding certification. The existing+AutoRib zero-draft warning and specialized standoff-network limits remain true.+No automatic rib placement, base blends or sink/warpage guarantee is implied.++Planar hosts are direct Box tops; cylindrical hosts are direct stock or top-open+hollow cylinders without bottom blends. Other Box faces, Extrude/Compose,+imported supports, compound/branching paths, overlapping/nested envelopes and+combination with Hole/EdgeFinish/Perforation/Thread remain explicit refusals.+Open arcs require Flat ends and positive sweeps no greater than 180 degrees.++The next geometric prerequisite for broader manual/automatic rib networks is an+authoritative footprint-junction arrangement that joins rib intersections and+retains named descendants. That belongs in the material arrangement owner,+before AutoRib selects among candidate networks. Ordinary selector dispatch and+analytic construction here require no judgment scoring.++Public behavior and examples:+[grooves and manual ribs](../../../public/firmament/grooves-and-ribs.md).++## Verdict++**Success within the documented manual-feature boundary.** Named ribs with side+draft and both requested groove sections construct integrated analytic solids,+survive strict STEP round trips and agree between validate/build. Unsupported+hosts, guide arrangements and feature combinations reject explicitly. AutoRib+automation, public named rib-face selectors and composite SDF/volume authority+remain separate, disclosed follow-up boundaries.diff --git a/docs/development/reports/2026-10/pmi-import-export-admission.md b/docs/development/reports/2026-10/pmi-import-export-admission.mdnew file mode 100644index 00000000..bd741e62--- /dev/null+++ b/docs/development/reports/2026-10/pmi-import-export-admission.md@@ -0,0 +1,145 @@+# Import-tolerant, export-strict PMI admission++Date: 2026-10-27++## Decision and implementation++A source-integrity pin identifies bytes; it does not select an editing policy.+Unchanged `InlineStep` annotation/re-export now uses the existing trusted+production exporter with enforced output preflight. It no longer requires the+importer's aggregate `GeometryStatus` to be `Qualified`.++| Boundary | Required evidence |+|---|---|+| Import/inspection | Retain geometry and report actual recovery/qualification; do not promote incomplete evidence |+| Exact Firmament part import | Explicit exact-BRep lane; no automatic tessellation/approximation fallback |+| Unchanged part plus PMI | Source receipt; unchanged topology, 3D supports/curves, edge trims, face bindings and vertices; proved PMI correspondence |+| Production export | Binding integrity, imported shell enclosure, canonical representation and enforced 3D boundary preflight |+| Optional UV traces | Independently validated set; otherwise omit it with `step-export-recovered-pcurves-omitted` |+| Trim-dependent editing | Existing operation-specific complete-trim/geometry guards remain in place |++Physical consistency allowance is capped at 0.1 mm on this imported-part route.+No recovery threshold was increased and manufacturing tolerances are not used as+healing allowances. Source qualification remains visible and is not relabeled as+complete after UV omission. Optional UV changes are excluded from the unchanged+PMI witness; its engineering topology, geometry and associations remain checked.++`TrustedProductionRoute` now defaults to `Enforce`. The low-level `LegacyRoute`+retains its compatibility/debug audit default; it is not the policy selected by+normal unchanged Firmament import/export. Explicit diagnostic overrides remain+available. Production normalization also uses physical boundary and shell+evidence instead of demanding complete UV recovery before or after normalization.++Representation policy remains analytic first, then admitted exact/bounded+non-rational geometry. Intentional polynomial B-splines remain supported. The+only rational product projection exception is a native ellipsoid's exact STEP+patches. Arbitrary rational geometry cannot bypass this policy through auxiliary+PMI dependencies. Geometry-changing normalization still cannot bypass the PMI+body witness.++## Actual geometry defects found by enforcing the boundary++The first strict run admitted thirteen exact NIST specimens and exposed three+existing representation defects. These were repaired before qualification:++- **FTC-07 and FTC-10:** an `EDGE_CURVE` can trim a B-spline through its vertices+ without a `TRIMMED_CURVE` wrapper. Import previously assigned the entire basis+ domain. Examples failed endpoint consistency by approximately 0.358/0.595 mm+ and 0.244 mm. Import now infers a bounded endpoint inverse, accepts a measured+ unique candidate within 0.000001 mm, and retains the original interval when it+ cannot resolve one. Explicit parameter trims are never overridden. The spline+ control net and topology vertices are unchanged.+- **STC-10:** the polynomial evaluator returned the last control point at every+ domain end. That is incorrect for non-clamped/periodic splines; the observed+ endpoint error was about 1.457 mm. Position and derivative evaluation now use+ the existing de Boor basis at the boundary. A separate uniform-basis test+ checks position, tangent, second derivative, rational unit-weight agreement+ and continuity at the domain end.++Strict output still rejects an inconsistent physical boundary. An invalid+optional UV trace can be omitted while preserving its source body's PMI. Tests+exercise both outcomes through the actual exporter.++Full qualification additionally exposed a historical canonical-box fixture whose+top cap listed reversed directed edges in forward order. Import now repairs only+a uniquely determined directed vertex cycle, preserving every edge, vertex,+coedge identity and edge sense. Ambiguous branches or disconnected components+are not guessed or stitched. Recovery is disclosed by+`step-import-loop-order-recovered`; the original STEP fixture is unchanged.++The historical ruled "production" probe is an open face with four boundary+edges. Its old success expectation is corrected to inspection success and solid+export refusal. A separate closed elliptical extrusion fixture qualifies the+positive workflow. `canon` now uses exact import, strict production export and+semantic PMI transfer in both metadata modes; deterministic headers are not an+audit bypass. Canonicalization warnings survive JSON/text presentation.++## Compatibility and baseline changes++The original NIST corpus still has sixteen exact successes and the explicitly+unsupported FTC-08 e1-tg input. Exactly three canonical serialization hashes were+updated after the endpoint repairs:++| Specimen | Previous SHA-256 | Corrected SHA-256 |+|---|---|---|+| FTC-07 e2 | `e2642cad595fb2ead2e3947f7a36fb7bba9b2deff1228ece9516c9fd73ad32ab` | `ea03b61c119b5b72c369a5b879cded916df4eece654a612fa3641845192060a7` |+| FTC-10 e2 | `0a8a7d4b2139e3c7974472a2db1b328ac5a8a75869dee7e869139d96dfb16d58` | `eff9d4990ed0509a2105389cfa785c9ba253a69ff0f7f1f2b8c2bfe4c07b73b5` |+| STC-10 e2 | `12f19eb86e1c02791a83fe1a75cb89920e5638f96ce09dce9816e1338d04ec8a` | `b3fefea3aa7068984fa1e2beb809b3bfe8ebb9176a913ac967b2e9101a57319b` |++All other fields in those frozen reports are unchanged: success status,+diagnostics, source sizes, and vertex/edge/face counts. The remaining fourteen+reports were not refreshed. These are explicit corrections to boundary+interpretation, not blanket baseline regeneration or an assertion that every+previously emitted byte is unchanged.++FTC-11's former invalid fixture is now the buildable+[`nist-ftc11-passthrough.firmament`](../../../../fixtures/Canonical/PMI/nist-ftc11-passthrough.firmament),+with retained source PMI and an added control. The old refusal expectation is+replaced by a real compiler test that preserves the source qualification and+requires strict output admission.++## Qualification++Persistent coverage includes all seventeen NIST inputs through source loading,+pin verification and the actual Firmament compiler; all sixteen exact inputs+through strict core PMI export; native ellipsoid rational projection; rational+auxiliary-PMI rejection; invalid physical boundaries; and invalid optional UV+data with unchanged semantic PMI. Original semantic round-trip and topology+correspondence tests remain in place.++Generated evidence and logs are in ignored+`artifacts/local/pmi-admission-audit/`. Public behavior is documented in+[STEP import](../../../public/firmament/step-import.md) and+[PMI](../../../public/firmament/pmi.md).++Final qualification against the frozen implementation:++- Complete solution Release build: zero errors, 38 warnings.+- Core fast lane: 1,141 passed.+- Complete solution regression: 6,234 passed, zero failed, two skipped across+ twenty test assemblies. The skips are optional external PDF rasterization+ tests requiring `AETHERIS_TEST_PDFTOPPM`.+- Rebuilt managed/WASM SDK; all nineteen JavaScript SDK tests passed.+- Fresh CLI corpus run: sixteen inputs passed `validate`, `build` and output+ analysis with semantic PMI retained. FTC-08 e1-tg remained an exact-geometry+ admission refusal, also reproduced with `geometryOnly`.+- Focused compatibility checks covered the repaired canonical box, explicit+ open-surface refusal, closed elliptical solid, and PMI preservation in both+ canonicalization metadata modes.+- `git diff --check` passed. No task-owned .NET runtime processes remained after+ qualification.++## Verdict and remaining limits++**Success for unchanged exact part import, PMI and strict re-export.** The+sixteen-part NIST capability is available through the normal compiler path,+without relabeling incomplete UV recovery as complete or weakening physical+boundary rejection. Unsupported FTC-08 is still explicit. Three serialization+changes repair documented source interpretation defects; accepted output is not+claimed byte-identical to the previous faulty boundary interpretation.++This does not qualify arbitrary imported-body edits or migration of PMI through+topology changes. Those retain their operation-specific guards. The preflight+reports its own bounded coverage; it is not a proof of every geometric property.+Legacy audit APIs remain available for compatibility and diagnosis. Product+Firmament imports and `canon` select the enforced production path explicitly.diff --git a/docs/development/reports/2026-10/pmi-passthrough-and-explicit-gdt.md b/docs/development/reports/2026-10/pmi-passthrough-and-explicit-gdt.mdindex 5005a68a..70f3d28b 100644--- a/docs/development/reports/2026-10/pmi-passthrough-and-explicit-gdt.md+++ b/docs/development/reports/2026-10/pmi-passthrough-and-explicit-gdt.md@@ -2,6 +2,10 @@Date: 2026-10-27+The import-admission results and integration gap below describe the state before+the subsequent guard repair. See [import-tolerant, export-strict admission](pmi-import-export-admission.md)+for the implementation, endpoint corrections and current qualification.+## Behavior and ownershipAn unchanged single-solid `InlineStep` now carries its semantic AP242 annotation@@ -77,12 +81,45 @@ admitted source, and compares rejected files against explicit geometry-onlyadmission. Existing geometry refusals are classified separately from PMI transferfailures. Tessellated-only source is not silently treated as an exact solid.-### NIST results through the real CLI+### Pinned InlineStep results through the real CLI++**Correction: this is a different gate from the established NIST import/export+corpus, which remains 16 exact successes out of 17, with FTC-08 e1-tg explicitly+unsupported. These numbers must not be presented as a fall from 16/17 to 5/17.**++The existing corpus checks import success, BRep binding validation and STEP+export against its frozen reports/hashes. Pinned `InlineStep` additionally+requires `ImportQualification.GeometryStatus == Qualified`. That guard predates+the PMI change: commit `8a747eee3`, October 21. A source-integrity pin therefore+also selects a stricter geometry admission policy. The PMI runner pinned every+file and requested a 0.1 mm pcurve qualification budget.The run covers all 17 stored specimens. Five pass validation, build and analysis;the remaining twelve reproduce the existing geometry admission refusal with`geometryOnly: true` as well. There are no PMI-specific admission failures orvalidate/build disagreements in this run.+Of those twelve refusals, eleven are exact parts that still pass the original+import/export gate; the remaining file is the known tessellated-only specimen.+The eleven exact parts have missing or invalid recovered face-local pcurves,+and two also have ambiguous orientation qualification. These are concrete trim+certification gaps, not evidence that the PMI change damaged their 3D geometry.++The follow-up audit reran `Step242NistAuditHarnessTests`: **21 passed**, including+the original per-file snapshot comparisons. At the same 0.1 mm policy used by the+PMI runner, a direct import/binding/export comparison confirmed all sixteen exact+files still succeed. For example, CTC-02 has nine missing pcurves and a reported+0.52959 mm UV-loop closure gap; FTC-11 has zero missing pcurves but fails recovered+UV-loop closure checks (one reported gap is 0.61073 mm). Increasing the tolerance+or suppressing the diagnostics would not establish correctness.++The integration issue is operation admission: unchanged geometry plus PMI is+currently held to the same complete-trim certification guard as pinned editing.+The next repair should qualify unchanged annotation/re-export against the existing+import/export evidence and source/body/association witnesses, while retaining the+stronger trim/orientation requirements for operations that actually depend on+them. No recovery guard or production admission rule was changed by this audit.+Evidence: `artifacts/local/pmi-admission-audit/comparison.json` and+`artifacts/local/pmi-nist-existing-gate.log`.| Specimen | Normal compilation | Datums / dimensions / controls ||---|---|---|@@ -155,11 +192,13 @@ No new Firmament parser route, source rewrite system, geometric constraint solveor native dependency was introduced. Source semantic readback, authoring admissionand emission share the existing AP242/PMI owners and the common control registry.-**Success for the bounded capability.** Semantic transfer and explicit GD&T work-through normal compilation for admitted geometry, with precision and association-evidence. Remaining NIST geometry admission refusals, advanced presentation,-topology-edit rebinding and assembly-wide transfer are explicit limits rather-than successful-looking omissions.+**Core transfer and explicit authoring are qualified; pinned-import integration+is incomplete for eleven otherwise importable exact NIST parts.** The original+16/17 corpus remains intact. The five pinned InlineStep successes do not establish+end-to-end coverage of all sixteen exact specimens. This operation-policy gap+must be resolved explicitly rather than dismissed as unrelated geometry failure.+Advanced presentation, topology-edit rebinding and assembly-wide transfer remain+separate declared limits.## Referencesdiff --git a/docs/public/firmament/grooves-and-ribs.md b/docs/public/firmament/grooves-and-ribs.mdnew file mode 100644index 00000000..e896f0ab--- /dev/null+++ b/docs/public/firmament/grooves-and-ribs.md@@ -0,0 +1,141 @@+# Grooves and manual ribs++Use named Concept guides or Paths to locate a channel or reinforcing rib. The+guide retains layout intent; the feature supplies its section and dimensions.+Both features produce one integrated analytic body, rather than overlapping+tool solids.++## Manual rib++This complete example is+[manual-rib.firmament](../../../fixtures/Canonical/Features/PathFeatures/manual-rib.firmament):++```firmament+Model ManuallyRibbedPlate {+ units: mm+ Concept Struct Layout on XY {+ Point2 Start { position: [-18mm, 0mm] }+ Point2 End { position: [18mm, 0mm] }+ Line2 Spine { from: Start; to: End }+ }+ Box Plate { size: [60mm, 40mm, 6mm] }+ Modify Plate {+ Rib<Rectangular> Stiffener {+ on: face(Plate.Top)+ path: Layout.Spine+ thickness: 3mm+ height: 10mm+ draft: 2deg+ ends: Round+ }+ }+}+```++`Rib` adds material to an existing host. It does not run AutoRib, relocate a guide,+or select a reinforcement network.++- `path` names a line, circular arc, circle, or a Path resolving to one such+ segment. Guide coordinates are XY coordinates local to the support.+- `thickness` is the full base thickness, centered on the guide.+- `height` is measured outward from the support.+- `draft` defaults to `0deg`. Positive draft narrows both sides toward the top:+ top thickness = base thickness − 2 × height × tan(draft).+- `ends` defaults to `Flat`. Straight guides also admit `Round`, giving+ semicircular ends in plan. Flat end planes remain at the guide endpoints:+ side draft does not shorten the guide. Flat end faces therefore have zero+ end draft, even when the band sides have positive draft.+- A closed circular guide has no ends; omit the field.++For a rounded straight rib, the guide endpoints are the centers of its rounded+ends. Overall length is guide length plus thickness at the relevant height.+An [arc rib](../../../fixtures/Canonical/Features/PathFeatures/arc-rib.firmament)+uses exact conical sides when drafted.++## Plate channels and circular face grooves++[plate-channels.firmament](../../../fixtures/Canonical/Features/PathFeatures/plate-channels.firmament)+contains two separate straight channels. Inside `Modify Plate`, write:++```firmament+Groove<Rectangular> Channel {+ on: +Z+ path: Upper+ width: 4mm+ depth: 2mm+ ends: Round+}+```++`Groove<Rectangular>` removes a centered band of the specified width and depth.+`Groove<Semicircular>` takes `radius` instead: opening width is twice the radius+and depth equals the radius. Supplying independent width/depth to a semicircle+is rejected.++For Round-ended straight channels, guide endpoints are cap centers: the opening+extends by half its width beyond each end.++A straight semicircular channel has a cylindrical bottom and, with Round ends,+spherical end patches. A circular or arc channel has a toroidal bottom.+[plate-seal-groove.firmament](../../../fixtures/Canonical/Features/PathFeatures/plate-seal-groove.firmament)+demonstrates a circular face groove.++## Cylindrical grooves++[shaft-seal-groove.firmament](../../../fixtures/Canonical/Features/PathFeatures/shaft-seal-groove.firmament)+declares a coaxial Circle2 with the shaft radius, then uses:++```firmament+Modify Shaft {+ Groove<Rectangular> SealSeat {+ on: face(Shaft.OuterWall)+ path: Layout.Seal+ station: 20mm+ width: 4mm+ depth: 2mm+ }+}+```++`station` is the axial center measured from the stock base (Z = 0). Width is+axial; depth is radial into material. `OuterWall` cuts inward, and `InnerWall`+cuts outward. The latter requires a top-open `Cylinder<Hollow>` host; its guide+circle radius equals the inner radius. See+[bore-seal-groove.firmament](../../../fixtures/Canonical/Features/PathFeatures/bore-seal-groove.firmament).+Both rectangular and semicircular sections are supported. The cut must leave+positive wall and axial end margins.++These constructs define geometry. An O-ring gland's squeeze, fill, clearances,+material compatibility and pressure suitability require separate engineering+requirements; a groove is not an automatic seal-design approval.++## Current limits++- Planar ribs/channels require a direct Box's top support (`+Z`, `Top` or+ `face(Body.Top)`). Other faces, Extrude/Compose and imported-body hosts reject.+- Cylindrical grooves require coaxial full circles on a direct Cylinder or+ top-open `Cylinder<Hollow>`, with no bottom blend. Cylindrical ribs,+ axial/helical cylinder channels and arbitrary surface paths reject.+- Open arcs require Flat ends and a positive sweep of at most 180 degrees.+ Compound Paths, corners, branch networks and arbitrary sections reject.+- Planar footprints must remain strictly inside the support. Multiple features+ require disjoint XY bounding boxes, a conservative admission rule: some+ nonintersecting nested or diagonal arrangements are therefore rejected too.+ Cylindrical groove axial envelopes must be disjoint.+- Combining these features with Hole, EdgeFinish, Perforation or Thread in the+ same body is not yet admitted. No requested operation is silently dropped.+- A rib top may not collapse under draft; a groove must leave positive material.+ No base fillet, molding-release certification or automatic rib placement is+ implied. Existing PlasticShell AutoRib retains its separate qualified limits.+- Construction points and guides must have unique names, including across+ Concept Struct scopes. Non-XY construction frames are+ rejected for these support-local feature consumers.+- Feature names and source provenance are retained. This does not introduce+ public selectors such as `face(Stiffener.Top)`.+- Authoritative volume assertions and SDF measurement are not yet qualified for+ these composite bodies. The CLI reports that limitation; topology inspection+ and explicitly numerical mesh comparisons remain available.++Related: [Profiles and construction](../reference/language/profiles.md),+[material offsets](material-offsets.md), [PlasticShell](plastic-shell.md),+and [solids and features](../reference/language/solids-and-features.md).diff --git a/docs/public/firmament/plastic-shell.md b/docs/public/firmament/plastic-shell.mdindex a12b084f..8fde5ffa 100644--- a/docs/public/firmament/plastic-shell.md+++ b/docs/public/firmament/plastic-shell.md@@ -11,6 +11,11 @@ Unknown network names reject instead of having no effect.`PlasticShell` is Aetheris's manufacturing-first domain for injection-molded product definitions. Wall thickness, tooling direction, parting, and reinforcement intent live in the domain model rather than as a sequence of cleanup features.+For explicitly placed reinforcement on mechanical Box stock, use+[manual ribs](grooves-and-ribs.md). That feature consumes an authored guide,+thickness, height and optional draft. It is separate from this domain's AutoRib+network selection and does not expand AutoRib's qualified geometry.+```firmamentPlasticShell EnclosureHalf {Exterior: Frustumdiff --git a/docs/public/firmament/pmi.md b/docs/public/firmament/pmi.mdindex d1c56530..68e58fe1 100644--- a/docs/public/firmament/pmi.md+++ b/docs/public/firmament/pmi.md@@ -95,9 +95,15 @@ auxiliary PMI pcurves also reject when their parameter domains cannot be provedsafe to normalize. Geometry-only editing of annotated imports still requiresexplicit `geometryOnly: true`; source-PMI migration through topology edits isnot admitted.-PMI transfer does not relax geometry admission: a file with unqualified imported-trims still rejects normal compilation, even if its annotation graph can be-transferred by the lower-level interchange API.+Unchanged annotation/re-export uses strict output admission: valid topology and+bindings, closed imported shells, canonical geometry and 3D boundary consistency.+A source hash proves identity; it does not require complete UV reconstruction.+Unqualified optional UV traces are omitted with a diagnostic, while the emitted+STEP retains its 3D edge curves, vertices and face associations. Source recovery+status remains inspectable and is not promoted to fully qualified.+Geometry edits which depend on reconstructed trims still require those trims to+be qualified. A physical boundary contradiction or unsupported normalization+rejects export, including when `geometryOnly: true` is requested.`geometryOnly: true` explicitly excludes source PMI and reports that exclusion;it never modifies the original STEP file. Imported assembly-wide PMI anddiff --git a/docs/public/firmament/sculpting.md b/docs/public/firmament/sculpting.mdindex 8c6ced80..24e2d2b8 100644--- a/docs/public/firmament/sculpting.md+++ b/docs/public/firmament/sculpting.md@@ -304,7 +304,7 @@ The housing lane verifies:**Aetheris does not use NURBS as its universal surface abstraction.**-Internal algorithms may temporarily use rational spline mathematics, but exported product geometry must normalize to analytic or non-rational forms. The export order is exact analytic surface, exact or explicitly bounded non-rational B-spline, then a blocking diagnostic. Arbitrary rational NURBS fallback is prohibited. The diagnostic is `surf-surface-export-normalization-failed`.+Internal algorithms may temporarily use rational spline mathematics, but exported product geometry must normalize to analytic or non-rational forms. The export order is exact analytic surface, exact or explicitly bounded non-rational B-spline, then a blocking diagnostic. Arbitrary rational NURBS fallback is prohibited. The diagnostic is `surf-surface-export-normalization-failed`. The [native ellipsoid primitive](geometry.md) has a separate exact rational STEP projection; this is not a freeform sculpting fallback.The base housing emits only `PLANE` and `CYLINDRICAL_SURFACE`. The patch-replacement example adds one `B_SPLINE_SURFACE_WITH_KNOTS` with no rational complex entity. A final STEP scan must report `RationalNURBS = 0`; otherwise export fails.diff --git a/docs/public/firmament/step-import.md b/docs/public/firmament/step-import.mdindex 99cde3bd..a8ab3082 100644--- a/docs/public/firmament/step-import.md+++ b/docs/public/firmament/step-import.md@@ -77,6 +77,26 @@ For bound geometry, `pcurveQualification` reports the face-edge use count, sourc`summary.importQualification` distinguishes `Qualified`, `Inspectable`, `Degraded`, and `Failed` from authoritative BRep evidence. Parser/API success means geometry was retained; it is not a qualification verdict. `status` and `geometryStatus` report engineering qualification independently of the viewport. `displayStatus` separately reports `NotAssessed`, `Complete`, `RefinementLimited`, or `Partial`, with display reasons and missing face identities. Missing trim bindings remain `Inspectable`; detected invalid trims or incomplete intended solid shells are `Degraded` even when a useful preview is complete. Exact faces can receive derived face-local pcurves without being classified as recovered geometry.+An unchanged `InlineStep` can be annotated and re-exported when strict production+output checks pass, even when optional UV recovery is incomplete. Source pins+prove the identity of the imported data; they do not select a stricter operation.+Export checks topology/bindings, imported shell enclosure, canonical representation+and 3D boundary consistency within the declared budget, capped at 0.1 mm. This is+a recovery allowance, not a machining tolerance. Invalid UV traces are omitted+with `step-export-recovered-pcurves-omitted`; STEP uses its 3D edge curves and+vertices to define those boundaries. The source qualification report is retained.+`Remove`/`Replace` operations that depend on face-local trims keep their own+qualified-trim requirements. Tessellated-only source cannot enter this exact+part path through an automatic approximation fallback.++`aetheris canon` applies the same strict geometry boundary in both metadata modes:+`deterministic` selects deterministic headers; `production` preserves source+metadata. Both retain supported semantic PMI and report exclusions or omitted UV+traces in JSON `diagnostics` and text warnings. Neither mode promotes an open+surface into a solid. Open inputs remain available to `analyze` and inspection.+The [closed ellipse extrusion](../../../fixtures/Canonical/Boundary2/closed-ellipse-extrusion.firmament)+is a complete source witness with analytic elliptical boundaries and planar caps.+Legacy AP203/AP214 import uses the same topology and geometry path. Viewport quality is chosen automatically from model scale and bounded adaptive sampling. Viewport triangles are disposable approximations: STEP export, topology selection, and engineering qualification consume BRep directly. A convincing preview cannot qualify invalid engineering geometry. The frozen 26-file McMaster corpus and the original closeout evidence are recorded in [STEP-LEGACY-CLOSEOUT-X2](../../development/reports/2026-10/STEP-LEGACY-CLOSEOUT-X2.md); the subsequent visual investigation and ball roundtrip repair are in [STEP-LEGACY-FINAL-X3](../../development/reports/2026-10/STEP-LEGACY-FINAL-X3.md). Vendor files and generated meshes stay local; the tracked manifest retains the X0 baseline metadata and outcomes.In Cadmata, expand **Surface / trim inspection** in the viewport. Compare **Surfaces only**, **BRep wire only**, **Translucent + BRep wire**, and **Face colors + BRep wire** without changing the camera. Red lines carry kernel edge identities; the wire and translucent views show them through surfaces. Select a patch from the list, or click a surface in an inspection view, to isolate its occurrence and face with the source STEP entity, support family, and boundary edges. STEP imports currently display BRep meshes, with no SDF field. These diagnostic controls change presentation only.@@ -85,7 +105,16 @@ Dense rectangular spline trims retain native parameter grid cells as the existinDense nonrectangular spline trims reuse that knot-aware grid to decompose the actual outer-minus-holes region into local polygons. Existing constrained ear clipping triangulates each region before bounded chord/normal refinement. Only convex intersections of already validated seed triangles may use an anchor fan; general polygons never use an averaged centre. Periodic charts are normalized upstream, and display subdivision retains the original face and occurrence identity for picking. Quality limits remain explicit in display diagnostics. See [STEP-TRIM-TRIANGULATION-X4](../../development/reports/2026-10/STEP-TRIM-TRIANGULATION-X4.md) for the corpus and product evidence.-Rational source supports may be evaluated and displayed. Production AP242 uses analytic or non-rational geometry, with bounded recovery on a copy of the imported BRep and independent trim validation. Ordinary imported parts can use an explicit recovery allowance of at most 0.1 mm; tighter source and application requirements still matter for small features. Recovery reports sampled deviation rather than claiming an exact mathematical error bound. Unsupported normalization fails explicitly. Display mesh quality never supplies export evidence.+Rational source supports may be evaluated and displayed. Production AP242 uses+analytic or non-rational geometry after bounded recovery and independent boundary+validation. Native ellipsoid octants are the explicit exception: their exact STEP+projection uses rational quadratic patches. Arbitrary rational NURBS fallback is+not admitted, including through auxiliary PMI geometry. Intentional polynomial+B-spline curves and surfaces remain supported. Ordinary imported parts can use an+explicit recovery allowance of at most 0.1 mm; tighter source and application+requirements still matter for small features. Recovery reports sampled deviation+rather than claiming an exact mathematical error bound. Unsupported normalization+fails explicitly. Display mesh quality never supplies export evidence.Firmament `inlineSTEP` consumes Aetheris-canonical AP242 on the bounded production path. Imported faces are selected by source entity identity, for example `body.face(#170)`, and recognized regions may supply stable semantic aliases. [`inline-step-cantilever.firmament`](../../../fixtures/Canonical/FEA/inline-step-cantilever.firmament) demonstrates FEA on a checked-in canonical STEP resource.diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex 2953994d..916a35fd 100644--- a/docs/public/firmament/syntax.md+++ b/docs/public/firmament/syntax.md@@ -40,4 +40,5 @@ Model Plate {| Interfaces, mates, datums, motion | [Assemblies and motion](../reference/language/assemblies-and-motion.md) || `Assert`, `measure`, stack-ups | [Checks and measurement](../reference/language/checks.md) || Explicit GD&T, datum precedence, metric PMI passthrough | [Semantic PMI](pmi.md) |+| Named channels, seal grooves and drafted manual ribs | [Grooves and ribs](grooves-and-ribs.md) || Older V1 forms | [Reading older source](../reference/language/compatibility.md) |diff --git a/docs/public/reference/language/solids-and-features.md b/docs/public/reference/language/solids-and-features.mdindex 1dd84760..179e7516 100644--- a/docs/public/reference/language/solids-and-features.md+++ b/docs/public/reference/language/solids-and-features.md@@ -34,7 +34,8 @@ different construction.## Modify`Modify name { ... }` applies features to an existing body: holes, edge finishes,-patterns. `Modify Base {}` with no features is a valid no-op, as long as `Base`+patterns, [grooves and manual ribs](../../firmament/grooves-and-ribs.md).+`Modify Base {}` with no features is a valid no-op, as long as `Base`exists.On a single `Extrude`, Modify takes the same features as on a `Compose` body:@@ -44,7 +45,9 @@ Cylinder stock; on Extrude and Compose bodies it rejects at its declaration(use a `Pattern` of holes for a grid of openings).Angular mold `Draft` is not currently a V2 `Modify` feature. Its bounded legacy-operation does not imply support on the modern authoring path.+operation does not imply support on the modern authoring path. Manual+`Rib<Rectangular>` accepts its own explicit side `draft` while constructing the+rib; that is separate from drafting existing body faces.## Composediff --git a/fixtures/Canonical/Boundary2/closed-ellipse-extrusion.firmament b/fixtures/Canonical/Boundary2/closed-ellipse-extrusion.firmamentnew file mode 100644index 00000000..1ba7a37d--- /dev/null+++ b/fixtures/Canonical/Boundary2/closed-ellipse-extrusion.firmament@@ -0,0 +1,6 @@+Model ClosedEllipseExtrusion {+ units: mm+ Ellipse2 Outline { center: [0mm, 0mm] axisLengths: [8mm, 4mm] }+ Profile Section { Loop Outer { Outline |> TraceLoop } }+ Struct Part { Extrude Solid { profile: Section from: 0mm to: 5mm } }+}diff --git a/fixtures/Canonical/Features/PathFeatures/arc-rib.firmament b/fixtures/Canonical/Features/PathFeatures/arc-rib.firmamentnew file mode 100644index 00000000..52c70240--- /dev/null+++ b/fixtures/Canonical/Features/PathFeatures/arc-rib.firmament@@ -0,0 +1,20 @@+Model CurvedStiffener {+ units: mm+ Concept Struct Layout on XY {+ Point2 Center { position: [0mm, 0mm] }+ Point2 Start { position: [12mm, 0mm] }+ Point2 End { position: [0mm, 12mm] }+ Arc2 Spine { center: Center; from: Start; to: End }+ }+ Box Plate { size: [50mm, 40mm, 6mm] }+ Modify Plate {+ Rib<Rectangular> Stiffener {+ on: +Z+ path: Layout.Spine+ thickness: 3mm+ height: 8mm+ draft: 2deg+ ends: Flat+ }+ }+}diff --git a/fixtures/Canonical/Features/PathFeatures/bore-seal-groove.firmament b/fixtures/Canonical/Features/PathFeatures/bore-seal-groove.firmamentnew file mode 100644index 00000000..6079aaa5--- /dev/null+++ b/fixtures/Canonical/Features/PathFeatures/bore-seal-groove.firmament@@ -0,0 +1,20 @@+Model GroovedBore {+ units: mm+ Concept Struct Layout on XY {+ Circle2 Seal { center: [0mm, 0mm]; radius: 10mm }+ }+ Cylinder<Hollow> Cup {+ radius: 15mm+ height: 40mm+ wallThickness: 5mm+ openings: [Top]+ }+ Modify Cup {+ Groove<Semicircular> SealSeat {+ on: face(Cup.InnerWall)+ path: Layout.Seal+ station: 20mm+ radius: 2mm+ }+ }+}diff --git a/fixtures/Canonical/Features/PathFeatures/manual-rib.firmament b/fixtures/Canonical/Features/PathFeatures/manual-rib.firmamentnew file mode 100644index 00000000..09585d68--- /dev/null+++ b/fixtures/Canonical/Features/PathFeatures/manual-rib.firmament@@ -0,0 +1,19 @@+Model ManuallyRibbedPlate {+ units: mm+ Concept Struct Layout on XY {+ Point2 Start { position: [-18mm, 0mm] }+ Point2 End { position: [18mm, 0mm] }+ Line2 Spine { from: Start; to: End }+ }+ Box Plate { size: [60mm, 40mm, 6mm] }+ Modify Plate {+ Rib<Rectangular> Stiffener {+ on: face(Plate.Top)+ path: Layout.Spine+ thickness: 3mm+ height: 10mm+ draft: 2deg+ ends: Round+ }+ }+}diff --git a/fixtures/Canonical/Features/PathFeatures/plate-channels.firmament b/fixtures/Canonical/Features/PathFeatures/plate-channels.firmamentnew file mode 100644index 00000000..59154681--- /dev/null+++ b/fixtures/Canonical/Features/PathFeatures/plate-channels.firmament@@ -0,0 +1,21 @@+Model PlateChannels {+ units: mm+ Box Plate { size: [60mm, 40mm, 8mm] }+ Path Upper { start: Point2(-18mm, 8mm); heading: 0deg; Line RunA { length: 36mm } }+ Path Lower { start: Point2(-18mm, -8mm); heading: 0deg; Line RunB { length: 36mm } }+ Modify Plate {+ Groove<Rectangular> FlatBottom {+ on: +Z+ path: Upper+ width: 4mm+ depth: 2mm+ ends: Round+ }+ Groove<Semicircular> RoundBottom {+ on: +Z+ path: Lower+ radius: 2mm+ ends: Round+ }+ }+}diff --git a/fixtures/Canonical/Features/PathFeatures/plate-seal-groove.firmament b/fixtures/Canonical/Features/PathFeatures/plate-seal-groove.firmamentnew file mode 100644index 00000000..f8638d99--- /dev/null+++ b/fixtures/Canonical/Features/PathFeatures/plate-seal-groove.firmament@@ -0,0 +1,14 @@+Model FaceSealPlate {+ units: mm+ Concept Struct Layout on XY {+ Circle2 Seal { center: [0mm, 0mm]; radius: 12mm }+ }+ Box Plate { size: [50mm, 40mm, 8mm] }+ Modify Plate {+ Groove<Semicircular> SealSeat {+ on: +Z+ path: Layout.Seal+ radius: 1.5mm+ }+ }+}diff --git a/fixtures/Canonical/Features/PathFeatures/shaft-seal-groove.firmament b/fixtures/Canonical/Features/PathFeatures/shaft-seal-groove.firmamentnew file mode 100644index 00000000..86cba8f8--- /dev/null+++ b/fixtures/Canonical/Features/PathFeatures/shaft-seal-groove.firmament@@ -0,0 +1,16 @@+Model GroovedShaft {+ units: mm+ Concept Struct Layout on XY {+ Circle2 Seal { center: [0mm, 0mm]; radius: 15mm }+ }+ Cylinder Shaft { radius: 15mm; height: 40mm }+ Modify Shaft {+ Groove<Rectangular> SealSeat {+ on: face(Shaft.OuterWall)+ path: Layout.Seal+ station: 20mm+ width: 4mm+ depth: 2mm+ }+ }+}diff --git a/fixtures/Invalid/InlineStep/nist-ftc11-pmi-unqualified-geometry.invalid.firmfixture b/fixtures/Canonical/PMI/nist-ftc11-passthrough.firmamentsimilarity index 63%rename from fixtures/Invalid/InlineStep/nist-ftc11-pmi-unqualified-geometry.invalid.firmfixturerename to fixtures/Canonical/PMI/nist-ftc11-passthrough.firmamentindex a1fc4e42..9fed6232 100644--- a/fixtures/Invalid/InlineStep/nist-ftc11-pmi-unqualified-geometry.invalid.firmfixture+++ b/fixtures/Canonical/PMI/nist-ftc11-passthrough.firmament@@ -1,8 +1,5 @@-// fixture-id: nist-ftc11-pmi-unqualified-geometry-// validity: invalid-// expected: invalid-// expected-diagnostic: firmament-inline-step-import-unqualified-// The semantic graph transfers at the kernel API, but normal builds retain the existing trim-admission gate.+// Unchanged source PMI plus an explicit control; incomplete UV recovery is not+// complete-trim certification. Strict export must still prove the 3D boundary.Model AnnotatedNistPart {units: mmInlineStep Source {diff --git a/testdata/step242/manifests/nist.v0.report.json b/testdata/step242/manifests/nist.v0.report.jsonindex 9b9a3652..7ed62367 100644--- a/testdata/step242/manifests/nist.v0.report.json+++ b/testdata/step242/manifests/nist.v0.report.json@@ -137,7 +137,7 @@"edges": 865,"faces": 304},- "canonicalSha256": "e2642cad595fb2ead2e3947f7a36fb7bba9b2deff1228ece9516c9fd73ad32ab"+ "canonicalSha256": "ea03b61c119b5b72c369a5b879cded916df4eece654a612fa3641845192060a7"},{"fileId": "testdata_step242_nist_FTC_nist_ftc_08_asme1_ap242-e1-tg",@@ -217,7 +217,7 @@"edges": 799,"faces": 264},- "canonicalSha256": "0a8a7d4b2139e3c7974472a2db1b328ac5a8a75869dee7e869139d96dfb16d58"+ "canonicalSha256": "eff9d4990ed0509a2105389cfa785c9ba253a69ff0f7f1f2b8c2bfe4c07b73b5"},{"fileId": "testdata_step242_nist_FTC_nist_ftc_11_asme1_ap242-e2",@@ -337,6 +337,6 @@"edges": 551,"faces": 256},- "canonicalSha256": "12f19eb86e1c02791a83fe1a75cb89920e5638f96ce09dce9816e1338d04ec8a"+ "canonicalSha256": "b3fefea3aa7068984fa1e2beb809b3bfe8ebb9176a913ac967b2e9101a57319b"}]diff --git a/tools/Run-RuledStepProbe.ps1 b/tools/Run-RuledStepProbe.ps1index 34433cb7..df5afb82 100644--- a/tools/Run-RuledStepProbe.ps1+++ b/tools/Run-RuledStepProbe.ps1@@ -51,7 +51,7 @@ Copy-Item -LiteralPath $probePath -Destination $probeCopy -Force& dotnet run --project (Join-Path $repoRoot 'Aetheris.CLI') -- canon $probeCopy --out $canonicalInput --mode production --jsonif ($LASTEXITCODE -ne 0) {- throw "Canonicalization failed for ruled STEP probe '$probePath'."+ throw "Canonicalization failed for ruled STEP probe '$probePath'. See the CLI diagnostics. Open surface probes remain inspection inputs and cannot be promoted into production solids."}$relativeInput = "../input/$([System.IO.Path]::GetFileName($canonicalInput))"