Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Preserve BRep topology and analytic edge trims during STEP export

Yuechen Libc0f99e131c5
diff --git a/Aetheris.CLI.Tests/ChamferM6FixturePipelineTests.cs b/Aetheris.CLI.Tests/ChamferM6FixturePipelineTests.cs
index 18c9322e..2a6bf4cf 100644
--- a/Aetheris.CLI.Tests/ChamferM6FixturePipelineTests.cs
+++ b/Aetheris.CLI.Tests/ChamferM6FixturePipelineTests.cs
@@ -30,7 +30,8 @@ public sealed class ChamferM6FixturePipelineTests
var imported = Step242Importer.ImportBody(File.ReadAllText(first.StepPath, Encoding.UTF8));
Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(d => d.Message)));
- Assert.Equal(6, imported.Value.Topology.Vertices.Count());
+ // Periodic rims share seam vertices after the producer topology repair.
+ Assert.Equal(3, imported.Value.Topology.Vertices.Count());
Assert.Equal(5, imported.Value.Topology.Edges.Count());
Assert.Equal(4, imported.Value.Topology.Faces.Count());
Assert.Equal(1, imported.Value.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Cylinder));
diff --git a/Aetheris.CLI.Tests/LocalizedPlanarSingleEdgeChamferPipelineTests.cs b/Aetheris.CLI.Tests/LocalizedPlanarSingleEdgeChamferPipelineTests.cs
new file mode 100644
index 00000000..4999277b
--- /dev/null
+++ b/Aetheris.CLI.Tests/LocalizedPlanarSingleEdgeChamferPipelineTests.cs
@@ -0,0 +1,110 @@
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.CLI.Tests;
+
+/// <summary>Real parser/export/reimport evidence for AIR-CHAMFER-LOCALIZED-PLAN-A1.</summary>
+public sealed class LocalizedPlanarSingleEdgeChamferPipelineTests
+{
+ [Theory]
+ [InlineData(10d, 8d, 6d, 1d)]
+ [InlineData(10d, 8d, 6d, 2d)]
+ [InlineData(12d, 5d, 7d, 1d)]
+ public void LocalizedPlanarReplacement_ExportsRealSingleEdgeChamfer(double width, double depth, double height, double distance)
+ {
+ var first = Run(Source(width, depth, height, distance));
+ var second = Run(Source(width, depth, height, distance));
+ Assert.Equal(0, first.Exit);
+ Assert.Equal(0, second.Exit);
+ using var json = JsonDocument.Parse(first.Output);
+ var air = json.RootElement.GetProperty("air");
+ Assert.Equal("SharedEdge(+X,+Z)", air.GetProperty("feature").GetProperty("selection").GetString());
+ Assert.Equal("LocalizedPlanarReplacement", air.GetProperty("construction").GetProperty("kind").GetString());
+ Assert.Equal("ExplicitOwnedEndpoints", air.GetProperty("construction").GetProperty("splitPolicy").GetString());
+ Assert.True(air.GetProperty("bRepPlan").GetProperty("authoritative").GetBoolean());
+ Assert.Equal("LocalizedPlanarReplacement", air.GetProperty("bRepPlan").GetProperty("planKind").GetString());
+ Assert.Equal("AirLocalizedPlanarSingleEdgeChamfer", air.GetProperty("materialization").GetProperty("route").GetString());
+ Assert.False(air.GetProperty("materialization").GetProperty("legacyFallback").GetBoolean());
+ Assert.True(air.GetProperty("step").GetProperty("reimportSucceeded").GetBoolean());
+ var localized = air.GetProperty("localizedChamfer");
+ Assert.Equal("Direct", localized.GetProperty("selectionMode").GetString());
+ Assert.Equal(2, localized.GetProperty("retainedFaces").GetInt32());
+ Assert.Equal(1, localized.GetProperty("replacementFaces").GetInt32());
+ Assert.Equal("valid", localized.GetProperty("preflight").GetString());
+
+ var stepPath = json.RootElement.GetProperty("outputPath").GetString()!;
+ var bytes = File.ReadAllBytes(stepPath);
+ Assert.Equal(Convert.ToHexString(SHA256.HashData(bytes)), Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(JsonDocument.Parse(second.Output).RootElement.GetProperty("outputPath").GetString()!))));
+ var imported = Step242Importer.ImportBody(Encoding.UTF8.GetString(bytes));
+ Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(d => d.Message)));
+ var body = imported.Value;
+ Assert.Equal(10, body.Topology.Vertices.Count());
+ Assert.Equal(15, body.Topology.Edges.Count());
+ Assert.Equal(7, body.Topology.Faces.Count());
+ Assert.Equal(7, body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Plane));
+ var points = body.Topology.Vertices.Select(v => body.TryGetVertexPoint(v.Id, out var p) ? p : throw new InvalidOperationException()).ToArray();
+ Assert.Contains(points, p => Math.Abs(p.X - width / 2d) < 1e-9 && Math.Abs(p.Z - (height / 2d - distance)) < 1e-9);
+ Assert.Contains(points, p => Math.Abs(p.X - (width / 2d - distance)) < 1e-9 && Math.Abs(p.Z - height / 2d) < 1e-9);
+ Assert.Equal(-width / 2d, points.Min(p => p.X), 9);
+ Assert.Equal(width / 2d, points.Max(p => p.X), 9);
+ Assert.Equal(-height / 2d, points.Min(p => p.Z), 9);
+ Assert.Equal(height / 2d, points.Max(p => p.Z), 9);
+ }
+
+ [Theory]
+ [InlineData(0d, "+X", "SharedEdgePlusZ", "localized-chamfer-distance-must-be-positive")]
+ [InlineData(6d, "+X", "SharedEdgePlusZ", "localized-chamfer-distance-too-large")]
+ [InlineData(1d, "+Z", "SharedEdgePlusZ", "air-chamfer-unsupported-selection-rejected")]
+ [InlineData(1d, "+X", "SharedEdgePlusY", "air-chamfer-unsupported-face-rejected")]
+ public void LocalizedPlanarReplacement_InvalidInput_FailsBeforeExport(double distance, string face, string target, string expected)
+ {
+ var run = Run(Source(10, 8, 6, distance, face, target));
+ Assert.Equal(1, run.Exit);
+ Assert.Contains(expected, run.Output, StringComparison.Ordinal);
+ Assert.DoesNotContain("legacyFallback\":true", run.Output, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void LocalizedPlanarReplacement_TwoEdgeJunction_RequiresExplicitConstructionWitness()
+ {
+ var run = Run("""
+ Model Localized mm
+ Box Base { Size: [10mm, 8mm, 6mm] }
+ Modify Base {
+ EdgeFinish First { Face: +X Target: SharedEdgePlusZ Kind: Chamfer Distance: 1mm }
+ EdgeFinish Second { Face: +Y Target: SharedEdgePlusZ Kind: Chamfer Distance: 1mm }
+ }
+ """);
+ Assert.Equal(1, run.Exit);
+ Assert.Contains("localized-chamfer-construction-witness-required:two-edge-junction", run.Output, StringComparison.Ordinal);
+ }
+
+ private static (int Exit, string Output) Run(string source)
+ {
+ var dir = Path.Combine(Path.GetTempPath(), "aetheris-localized-plan", Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(dir);
+ var sourcePath = Path.Combine(dir, "case.firmament");
+ var stepPath = Path.Combine(dir, "case.step");
+ File.WriteAllText(sourcePath, source);
+ var output = new StringWriter();
+ var error = new StringWriter();
+ var exit = Aetheris.CLI.CliRunner.Run(["build", sourcePath, "--out", stepPath, "--json"], output, error);
+ return (exit, output + error.ToString());
+ }
+
+ private static string Source(double width, double depth, double height, double distance, string face = "+X", string target = "SharedEdgePlusZ") => $$"""
+ Model Localized mm
+ Box Base { Size: [{{width}}mm, {{depth}}mm, {{height}}mm] }
+ Modify Base {
+ EdgeFinish Break {
+ Face: {{face}}
+ Target: {{target}}
+ Kind: Chamfer
+ Distance: {{distance}}mm
+ }
+ }
+ """;
+}
diff --git a/Aetheris.CLI.Tests/LocalizedTangentBlendFilletPipelineTests.cs b/Aetheris.CLI.Tests/LocalizedTangentBlendFilletPipelineTests.cs
new file mode 100644
index 00000000..cad89e01
--- /dev/null
+++ b/Aetheris.CLI.Tests/LocalizedTangentBlendFilletPipelineTests.cs
@@ -0,0 +1,112 @@
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.CLI.Tests;
+
+/// <summary>Real parser/export/reimport evidence for AIR-FILLET-LOCALIZED-M1.</summary>
+public sealed class LocalizedTangentBlendFilletPipelineTests
+{
+ [Theory]
+ [InlineData(10d, 8d, 6d, 1d)]
+ [InlineData(10d, 8d, 6d, 2d)]
+ [InlineData(12d, 5d, 7d, 1d)]
+ public void LocalizedTangentBlend_ExportsExactSingleEdgeFillet(double width, double depth, double height, double radius)
+ {
+ var first = Run(Source(width, depth, height, radius));
+ var second = Run(Source(width, depth, height, radius));
+ Assert.Equal(0, first.Exit);
+ Assert.Equal(0, second.Exit);
+ using var json = JsonDocument.Parse(first.Output);
+ var air = json.RootElement.GetProperty("air");
+ Assert.Equal("Fillet", air.GetProperty("feature").GetProperty("kind").GetString());
+ Assert.Equal("LocalizedTangentBlend", air.GetProperty("construction").GetProperty("kind").GetString());
+ Assert.Equal("LocalizedTangentBlend", air.GetProperty("bRepPlan").GetProperty("planKind").GetString());
+ Assert.Equal("AirLocalizedTangentBlendSingleEdgeFillet", air.GetProperty("materialization").GetProperty("route").GetString());
+ Assert.False(air.GetProperty("materialization").GetProperty("legacyFallback").GetBoolean());
+ var localized = air.GetProperty("localizedFillet");
+ Assert.Equal("QuarterCircle", localized.GetProperty("profile").GetString());
+ Assert.Equal("Linear", localized.GetProperty("sweep").GetString());
+ Assert.Equal("Direct", localized.GetProperty("selectionMode").GetString());
+ Assert.Equal(2, localized.GetProperty("retainedFaces").GetInt32());
+ Assert.Equal(1, localized.GetProperty("replacementFaces").GetInt32());
+ Assert.Equal("valid", localized.GetProperty("preflight").GetString());
+ Assert.True(air.GetProperty("step").GetProperty("reimportSucceeded").GetBoolean());
+
+ var stepPath = json.RootElement.GetProperty("outputPath").GetString()!;
+ var bytes = File.ReadAllBytes(stepPath);
+ Assert.Contains("TRIMMED_CURVE", Encoding.UTF8.GetString(bytes), StringComparison.Ordinal);
+ Assert.Equal(Convert.ToHexString(SHA256.HashData(bytes)), Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(JsonDocument.Parse(second.Output).RootElement.GetProperty("outputPath").GetString()!))));
+ var imported = Step242Importer.ImportBody(Encoding.UTF8.GetString(bytes));
+ Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(d => d.Message)));
+ var body = imported.Value;
+ Assert.Equal(10, body.Topology.Vertices.Count());
+ Assert.Equal(15, body.Topology.Edges.Count());
+ Assert.Equal(7, body.Topology.Faces.Count());
+ Assert.Equal(6, body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Plane));
+ var cylinder = Assert.Single(body.Geometry.Surfaces, s => s.Value.Kind == SurfaceGeometryKind.Cylinder).Value.Cylinder!.Value;
+ Assert.Equal(radius, cylinder.Radius, 9);
+ Assert.Equal(0, cylinder.Axis.X, 9); Assert.Equal(1, cylinder.Axis.Y, 9); Assert.Equal(0, cylinder.Axis.Z, 9);
+ var points = body.Topology.Vertices.Select(v => body.TryGetVertexPoint(v.Id, out var p) ? p : throw new InvalidOperationException()).ToArray();
+ Assert.Contains(points, p => Math.Abs(p.X - width / 2d) < 1e-9 && Math.Abs(p.Z - (height / 2d - radius)) < 1e-9);
+ Assert.Contains(points, p => Math.Abs(p.X - (width / 2d - radius)) < 1e-9 && Math.Abs(p.Z - height / 2d) < 1e-9);
+
+ // Removed corner area = R² - πR²/4: the square setback less the retained quarter-disc.
+ var removedArea = radius * radius * (1d - Math.PI / 4d);
+ Assert.True(removedArea > 0d);
+ }
+
+ [Theory]
+ [InlineData(0d, "+X", "SharedEdgePlusZ", "localized-fillet-radius-must-be-positive")]
+ [InlineData(6d, "+X", "SharedEdgePlusZ", "localized-fillet-radius-too-large")]
+ [InlineData(1d, "+Z", "SharedEdgePlusZ", "localized-fillet-unsupported-selection")]
+ [InlineData(1d, "+X", "SharedEdgePlusY", "localized-fillet-unsupported-selection")]
+ public void LocalizedTangentBlend_InvalidInput_FailsBeforeExport(double radius, string face, string target, string expected)
+ {
+ var run = Run(Source(10, 8, 6, radius, face, target));
+ Assert.Equal(1, run.Exit);
+ Assert.Contains(expected, run.Output, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void LocalizedTangentBlend_TwoEdgeJunction_RequiresExplicitConstructionWitness()
+ {
+ var run = Run("""
+ Model Localized mm
+ Box Base { Size: [10mm, 8mm, 6mm] }
+ Modify Base {
+ EdgeFinish First { Face: +X Target: SharedEdgePlusZ Kind: Fillet Distance: 1mm }
+ EdgeFinish Second { Face: +Y Target: SharedEdgePlusZ Kind: Fillet Distance: 1mm }
+ }
+ """);
+ Assert.Equal(1, run.Exit);
+ Assert.Contains("localized-fillet-construction-witness-required:two-edge-junction", run.Output, StringComparison.Ordinal);
+ }
+
+ private static (int Exit, string Output) Run(string source)
+ {
+ var dir = Path.Combine(Path.GetTempPath(), "aetheris-localized-fillet", Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(dir);
+ var sourcePath = Path.Combine(dir, "case.firmament");
+ var stepPath = Path.Combine(dir, "case.step");
+ File.WriteAllText(sourcePath, source);
+ var output = new StringWriter(); var error = new StringWriter();
+ var exit = Aetheris.CLI.CliRunner.Run(["build", sourcePath, "--out", stepPath, "--json"], output, error);
+ return (exit, output + error.ToString());
+ }
+
+ private static string Source(double width, double depth, double height, double radius, string face = "+X", string target = "SharedEdgePlusZ") => $$"""
+ Model Localized mm
+ Box Base { Size: [{{width}}mm, {{depth}}mm, {{height}}mm] }
+ Modify Base {
+ EdgeFinish RoundedEdge {
+ Face: {{face}}
+ Target: {{target}}
+ Kind: Fillet
+ Distance: {{radius}}mm
+ }
+ }
+ """;
+}
diff --git a/Aetheris.Kernel.Core.Tests/Air/ChamferCornerPolicyResolverTests.cs b/Aetheris.Kernel.Core.Tests/Air/ChamferCornerPolicyResolverTests.cs
new file mode 100644
index 00000000..e7653466
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Air/ChamferCornerPolicyResolverTests.cs
@@ -0,0 +1,127 @@
+using Aetheris.Kernel.Core.Air;
+using Aetheris.Kernel.Core.Air.BRepPlan;
+using Aetheris.Kernel.Core.Brep.Prismatic;
+
+namespace Aetheris.Kernel.Core.Tests.Air;
+
+public sealed class ChamferCornerPolicyResolverTests
+{
+ [Fact]
+ public void ClosedRectangularLoop_HasOneHardValidPolicy_AndSelectsDirectly()
+ {
+ var planned = AirTopFaceLoopChamferBRepPlanner.Plan(new PrismaticTopFaceLoopChamferRequest(10, 8, 6, 1));
+ Assert.True(planned.Succeeded);
+ var witness = new ChamferCornerConstructionWitness(
+ "corner-witness:top-loop:0",
+ "PrismaticSectionTransition",
+ ChamferCornerPolicy.SectionTransitionJunction,
+ planned.Plan!,
+ ChamferCornerSourceProvenance.GeneratedHistoryKnown);
+
+ var result = ChamferCornerPolicyResolver.Resolve(ValidContext(
+ topology: ChamferCornerTopologyKind.ClosedLoop,
+ incidentSelectedEdges: 2,
+ valence: 3,
+ witness: witness));
+
+ Assert.True(result.IsSuccess);
+ Assert.Equal(ChamferCornerPolicy.SectionTransitionJunction, result.Value!.Policy);
+ Assert.Equal(ChamferCornerSelectionMode.Direct, result.Value.SelectionMode);
+ var candidate = Assert.Single(result.Value.Candidates);
+ Assert.True(candidate.Admitted);
+ Assert.Null(candidate.UtilityScore);
+ Assert.Same(planned.Plan, result.Value.Witness.Plan);
+ Assert.True(result.Value.Witness.Plan.IsAuthoritative);
+ }
+
+ [Theory]
+ [InlineData(2, "PlanarEdgePairCut")]
+ [InlineData(3, "PlanarTriangularCut")]
+ public void ConvexJunction_LegacyGeometryWithoutAuthoritativePlan_IsNotModernAdmission(
+ int selectedEdges,
+ string expectedPolicy)
+ {
+ var result = ChamferCornerPolicyResolver.Resolve(ValidContext(
+ topology: ChamferCornerTopologyKind.Junction,
+ incidentSelectedEdges: selectedEdges,
+ valence: 3,
+ witness: null));
+
+ Assert.False(result.IsSuccess);
+ Assert.Equal(ChamferLoweringErrorKind.ConstructionWitnessRequired, result.Error!.Kind);
+ Assert.Equal("chamfer-corner-construction-witness-required:authoritative-brep-plan", result.Error.Code);
+ Assert.Contains(result.Error.Evidence!, value => value.Contains($"candidate={expectedPolicy}", StringComparison.Ordinal));
+ Assert.Contains(result.Error.Evidence!, value => value.Contains("MissingAuthoritativeBRepPlan", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void ConcaveTrihedralCorner_RequiresAnExplicitValidatedWitness()
+ {
+ var context = ValidContext(ChamferCornerTopologyKind.Junction, 3, 3, null) with
+ {
+ Convexity = ChamferCornerConvexity.Concave,
+ MaterialSide = ChamferCornerMaterialSide.RetainExterior,
+ SourceProvenance = ChamferCornerSourceProvenance.GeneratedHistoryKnown,
+ };
+
+ var result = ChamferCornerPolicyResolver.Resolve(context);
+
+ Assert.False(result.IsSuccess);
+ Assert.Equal(ChamferLoweringErrorKind.ConstructionWitnessRequired, result.Error!.Kind);
+ Assert.Contains(result.Error.Evidence!, value => value.Contains("candidate=ExplicitWitness", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void HardInvariantFailure_IsARejectionAndNeverAUtilityPenalty()
+ {
+ var planned = AirTopFaceLoopChamferBRepPlanner.Plan(new PrismaticTopFaceLoopChamferRequest(10, 8, 6, 1));
+ var witness = new ChamferCornerConstructionWitness("w", "PrismaticSectionTransition", ChamferCornerPolicy.SectionTransitionJunction, planned.Plan!, ChamferCornerSourceProvenance.GeneratedHistoryKnown);
+ var context = ValidContext(ChamferCornerTopologyKind.ClosedLoop, 2, 3, witness) with { NonSelfIntersecting = false };
+
+ var result = ChamferCornerPolicyResolver.Resolve(context);
+
+ Assert.False(result.IsSuccess);
+ Assert.Equal(ChamferLoweringErrorKind.SelfIntersection, result.Error!.Kind);
+ Assert.Contains(result.Error.Evidence!, value => value.Contains("failure=SelfIntersection", StringComparison.Ordinal));
+ Assert.DoesNotContain(result.Error.Evidence!, value => value.Contains("score", StringComparison.OrdinalIgnoreCase));
+ }
+
+ [Fact]
+ public void AsymmetricRule_IsHardRejected_NotUtilityRanked()
+ {
+ var planned = AirTopFaceLoopChamferBRepPlanner.Plan(new PrismaticTopFaceLoopChamferRequest(10, 8, 6, 1));
+ var witness = new ChamferCornerConstructionWitness("w", "PrismaticSectionTransition", ChamferCornerPolicy.SectionTransitionJunction, planned.Plan!, ChamferCornerSourceProvenance.GeneratedHistoryKnown);
+ var context = ValidContext(ChamferCornerTopologyKind.ClosedLoop, 2, 3, witness) with { Rule = ChamferCornerRule.Asymmetric };
+
+ var result = ChamferCornerPolicyResolver.Resolve(context);
+
+ Assert.False(result.IsSuccess);
+ Assert.Equal(ChamferLoweringErrorKind.UnsupportedSelection, result.Error!.Kind);
+ Assert.Contains(result.Error.Evidence!, value => value.Contains("failure=UnsupportedChamferRule", StringComparison.Ordinal));
+ }
+
+ private static ChamferCornerContext ValidContext(
+ ChamferCornerTopologyKind topology,
+ int incidentSelectedEdges,
+ int valence,
+ ChamferCornerConstructionWitness? witness) => new(
+ CornerId: "Corner0",
+ Convexity: ChamferCornerConvexity.Convex,
+ IncidentSelectedEdgeCount: incidentSelectedEdges,
+ VertexValence: valence,
+ SupportSurfaces: Enumerable.Repeat(ChamferCornerSupportSurfaceFamily.Plane, valence).ToArray(),
+ MaterialSide: ChamferCornerMaterialSide.RetainInterior,
+ Rule: ChamferCornerRule.UniformEqualDistance,
+ TopologyKind: topology,
+ HasConstructionHistory: true,
+ IsSymmetric: true,
+ SourceProvenance: ChamferCornerSourceProvenance.GeneratedHistoryKnown,
+ DistanceAdmissible: true,
+ NonSelfIntersecting: true,
+ HasClosedReplacementRegion: true,
+ HasRetainedRegionOwnership: true,
+ HasReplacementRegionOwnership: true,
+ PreservesManifoldTopology: true,
+ ExactConstructionAvailable: true,
+ AvailableWitness: witness);
+}
diff --git a/Aetheris.Kernel.Core.Tests/Brep/BrepExportPreflightTests.cs b/Aetheris.Kernel.Core.Tests/Brep/BrepExportPreflightTests.cs
new file mode 100644
index 00000000..48eff50f
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Brep/BrepExportPreflightTests.cs
@@ -0,0 +1,101 @@
+using Aetheris.Kernel.Core.Brep;
+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.Topology;
+using Aetheris.Kernel.Core.Step242;
+using Xunit;
+
+namespace Aetheris.Kernel.Core.Tests.Brep;
+
+public sealed class BrepExportPreflightTests
+{
+ private static readonly Direction3D Z = Direction3D.Create(new Vector3D(0, 0, 1));
+ private static readonly Direction3D X = Direction3D.Create(new Vector3D(1, 0, 0));
+
+ [Fact]
+ public void ValidPeriodicCircleSeam_IsAccepted()
+ {
+ var body = ClosedCircleBody(SurfaceGeometry.FromCylinder(new CylinderSurface(Point3D.Origin, Z, 2, X)), new Circle3Curve(Point3D.Origin, Z, 2, X));
+ Assert.True(BrepExportPreflight.Validate(body).IsValid);
+ }
+
+ [Theory]
+ [InlineData("plane")]
+ [InlineData("cylinder")]
+ [InlineData("cone")]
+ public void TrimOffAnalyticSupport_IsRejected(string family)
+ {
+ var body = family switch
+ {
+ "plane" => ClosedCircleBody(SurfaceGeometry.FromPlane(new PlaneSurface(Point3D.Origin, Z, X)), new Circle3Curve(new Point3D(0, 0, 1), Z, 2, X)),
+ "cylinder" => ClosedCircleBody(SurfaceGeometry.FromCylinder(new CylinderSurface(Point3D.Origin, Z, 2, X)), new Circle3Curve(Point3D.Origin, Z, 3, X)),
+ _ => ClosedCircleBody(SurfaceGeometry.FromCone(new ConeSurface(Point3D.Origin, Z, double.Pi / 4, X)), new Circle3Curve(new Point3D(0, 0, 2), Z, 3, X)),
+ };
+
+ var report = BrepExportPreflight.Validate(body);
+ Assert.False(report.IsValid);
+ Assert.Contains(report.Diagnostics, diagnostic =>
+ diagnostic.Code == "brep-preflight-trim-off-surface" &&
+ diagnostic.Classification == BrepExportPreflightFindingClassification.InvalidGeometry);
+ }
+
+ [Fact]
+ public void EnforcedExport_FailsBeforeStepSerialization_WithStructuredPreflightEvidence()
+ {
+ var body = ClosedCircleBody(
+ SurfaceGeometry.FromCone(new ConeSurface(Point3D.Origin, Z, double.Pi / 4, X)),
+ new Circle3Curve(new Point3D(0, 0, 2), Z, 3, X));
+
+ var export = Step242Exporter.ExportBody(body, new Step242ExportOptions { BrepExportPreflightMode = BrepExportPreflightMode.Enforce });
+ Assert.False(export.IsSuccess);
+ Assert.Contains(export.Diagnostics, diagnostic => diagnostic.Message.Contains("brep-preflight-trim-off-surface", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void DisconnectedLoop_IsClassifiedAsInvalidTopology()
+ {
+ var report = BrepExportPreflight.Validate(DisconnectedLoopBody());
+
+ Assert.Contains(report.Diagnostics, diagnostic =>
+ diagnostic.Code == "brep-preflight-coedge-disconnected" &&
+ diagnostic.Classification == BrepExportPreflightFindingClassification.InvalidTopology);
+ }
+
+ private static BrepBody ClosedCircleBody(SurfaceGeometry surface, Circle3Curve circle)
+ {
+ var topology = new TopologyModel();
+ var vertex = new VertexId(1); var edge = new EdgeId(1); var coedge = new CoedgeId(1); var loop = new LoopId(1); var face = new FaceId(1); var shell = new ShellId(1);
+ topology.AddVertex(new Vertex(vertex)); topology.AddEdge(new Edge(edge, vertex, vertex));
+ topology.AddCoedge(new Coedge(coedge, edge, loop, coedge, coedge, false)); topology.AddLoop(new Loop(loop, [coedge]));
+ topology.AddFace(new Face(face, [loop])); topology.AddShell(new Shell(shell, [face])); topology.AddBody(new Body(new BodyId(1), [shell]));
+ var geometry = new BrepGeometryStore(); geometry.AddCurve(new CurveGeometryId(1), CurveGeometry.FromCircle(circle)); geometry.AddSurface(new SurfaceGeometryId(1), surface);
+ var bindings = new BrepBindingModel(); bindings.AddEdgeBinding(new EdgeGeometryBinding(edge, new CurveGeometryId(1), new ParameterInterval(0, 2 * double.Pi))); bindings.AddFaceBinding(new FaceGeometryBinding(face, new SurfaceGeometryId(1)));
+ return new BrepBody(topology, geometry, bindings, new Dictionary<VertexId, Point3D> { [vertex] = circle.Evaluate(0) });
+ }
+
+ private static BrepBody DisconnectedLoopBody()
+ {
+ var topology = new TopologyModel();
+ var vertices = new[] { new VertexId(1), new VertexId(2), new VertexId(3), new VertexId(4) };
+ foreach (var vertex in vertices) topology.AddVertex(new Vertex(vertex));
+ topology.AddEdge(new Edge(new EdgeId(1), vertices[0], vertices[1]));
+ topology.AddEdge(new Edge(new EdgeId(2), vertices[2], vertices[3]));
+ topology.AddCoedge(new Coedge(new CoedgeId(1), new EdgeId(1), new LoopId(1), new CoedgeId(2), new CoedgeId(2), false));
+ topology.AddCoedge(new Coedge(new CoedgeId(2), new EdgeId(2), new LoopId(1), new CoedgeId(1), new CoedgeId(1), false));
+ topology.AddLoop(new Loop(new LoopId(1), [new CoedgeId(1), new CoedgeId(2)]));
+ topology.AddFace(new Face(new FaceId(1), [new LoopId(1)]));
+ topology.AddShell(new Shell(new ShellId(1), [new FaceId(1)]));
+ topology.AddBody(new Body(new BodyId(1), [new ShellId(1)]));
+ var geometry = new BrepGeometryStore();
+ geometry.AddCurve(new CurveGeometryId(1), CurveGeometry.FromLine(new Line3Curve(Point3D.Origin, X)));
+ geometry.AddCurve(new CurveGeometryId(2), CurveGeometry.FromLine(new Line3Curve(new Point3D(1, 1, 0), Direction3D.Create(new Vector3D(-1, 0, 0)))));
+ geometry.AddSurface(new SurfaceGeometryId(1), SurfaceGeometry.FromPlane(new PlaneSurface(Point3D.Origin, Z, X)));
+ var bindings = new BrepBindingModel();
+ bindings.AddEdgeBinding(new EdgeGeometryBinding(new EdgeId(1), new CurveGeometryId(1), new ParameterInterval(0, 1)));
+ bindings.AddEdgeBinding(new EdgeGeometryBinding(new EdgeId(2), new CurveGeometryId(2), new ParameterInterval(0, 1)));
+ bindings.AddFaceBinding(new FaceGeometryBinding(new FaceId(1), new SurfaceGeometryId(1)));
+ return new BrepBody(topology, geometry, bindings);
+ }
+}
diff --git a/Aetheris.Kernel.Core.Tests/Brep/EdgeFinishing/BrepBoundedChamferCornerStepEvidenceTests.cs b/Aetheris.Kernel.Core.Tests/Brep/EdgeFinishing/BrepBoundedChamferCornerStepEvidenceTests.cs
new file mode 100644
index 00000000..0b959c61
--- /dev/null
+++ b/Aetheris.Kernel.Core.Tests/Brep/EdgeFinishing/BrepBoundedChamferCornerStepEvidenceTests.cs
@@ -0,0 +1,81 @@
+using System.Security.Cryptography;
+using System.Text;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Brep.EdgeFinishing;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Kernel.Core.Tests.Brep.EdgeFinishing;
+
+public sealed class BrepBoundedChamferCornerStepEvidenceTests
+{
+ [Fact]
+ public void LegacySyntheticThreeEdgeConvexVertex_FailsEnforcedPreflight()
+ {
+ var result = BrepBoundedChamfer.ChamferAxisAlignedBoxSingleCorner(
+ new(-10, 10, -10, 10, -10, 10),
+ BrepBoundedChamferCorner.XMaxYMaxZMax,
+ 1);
+
+ Assert.True(result.IsSuccess, string.Join(Environment.NewLine, result.Diagnostics.Select(d => d.Message)));
+ Assert.Equal((10, 15, 7), (result.Value.Topology.Vertices.Count(), result.Value.Topology.Edges.Count(), result.Value.Topology.Faces.Count()));
+ var preflight = BrepExportPreflight.Validate(result.Value);
+ Assert.False(preflight.IsValid);
+ Assert.Contains(preflight.Diagnostics, diagnostic => diagnostic.Code == "brep-preflight-coedge-disconnected");
+ var exported = Step242Exporter.ExportBody(result.Value, new Step242ExportOptions
+ {
+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
+ });
+ Assert.False(exported.IsSuccess);
+ }
+
+ [Fact]
+ public void LegacyTwoEdgeConvexJunction_PassesAetherisRoundTrip_ButIsNotModernAdmission()
+ {
+ var source = BrepPrimitives.CreateBox(20, 20, 20);
+ Assert.True(source.IsSuccess);
+ var result = BrepBoundedChamfer.ChamferTrustedPolyhedralIncidentEdgePair(
+ source.Value,
+ new(BrepBoundedChamferCorner.XMaxYMaxZMax, BrepBoundedChamferCornerIncidentEdge.XNegative, BrepBoundedChamferCornerIncidentEdge.YNegative),
+ 1);
+
+ Assert.True(result.IsSuccess, string.Join(Environment.NewLine, result.Diagnostics.Select(d => d.Message)));
+ Assert.Equal((10, 15, 7), (result.Value.Topology.Vertices.Count(), result.Value.Topology.Edges.Count(), result.Value.Topology.Faces.Count()));
+ AssertRoundTrip(result.Value, 10, 15, 7, "legacy-two-edge-convex-junction.step");
+ }
+
+ [Fact]
+ public void LegacyThreeEdgeConvexVertex_PassesAetherisRoundTrip_ButIsNotModernAdmission()
+ {
+ var source = BrepPrimitives.CreateTriangularPrism(8, 6, 10);
+ Assert.True(source.IsSuccess);
+ var result = BrepBoundedChamfer.ChamferTrustedPolyhedralSingleCorner(source.Value, BrepBoundedChamferCorner.XMaxYMaxZMax, 1);
+
+ Assert.True(result.IsSuccess, string.Join(Environment.NewLine, result.Diagnostics.Select(d => d.Message)));
+ Assert.Equal((8, 12, 6), (result.Value.Topology.Vertices.Count(), result.Value.Topology.Edges.Count(), result.Value.Topology.Faces.Count()));
+ AssertRoundTrip(result.Value, 8, 12, 6, "legacy-three-edge-convex-vertex.step");
+ }
+
+ private static void AssertRoundTrip(BrepBody body, int vertices, int edges, int faces, string artifactName)
+ {
+ var preflight = BrepExportPreflight.Validate(body);
+ Assert.True(preflight.IsValid, string.Join(Environment.NewLine, preflight.Diagnostics.Select(d => d.Message)));
+ var exported = Step242Exporter.ExportBody(body, new Step242ExportOptions
+ {
+ ProductName = "AIR-CHAMFER-CORNER-POLICY-A0",
+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
+ });
+ Assert.True(exported.IsSuccess, string.Join(Environment.NewLine, exported.Diagnostics.Select(d => d.Message)));
+ Assert.NotEmpty(SHA256.HashData(Encoding.UTF8.GetBytes(exported.Value)));
+ var artifactDirectory = Environment.GetEnvironmentVariable("AETHERIS_CORNER_ARTIFACT_DIR");
+ if (!string.IsNullOrWhiteSpace(artifactDirectory))
+ {
+ Directory.CreateDirectory(artifactDirectory);
+ File.WriteAllText(Path.Combine(artifactDirectory, artifactName), exported.Value, Encoding.UTF8);
+ }
+ var imported = Step242Importer.ImportBody(exported.Value);
+ Assert.True(imported.IsSuccess, string.Join(Environment.NewLine, imported.Diagnostics.Select(d => d.Message)));
+ Assert.Equal((vertices, edges, faces), (imported.Value.Topology.Vertices.Count(), imported.Value.Topology.Edges.Count(), imported.Value.Topology.Faces.Count()));
+ }
+}
diff --git a/Aetheris.Kernel.Core/Air/AirBRepPlan.cs b/Aetheris.Kernel.Core/Air/AirBRepPlan.cs
index 5a284281..de5151f0 100644
--- a/Aetheris.Kernel.Core/Air/AirBRepPlan.cs
+++ b/Aetheris.Kernel.Core/Air/AirBRepPlan.cs
@@ -3,9 +3,9 @@ using Aetheris.Kernel.Core.Brep.Prismatic;
namespace Aetheris.Kernel.Core.Air.BRepPlan;
-internal enum AirBRepPlanKind { PrismaticSectionTransition, RevolvedProfile, Unsupported }
+internal enum AirBRepPlanKind { PrismaticSectionTransition, RevolvedProfile, LocalizedPlanarReplacement, LocalizedTangentBlend, Unsupported }
internal enum AirBRepPlanElementKind { Vertex, Curve, Edge, Coedge, Loop, Surface, Face, Shell, Body }
-internal enum AirBRepPlanRole { Unknown, SectionVertex, SectionEdge, VerticalTransitionEdge, SectionLoop, ProfileVertex, ProfileSegment, CircularRim, SeamEdge, CapFace, SideFace, CylindricalFace, ConicalTransitionFace, TransitionFace, PrismaticTransitionFace, ChamferFace, BodyShell, Body }
+internal enum AirBRepPlanRole { Unknown, SectionVertex, SectionEdge, VerticalTransitionEdge, SectionLoop, ProfileVertex, ProfileSegment, CircularRim, SeamEdge, CapFace, SideFace, CylindricalFace, ConicalTransitionFace, TransitionFace, PrismaticTransitionFace, ChamferFace, FilletFace, RetainedSupportFaceA, RetainedSupportFaceB, EndpointTransitionStart, EndpointTransitionEnd, UnaffectedFace, BodyShell, Body }
internal readonly record struct AirBRepPlanId(string Value)
{
@@ -76,9 +76,11 @@ internal sealed record AirBRepPlan(
IReadOnlyList<string> Guarantees,
AirBRepPlanFeatureContext? FeatureContext = null,
PrismaticSectionTransitionTopologyPlan? RealizationPlan = null,
- RevolvedProfileTopologyPlan? RevolvedRealizationPlan = null)
+ RevolvedProfileTopologyPlan? RevolvedRealizationPlan = null,
+ AirLocalizedPlanarReplacementTopologyPlan? LocalizedPlanarReplacementRealizationPlan = null,
+ AirLocalizedTangentBlendTopologyPlan? LocalizedTangentBlendRealizationPlan = null)
{
- public bool IsAuthoritative => RealizationPlan is not null || RevolvedRealizationPlan is not null;
+ public bool IsAuthoritative => RealizationPlan is not null || RevolvedRealizationPlan is not null || LocalizedPlanarReplacementRealizationPlan is not null || LocalizedTangentBlendRealizationPlan is not null;
}
internal sealed record AirBRepPlanResult(AirBRepPlan? Plan, AirBRepPlanValidationResult Validation)
diff --git a/Aetheris.Kernel.Core/Air/AirDeferredChamferLowerer.cs b/Aetheris.Kernel.Core/Air/AirDeferredChamferLowerer.cs
index 4a55b68a..5e863944 100644
--- a/Aetheris.Kernel.Core/Air/AirDeferredChamferLowerer.cs
+++ b/Aetheris.Kernel.Core/Air/AirDeferredChamferLowerer.cs
@@ -37,9 +37,9 @@ internal static class AirDeferredChamferLowerer
"chamfer-missing-construction-witness:localized-planar-replacement-not-implemented",
"A bounded support plane is insufficient without an authoritative retained/replacement region topology plan.", request),
AirDeferredChamferFamily.AdjacentEdgeJunction => Error(
- ChamferLoweringErrorKind.CornerPolicyRequired,
- "chamfer-corner-policy-required:multiple-valid-corner-patches",
- "The two edge strips admit multiple valid junction patches (miter, setback, or explicit corner face).", request),
+ ChamferLoweringErrorKind.ConstructionWitnessRequired,
+ "chamfer-corner-construction-witness-required:authoritative-brep-plan",
+ "The two edge strips do not yet own a hard-validated junction construction and authoritative BRepPlan; legacy miter/setback/patch alternatives are not proof of modern admissibility.", request),
_ => Error(ChamferLoweringErrorKind.UnsupportedJunction, "chamfer-unsupported-junction", "No bounded construction family is registered.", request),
};
}
diff --git a/Aetheris.Kernel.Core/Air/AirLocalizedPlanarReplacementChamferCompiler.cs b/Aetheris.Kernel.Core/Air/AirLocalizedPlanarReplacementChamferCompiler.cs
new file mode 100644
index 00000000..7a138c11
--- /dev/null
+++ b/Aetheris.Kernel.Core/Air/AirLocalizedPlanarReplacementChamferCompiler.cs
@@ -0,0 +1,170 @@
+using System.Security.Cryptography;
+using System.Text;
+using Aetheris.Kernel.Core.Air.BRepPlan;
+using Aetheris.Kernel.Core.Brep;
+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.Topology;
+
+namespace Aetheris.Kernel.Core.Air;
+
+/// <summary>Exact, finite witness for the admitted +X/+Z box edge only. It is deliberately
+/// geometry-first: the emitter receives this plan, rather than discovering topology from a body.</summary>
+internal sealed record AirLocalizedPlanarReplacementWitness(
+ string SupportPlaneA, string SupportPlaneB, Point3D EdgeStart, Point3D EdgeEnd,
+ IReadOnlyList<Point3D> RetainedSupportFaceA, IReadOnlyList<Point3D> RetainedSupportFaceB,
+ IReadOnlyList<Point3D> ReplacementChamfer, string MaterialSide, string EndpointPolicy);
+
+internal sealed record AirLocalizedPlanarReplacementTopologyPlan(
+ IReadOnlyList<Point3D> CrossSection, double MinY, double MaxY,
+ IReadOnlyList<string> FaceRoles, string DeterministicSignature)
+{
+ public int ExpectedVertexCount => CrossSection.Count * 2;
+ public int ExpectedEdgeCount => CrossSection.Count * 3;
+ public int ExpectedFaceCount => CrossSection.Count + 2;
+ public int ExpectedLoopCount => ExpectedFaceCount;
+ public int ExpectedCoedgeCount => 4 * CrossSection.Count + 2 * CrossSection.Count;
+}
+
+internal sealed record AirLocalizedPlanarReplacementConstruction(
+ string ConstructionId, string SourceFeatureId, AirLocalizedPlanarReplacementWitness Witness,
+ AirLocalizedPlanarReplacementTopologyPlan TopologyPlan);
+
+internal sealed record AirLocalizedPlanarReplacementChamferCompileRequest(
+ string BodyId, string FeatureId, string FeatureName, double Width, double Depth, double Height,
+ string FaceA, string FaceB, string Kind, double Distance, AirSourceSpan SourceSpan, bool HistoryKnown = true);
+
+internal sealed record AirLocalizedPlanarReplacementChamferCompileResult(
+ bool Succeeded, AirChamferFeature Feature, AirLocalizedPlanarReplacementConstruction? Construction,
+ AirBRepPlan? BRepPlan, BrepBody? Body, ChamferLoweringError? Error, IReadOnlyList<string> Diagnostics)
+{
+ public const string ProductionRoute = "AirLocalizedPlanarSingleEdgeChamfer";
+}
+
+internal static class AirLocalizedPlanarReplacementChamferCompiler
+{
+ private const double Tol = 1e-9;
+
+ public static AirLocalizedPlanarReplacementChamferCompileResult Compile(AirLocalizedPlanarReplacementChamferCompileRequest input)
+ {
+ var lowered = Lower(input);
+ var feature = Feature(input, lowered.Error);
+ if (!lowered.IsSuccess) return new(false, feature, null, null, null, lowered.Error, [lowered.Error!.Code]);
+
+ var construction = lowered.Value!;
+ var plan = BuildPlan(input, feature, construction);
+ var emitted = AirLocalizedPlanarReplacementEmitter.Emit(construction.TopologyPlan);
+ if (!emitted.Succeeded || emitted.Body is null)
+ {
+ var error = new ChamferLoweringError(ChamferLoweringErrorKind.BackendMaterializationDefect,
+ "localized-chamfer-materialization-failed", "The authoritative localized BRepPlan did not materialize.", "BRep", emitted.Diagnostics);
+ return new(false, feature, construction, plan, null, error, [error.Code, .. emitted.Diagnostics]);
+ }
+ var body = emitted.Body;
+ var planes = body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Plane);
+ if (planes != 7 || body.Topology.Faces.Count() != construction.TopologyPlan.ExpectedFaceCount)
+ {
+ var error = new ChamferLoweringError(ChamferLoweringErrorKind.VerificationFailure, "localized-chamfer-analytic-topology-verification-failed",
+ "Localized planar replacement must produce seven planar faces with the planned topology.", "Verification");
+ return new(false, feature, construction, plan, body, error, [error.Code]);
+ }
+ return new(true, feature, construction, plan, body, null,
+ ["localized-chamfer-feature-admitted", "localized-chamfer-direct-single-candidate", "localized-chamfer-authoritative-brep-plan-consumed", "localized-chamfer-explicit-owned-endpoints"]);
+ }
+
+ public static ChamferLoweringResult<AirLocalizedPlanarReplacementConstruction> Lower(AirLocalizedPlanarReplacementChamferCompileRequest input)
+ {
+ ChamferLoweringResult<AirLocalizedPlanarReplacementConstruction> Fail(ChamferLoweringErrorKind kind, string code, string message) =>
+ ChamferLoweringResult<AirLocalizedPlanarReplacementConstruction>.Err(new(kind, code, message, "FeatureAIR->ConstructionAIR"));
+ if (!input.HistoryKnown) return Fail(ChamferLoweringErrorKind.UnsupportedHistory, "localized-chamfer-unsupported-history", "Localized replacement requires known prismatic construction history.");
+ if (!string.Equals(input.Kind, "Chamfer", StringComparison.Ordinal)) return Fail(ChamferLoweringErrorKind.InvalidAuthoredInput, "localized-chamfer-invalid-kind", "Only equal-distance chamfer intent is admitted.");
+ if (!string.Equals(input.FaceA, "+X", StringComparison.Ordinal) || !string.Equals(input.FaceB, "+Z", StringComparison.Ordinal))
+ return Fail(ChamferLoweringErrorKind.UnsupportedSelection, "localized-chamfer-unsupported-selection:expected-shared-edge-plus-x-plus-z", "The first localized route admits SharedEdge(+X,+Z) only.");
+ if (!double.IsFinite(input.Width) || !double.IsFinite(input.Depth) || !double.IsFinite(input.Height) || input.Width <= Tol || input.Depth <= Tol || input.Height <= Tol)
+ return Fail(ChamferLoweringErrorKind.InvalidAuthoredInput, "localized-chamfer-invalid-box-dimensions", "Host dimensions must be finite and positive.");
+ if (!double.IsFinite(input.Distance) || input.Distance <= Tol) return Fail(ChamferLoweringErrorKind.InvalidAuthoredInput, "localized-chamfer-distance-must-be-positive", "Distance must be finite and positive.");
+ if (input.Distance >= input.Width - Tol || input.Distance >= input.Height - Tol)
+ return Fail(ChamferLoweringErrorKind.DistanceTooLarge, "localized-chamfer-distance-too-large", "Distance must remain within both planar support-face extents.");
+
+ var hx = input.Width / 2d; var hy = input.Depth / 2d; var hz = input.Height / 2d; var d = input.Distance;
+ var cross = new[] { new Point3D(-hx, -hy, -hz), new Point3D(hx, -hy, -hz), new Point3D(hx, -hy, hz - d), new Point3D(hx - d, -hy, hz), new Point3D(-hx, -hy, hz) };
+ var start = new Point3D(hx, -hy, hz);
+ var end = new Point3D(hx, hy, hz);
+ var replacement = new[] { new Point3D(hx, -hy, hz - d), new Point3D(hx - d, -hy, hz), new Point3D(hx - d, hy, hz), new Point3D(hx, hy, hz - d) };
+ var retainedX = new[] { new Point3D(hx, -hy, -hz), new Point3D(hx, hy, -hz), new Point3D(hx, hy, hz - d), new Point3D(hx, -hy, hz - d) };
+ var retainedZ = new[] { new Point3D(-hx, -hy, hz), new Point3D(hx - d, -hy, hz), new Point3D(hx - d, hy, hz), new Point3D(-hx, hy, hz) };
+ if (replacement.Distinct().Count() != 4) return Fail(ChamferLoweringErrorKind.DegenerateTransition, "localized-chamfer-degenerate-transition", "Endpoint transition quad is degenerate.");
+ var signature = Signature(input.Width, input.Depth, input.Height, d);
+ var topology = new AirLocalizedPlanarReplacementTopologyPlan(cross, -hy, hy,
+ ["UnaffectedFace(-Z)", "UnaffectedFace(-Y)", "RetainedSupportFaceA(+X)", "ChamferFace", "RetainedSupportFaceB(+Z)", "EndpointTransitionStart(-Y)", "EndpointTransitionEnd(+Y)"], signature);
+ var witness = new AirLocalizedPlanarReplacementWitness("plane(+X)", "plane(+Z)", start, end, retainedX, retainedZ, replacement,
+ "inside:x<=max,z<=max,x+z<=maxX+maxZ-distance", "ExplicitOwnedEndpoints");
+ return ChamferLoweringResult<AirLocalizedPlanarReplacementConstruction>.Ok(new($"construction:{input.FeatureId}", input.FeatureId, witness, topology));
+ }
+
+ private static AirChamferFeature Feature(AirLocalizedPlanarReplacementChamferCompileRequest input, ChamferLoweringError? error) => new(
+ input.FeatureId, input.FeatureName, input.BodyId, new AirFaceBoundarySelection("+X", "SharedEdge(+X,+Z)", false), new AirEqualDistanceChamferRule(input.Distance), input.SourceSpan,
+ input.HistoryKnown ? "generated/history-known-axis-aligned-rectangular-prism" : "imported/no-history",
+ error is null ? AirFeatureAdmissionStatus.Admitted : error.Kind == ChamferLoweringErrorKind.UnsupportedHistory ? AirFeatureAdmissionStatus.Deferred : AirFeatureAdmissionStatus.Rejected,
+ error?.Code ?? "localized-chamfer-planar-single-edge-admitted");
+
+ private static AirBRepPlan BuildPlan(AirLocalizedPlanarReplacementChamferCompileRequest input, AirChamferFeature feature, AirLocalizedPlanarReplacementConstruction construction)
+ {
+ var p = construction.TopologyPlan;
+ var provenance = new AirProvenance("AIR-CHAMFER-LOCALIZED-PLAN-A1", "Localized planar replacement", "shared-edge(+X,+Z)", input.FeatureId,
+ nameof(AirLocalizedPlanarReplacementChamferCompiler), AirSelectionClass.None, AirRuleKind.UniformChamfer, feature.ConstructionHistoryKind, true,
+ ["No legacy direct-BRep surgery.", "Plan is constructed before emission."]);
+ var elements = new List<AirBRepPlanElement>();
+ for (var i = 0; i < p.ExpectedVertexCount; i++) elements.Add(new(new($"vertex:{i}"), AirBRepPlanElementKind.Vertex, i is 2 or 7 ? AirBRepPlanRole.EndpointTransitionStart : i is 3 or 8 ? AirBRepPlanRole.EndpointTransitionEnd : AirBRepPlanRole.SectionVertex, input.FeatureId, provenance));
+ for (var i = 0; i < p.ExpectedEdgeCount; i++) elements.Add(new(new($"edge:{i}"), AirBRepPlanElementKind.Edge, AirBRepPlanRole.SectionEdge, input.FeatureId, provenance));
+ for (var i = 0; i < p.FaceRoles.Count; i++)
+ {
+ var role = p.FaceRoles[i].StartsWith("RetainedSupportFaceA", StringComparison.Ordinal) ? AirBRepPlanRole.RetainedSupportFaceA : p.FaceRoles[i].StartsWith("RetainedSupportFaceB", StringComparison.Ordinal) ? AirBRepPlanRole.RetainedSupportFaceB : p.FaceRoles[i].StartsWith("ChamferFace", StringComparison.Ordinal) ? AirBRepPlanRole.ChamferFace : p.FaceRoles[i].StartsWith("Endpoint", StringComparison.Ordinal) ? (i == 5 ? AirBRepPlanRole.EndpointTransitionStart : AirBRepPlanRole.EndpointTransitionEnd) : AirBRepPlanRole.UnaffectedFace;
+ elements.Add(new(new($"loop:{i}"), AirBRepPlanElementKind.Loop, role, input.FeatureId, provenance));
+ for (var c = 0; c < (i < 2 ? 5 : 4); c++) elements.Add(new(new($"coedge:{i}:{c}"), AirBRepPlanElementKind.Coedge, role, input.FeatureId, provenance));
+ elements.Add(new(new($"face:{i}"), AirBRepPlanElementKind.Face, role, input.FeatureId, provenance, FaceRole: p.FaceRoles[i]));
+ }
+ elements.Add(new(new("shell:0"), AirBRepPlanElementKind.Shell, AirBRepPlanRole.BodyShell, input.FeatureId, provenance));
+ elements.Add(new(new("body:0"), AirBRepPlanElementKind.Body, AirBRepPlanRole.Body, input.FeatureId, provenance));
+ var summary = new AirBRepPlanSummary(AirBRepPlanKind.LocalizedPlanarReplacement, input.FeatureId, p.ExpectedVertexCount, p.ExpectedEdgeCount, p.ExpectedEdgeCount, p.ExpectedCoedgeCount, p.ExpectedLoopCount, p.ExpectedFaceCount, p.ExpectedFaceCount, 1, 1, 0, 4, 1, 1,
+ $"box={input.Width:R}x{input.Depth:R}x{input.Height:R}", "explicit-owned-endpoints", [], ["authoritative", "no legacy fallback", "direct single candidate"],
+ new(AirNodeKind.TopFaceLoopChamfer, AirRouteKind.Unsupported, AirSelectionClass.None, AirRuleKind.UniformChamfer, feature.ConstructionHistoryKind, "Direct", ["SharedEdge(+X,+Z)"]));
+ return new($"brep-plan:localized-planar-replacement:{input.FeatureId}", AirBRepPlanKind.LocalizedPlanarReplacement, input.FeatureId, provenance, elements, summary, [], summary.Guarantees, summary.FeatureContext, LocalizedPlanarReplacementRealizationPlan: p);
+ }
+
+ private static string Signature(double w, double d, double h, double c) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(FormattableString.Invariant($"localized-planar-replacement:+X,+Z:{w:R}:{d:R}:{h:R}:{c:R}"))));
+}
+
+internal sealed record AirLocalizedPlanarReplacementEmissionResult(bool Succeeded, BrepBody? Body, IReadOnlyList<string> Diagnostics);
+
+internal static class AirLocalizedPlanarReplacementEmitter
+{
+ public static AirLocalizedPlanarReplacementEmissionResult Emit(AirLocalizedPlanarReplacementTopologyPlan plan)
+ {
+ var n = plan.CrossSection.Count;
+ if (n != 5 || plan.FaceRoles.Count != 7) return new(false, null, ["localized-chamfer-invalid-authoritative-plan"]);
+ var b = new TopologyBuilder(); var low = new VertexId[n]; var high = new VertexId[n];
+ for (var i = 0; i < n; i++) { low[i] = b.AddVertex(); high[i] = b.AddVertex(); }
+ var lowEdges = new EdgeId[n]; var highEdges = new EdgeId[n]; var spans = new EdgeId[n];
+ for (var i = 0; i < n; i++) { var next = (i + 1) % n; lowEdges[i] = b.AddEdge(low[i], low[next]); highEdges[i] = b.AddEdge(high[i], high[next]); spans[i] = b.AddEdge(low[i], high[i]); }
+ var faces = new List<FaceId> { AddFace(b, lowEdges.Select(Use.F).ToArray()), AddFace(b, highEdges.Reverse().Select(Use.R).ToArray()) };
+ for (var i = 0; i < n; i++) { var next = (i + 1) % n; faces.Add(AddFace(b, [Use.R(lowEdges[i]), Use.F(spans[i]), Use.F(highEdges[i]), Use.R(spans[next])])); }
+ var shell = b.AddShell(faces); b.AddBody([shell]);
+ var lower = plan.CrossSection.ToArray(); var upper = lower.Select(p => new Point3D(p.X, plan.MaxY, p.Z)).ToArray();
+ var geo = new BrepGeometryStore(); var bindings = new BrepBindingModel(); int curve = 1;
+ void BindEdge(EdgeId id, Point3D a, Point3D z) { var cid = new CurveGeometryId(curve++); geo.AddCurve(cid, CurveGeometry.FromLine(new Line3Curve(a, Direction3D.Create(z - a)))); bindings.AddEdgeBinding(new EdgeGeometryBinding(id, cid, new ParameterInterval(0, (z-a).Length))); }
+ for (var i = 0; i < n; i++) { var next=(i+1)%n; BindEdge(lowEdges[i],lower[i],lower[next]); BindEdge(highEdges[i],upper[i],upper[next]); BindEdge(spans[i],lower[i],upper[i]); }
+ int surface = 1;
+ void BindFace(FaceId id, Point3D origin, Vector3D normal, Vector3D u) { var sid=new SurfaceGeometryId(surface++); geo.AddSurface(sid,SurfaceGeometry.FromPlane(new PlaneSurface(origin,Direction3D.Create(normal),Direction3D.Create(u)))); bindings.AddFaceBinding(new FaceGeometryBinding(id,sid)); }
+ BindFace(faces[0], lower[0], new Vector3D(0,-1,0), new Vector3D(1,0,0));
+ BindFace(faces[1], upper[0], new Vector3D(0,1,0), new Vector3D(1,0,0));
+ for (var i=0;i<n;i++) { var next=(i+1)%n; var edge=lower[next]-lower[i]; BindFace(faces[i+2],lower[i],new Vector3D(0,1,0).Cross(edge),new Vector3D(0,1,0)); }
+ var points = new Dictionary<VertexId,Point3D>(); for(var i=0;i<n;i++){points[low[i]]=lower[i];points[high[i]]=upper[i];}
+ var body = new BrepBody(b.Model,geo,bindings,points); var check=BrepBindingValidator.Validate(body,true);
+ return check.IsSuccess ? new(true,body,["localized-chamfer-plan-emitted"]) : new(false,null,check.Diagnostics.Select(d=>d.Message).ToArray());
+ }
+ private static FaceId AddFace(TopologyBuilder b, IReadOnlyList<Use> uses) { var loop=b.AllocateLoopId(); var ids=new CoedgeId[uses.Count]; for(var i=0;i<ids.Length;i++)ids[i]=b.AllocateCoedgeId(); for(var i=0;i<ids.Length;i++)b.AddCoedge(new Coedge(ids[i],uses[i].Id,loop,ids[(i+1)%ids.Length],ids[(i+ids.Length-1)%ids.Length],uses[i].Reverse)); b.AddLoop(new Loop(loop,ids)); return b.AddFace([loop]); }
+ private readonly record struct Use(EdgeId Id,bool Reverse) { public static Use F(EdgeId id)=>new(id,false); public static Use R(EdgeId id)=>new(id,true); }
+}
diff --git a/Aetheris.Kernel.Core/Air/AirLocalizedTangentBlendFilletCompiler.cs b/Aetheris.Kernel.Core/Air/AirLocalizedTangentBlendFilletCompiler.cs
new file mode 100644
index 00000000..ca5677c5
--- /dev/null
+++ b/Aetheris.Kernel.Core/Air/AirLocalizedTangentBlendFilletCompiler.cs
@@ -0,0 +1,197 @@
+using System.Security.Cryptography;
+using System.Text;
+using Aetheris.Kernel.Core.Air.BRepPlan;
+using Aetheris.Kernel.Core.Brep;
+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.Topology;
+
+namespace Aetheris.Kernel.Core.Air;
+
+/// <summary>
+/// The first admitted exact fillet construction: a finite quarter-circle swept linearly
+/// along the history-known +X/+Z edge of an axis-aligned box. This is intentionally
+/// not a general rolling-ball or direct-BRep edge surgery route.
+/// </summary>
+internal sealed record AirLocalizedTangentBlendWitness(
+ string SupportPlaneA, string SupportPlaneB, Point3D SelectedEdgeStart, Point3D SelectedEdgeEnd,
+ Point3D ArcCenterStart, Point3D ArcCenterEnd, Circle3Curve QuarterCircleStart,
+ Circle3Curve QuarterCircleEnd, CylinderSurface BlendCylinder, double Radius,
+ IReadOnlyList<Point3D> RetainedSupportFaceA, IReadOnlyList<Point3D> RetainedSupportFaceB,
+ string MaterialSide, string EndpointPolicy, string Provenance);
+
+internal sealed record AirLocalizedTangentBlendTopologyPlan(
+ IReadOnlyList<Point3D> CrossSection, double MinY, double MaxY, double Radius,
+ IReadOnlyList<string> FaceRoles, string DeterministicSignature)
+{
+ public int ExpectedVertexCount => CrossSection.Count * 2;
+ public int ExpectedEdgeCount => CrossSection.Count * 3;
+ public int ExpectedFaceCount => CrossSection.Count + 2;
+ public int ExpectedLoopCount => ExpectedFaceCount;
+ public int ExpectedCoedgeCount => 6 * CrossSection.Count;
+}
+
+internal sealed record AirLocalizedTangentBlendConstruction(
+ string ConstructionId, string SourceFeatureId, AirLocalizedTangentBlendWitness Witness,
+ AirLocalizedTangentBlendTopologyPlan TopologyPlan);
+
+internal sealed record AirLocalizedTangentBlendFilletCompileRequest(
+ string BodyId, string FeatureId, string FeatureName, double Width, double Depth, double Height,
+ string FaceA, string FaceB, string Kind, double Radius, AirSourceSpan SourceSpan, bool HistoryKnown = true);
+
+internal sealed record AirLocalizedTangentBlendFilletCompileResult(
+ bool Succeeded, AirFilletFeature Feature, AirLocalizedTangentBlendConstruction? Construction,
+ AirBRepPlan? BRepPlan, BrepBody? Body, ChamferLoweringError? Error, IReadOnlyList<string> Diagnostics)
+{
+ public const string ProductionRoute = "AirLocalizedTangentBlendSingleEdgeFillet";
+}
+
+internal sealed record AirConstantRadiusFilletRule(double Radius, string Unit = "mm");
+internal sealed record AirFilletFeature(
+ string FeatureId, string FeatureName, string BodyId, AirFaceBoundarySelection Selection,
+ AirConstantRadiusFilletRule Rule, AirSourceSpan SourceSpan, string ConstructionHistoryKind,
+ AirFeatureAdmissionStatus Admission, string AdmissionReason);
+
+internal static class AirLocalizedTangentBlendFilletCompiler
+{
+ private const double Tol = 1e-9;
+
+ public static AirLocalizedTangentBlendFilletCompileResult Compile(AirLocalizedTangentBlendFilletCompileRequest input)
+ {
+ var lowered = Lower(input);
+ var feature = Feature(input, lowered.Error);
+ if (!lowered.IsSuccess) return new(false, feature, null, null, null, lowered.Error, [lowered.Error!.Code]);
+
+ var construction = lowered.Value!;
+ var plan = BuildPlan(input, feature, construction);
+ var emitted = AirLocalizedTangentBlendEmitter.Emit(construction);
+ if (!emitted.Succeeded || emitted.Body is null)
+ {
+ var error = new ChamferLoweringError(ChamferLoweringErrorKind.BackendMaterializationDefect,
+ "localized-fillet-materialization-failed", "The authoritative localized tangent-blend BRepPlan did not materialize.", "BRep", emitted.Diagnostics);
+ return new(false, feature, construction, plan, null, error, [error.Code, .. emitted.Diagnostics]);
+ }
+
+ var body = emitted.Body;
+ var cylinders = body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Cylinder);
+ var planes = body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Plane);
+ if (cylinders != 1 || planes != 6 || body.Topology.Faces.Count() != construction.TopologyPlan.ExpectedFaceCount)
+ {
+ var error = new ChamferLoweringError(ChamferLoweringErrorKind.VerificationFailure,
+ "localized-fillet-analytic-topology-verification-failed", "The localized blend must contain six planar faces and one exact cylindrical face.", "Verification");
+ return new(false, feature, construction, plan, body, error, [error.Code]);
+ }
+ return new(true, feature, construction, plan, body, null,
+ ["localized-fillet-feature-admitted", "localized-fillet-direct-single-candidate", "localized-fillet-authoritative-brep-plan-consumed", "localized-fillet-exact-quarter-circle-linear-sweep", "localized-fillet-explicit-owned-endpoints"]);
+ }
+
+ public static ChamferLoweringResult<AirLocalizedTangentBlendConstruction> Lower(AirLocalizedTangentBlendFilletCompileRequest input)
+ {
+ ChamferLoweringResult<AirLocalizedTangentBlendConstruction> Fail(ChamferLoweringErrorKind kind, string code, string message) =>
+ ChamferLoweringResult<AirLocalizedTangentBlendConstruction>.Err(new(kind, code, message, "FeatureAIR->ConstructionAIR"));
+ if (!input.HistoryKnown) return Fail(ChamferLoweringErrorKind.UnsupportedHistory, "localized-fillet-unsupported-history", "Localized tangent blending requires known prismatic construction history.");
+ if (!string.Equals(input.Kind, "Fillet", StringComparison.Ordinal)) return Fail(ChamferLoweringErrorKind.InvalidAuthoredInput, "localized-fillet-invalid-kind", "This lowerer accepts constant-radius Fillet intent only.");
+ if (!string.Equals(input.FaceA, "+X", StringComparison.Ordinal) || !string.Equals(input.FaceB, "+Z", StringComparison.Ordinal))
+ return Fail(ChamferLoweringErrorKind.UnsupportedSelection, "localized-fillet-unsupported-selection:expected-shared-edge-plus-x-plus-z", "The first localized fillet route admits SharedEdge(+X,+Z) only.");
+ if (!double.IsFinite(input.Width) || !double.IsFinite(input.Depth) || !double.IsFinite(input.Height) || input.Width <= Tol || input.Depth <= Tol || input.Height <= Tol)
+ return Fail(ChamferLoweringErrorKind.InvalidAuthoredInput, "localized-fillet-invalid-box-dimensions", "Host dimensions must be finite and positive.");
+ if (!double.IsFinite(input.Radius) || input.Radius <= Tol) return Fail(ChamferLoweringErrorKind.InvalidAuthoredInput, "localized-fillet-radius-must-be-positive", "Radius must be finite and positive.");
+ if (input.Radius >= input.Width - Tol || input.Radius >= input.Height - Tol)
+ return Fail(ChamferLoweringErrorKind.DistanceTooLarge, "localized-fillet-radius-too-large", "Radius must remain within both orthogonal planar support-face extents.");
+
+ var hx = input.Width / 2d; var hy = input.Depth / 2d; var hz = input.Height / 2d; var r = input.Radius;
+ var cross = new[] { new Point3D(-hx, -hy, -hz), new Point3D(hx, -hy, -hz), new Point3D(hx, -hy, hz - r), new Point3D(hx - r, -hy, hz), new Point3D(-hx, -hy, hz) };
+ var centerStart = new Point3D(hx - r, -hy, hz - r);
+ var centerEnd = new Point3D(hx - r, hy, hz - r);
+ var yAxis = Direction3D.Create(new Vector3D(0, 1, 0));
+ // The profile uses the opposite normal so its increasing trim [0,π/2]
+ // follows the topology edge from the +X tangent to the +Z tangent.
+ var profileNormal = Direction3D.Create(new Vector3D(0, -1, 0));
+ var xAxis = Direction3D.Create(new Vector3D(1, 0, 0));
+ var arcStart = new Circle3Curve(centerStart, profileNormal, r, xAxis);
+ var arcEnd = new Circle3Curve(centerEnd, profileNormal, r, xAxis);
+ var cylinder = new CylinderSurface(centerStart, yAxis, r, xAxis);
+ var retainedX = new[] { new Point3D(hx, -hy, -hz), new Point3D(hx, hy, -hz), new Point3D(hx, hy, hz-r), new Point3D(hx, -hy, hz-r) };
+ var retainedZ = new[] { new Point3D(-hx, -hy, hz), new Point3D(hx-r, -hy, hz), new Point3D(hx-r, hy, hz), new Point3D(-hx, hy, hz) };
+ if ((cross[2] - cross[3]).Length <= Tol) return Fail(ChamferLoweringErrorKind.DegenerateTransition, "localized-fillet-degenerate-blend", "The tangent points produce a degenerate blend boundary.");
+ var topology = new AirLocalizedTangentBlendTopologyPlan(cross, -hy, hy, r,
+ ["UnaffectedFace(-Z)", "UnaffectedFace(-Y)", "RetainedSupportFaceA(+X)", "CylindricalFilletFace", "RetainedSupportFaceB(+Z)", "EndpointTransitionStart(-Y)", "EndpointTransitionEnd(+Y)"], Signature(input.Width, input.Depth, input.Height, r));
+ var witness = new AirLocalizedTangentBlendWitness("plane(+X)", "plane(+Z)", new Point3D(hx, -hy, hz), new Point3D(hx, hy, hz), centerStart, centerEnd, arcStart, arcEnd, cylinder, r,
+ retainedX, retainedZ, "inside:x<=max,z<=max; remove exterior corner outside quarter-circle", "ExplicitOwnedEndpoints", "history-known-axis-aligned-rectangular-prism");
+ return ChamferLoweringResult<AirLocalizedTangentBlendConstruction>.Ok(new($"construction:{input.FeatureId}", input.FeatureId, witness, topology));
+ }
+
+ private static AirFilletFeature Feature(AirLocalizedTangentBlendFilletCompileRequest input, ChamferLoweringError? error) => new(
+ input.FeatureId, input.FeatureName, input.BodyId, new AirFaceBoundarySelection("+X", "SharedEdge(+X,+Z)", false), new AirConstantRadiusFilletRule(input.Radius), input.SourceSpan,
+ input.HistoryKnown ? "generated/history-known-axis-aligned-rectangular-prism" : "imported/no-history",
+ error is null ? AirFeatureAdmissionStatus.Admitted : error.Kind == ChamferLoweringErrorKind.UnsupportedHistory ? AirFeatureAdmissionStatus.Deferred : AirFeatureAdmissionStatus.Rejected,
+ error?.Code ?? "localized-fillet-tangent-blend-single-edge-admitted");
+
+ private static AirBRepPlan BuildPlan(AirLocalizedTangentBlendFilletCompileRequest input, AirFilletFeature feature, AirLocalizedTangentBlendConstruction construction)
+ {
+ var p = construction.TopologyPlan;
+ var provenance = new AirProvenance("AIR-FILLET-LOCALIZED-M1", "Localized tangent-blend Construction AIR", "shared-edge(+X,+Z)", input.FeatureId,
+ nameof(AirLocalizedTangentBlendFilletCompiler), AirSelectionClass.SingleEdge, AirRuleKind.ConstantRadiusFillet, feature.ConstructionHistoryKind, true,
+ ["Exact quarter-circle profile.", "Exact cylinder generated by linear sweep.", "No legacy direct-BRep surgery.", "Plan is constructed before emission."]);
+ var elements = new List<AirBRepPlanElement>();
+ for (var i = 0; i < p.ExpectedVertexCount; i++) elements.Add(new(new($"vertex:{i}"), AirBRepPlanElementKind.Vertex, i is 2 or 7 ? AirBRepPlanRole.EndpointTransitionStart : i is 3 or 8 ? AirBRepPlanRole.EndpointTransitionEnd : AirBRepPlanRole.SectionVertex, input.FeatureId, provenance));
+ for (var i = 0; i < p.ExpectedEdgeCount; i++) elements.Add(new(new($"edge:{i}"), AirBRepPlanElementKind.Edge, i is 2 or 7 ? AirBRepPlanRole.FilletFace : AirBRepPlanRole.SectionEdge, input.FeatureId, provenance));
+ for (var i = 0; i < p.FaceRoles.Count; i++)
+ {
+ var role = p.FaceRoles[i].StartsWith("RetainedSupportFaceA", StringComparison.Ordinal) ? AirBRepPlanRole.RetainedSupportFaceA : p.FaceRoles[i].StartsWith("RetainedSupportFaceB", StringComparison.Ordinal) ? AirBRepPlanRole.RetainedSupportFaceB : p.FaceRoles[i].StartsWith("CylindricalFilletFace", StringComparison.Ordinal) ? AirBRepPlanRole.FilletFace : p.FaceRoles[i].StartsWith("Endpoint", StringComparison.Ordinal) ? (i == 5 ? AirBRepPlanRole.EndpointTransitionStart : AirBRepPlanRole.EndpointTransitionEnd) : AirBRepPlanRole.UnaffectedFace;
+ elements.Add(new(new($"loop:{i}"), AirBRepPlanElementKind.Loop, role, input.FeatureId, provenance));
+ for (var c = 0; c < (i < 2 ? 5 : 4); c++) elements.Add(new(new($"coedge:{i}:{c}"), AirBRepPlanElementKind.Coedge, role, input.FeatureId, provenance));
+ elements.Add(new(new($"face:{i}"), AirBRepPlanElementKind.Face, role, input.FeatureId, provenance, FaceRole: p.FaceRoles[i]));
+ }
+ elements.Add(new(new("surface:cylinder:0"), AirBRepPlanElementKind.Surface, AirBRepPlanRole.FilletFace, input.FeatureId, provenance));
+ elements.Add(new(new("shell:0"), AirBRepPlanElementKind.Shell, AirBRepPlanRole.BodyShell, input.FeatureId, provenance));
+ elements.Add(new(new("body:0"), AirBRepPlanElementKind.Body, AirBRepPlanRole.Body, input.FeatureId, provenance));
+ var summary = new AirBRepPlanSummary(AirBRepPlanKind.LocalizedTangentBlend, input.FeatureId, p.ExpectedVertexCount, p.ExpectedEdgeCount, p.ExpectedEdgeCount, p.ExpectedCoedgeCount, p.ExpectedLoopCount, p.ExpectedFaceCount, p.ExpectedFaceCount, 1, 1, 0, 4, 1, 0,
+ $"box={input.Width:R}x{input.Depth:R}x{input.Height:R};radius={input.Radius:R}", "explicit-owned-endpoints", [], ["authoritative", "exact-cylinder", "no legacy fallback", "direct single candidate"],
+ new(AirNodeKind.Unsupported, AirRouteKind.Unsupported, AirSelectionClass.SingleEdge, AirRuleKind.ConstantRadiusFillet, feature.ConstructionHistoryKind, "Direct", ["SharedEdge(+X,+Z)"]));
+ return new($"brep-plan:localized-tangent-blend:{input.FeatureId}", AirBRepPlanKind.LocalizedTangentBlend, input.FeatureId, provenance, elements, summary, [], summary.Guarantees, summary.FeatureContext, LocalizedTangentBlendRealizationPlan: p);
+ }
+
+ private static string Signature(double w, double d, double h, double r) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(FormattableString.Invariant($"localized-tangent-blend:+X,+Z:{w:R}:{d:R}:{h:R}:{r:R}"))));
+}
+
+internal sealed record AirLocalizedTangentBlendEmissionResult(bool Succeeded, BrepBody? Body, IReadOnlyList<string> Diagnostics);
+
+internal static class AirLocalizedTangentBlendEmitter
+{
+ public static AirLocalizedTangentBlendEmissionResult Emit(AirLocalizedTangentBlendConstruction construction)
+ {
+ var plan = construction.TopologyPlan; var witness = construction.Witness; var n = plan.CrossSection.Count;
+ if (n != 5 || plan.FaceRoles.Count != 7 || plan.Radius <= 0d) return new(false, null, ["localized-fillet-invalid-authoritative-plan"]);
+ var b = new TopologyBuilder(); var low = new VertexId[n]; var high = new VertexId[n];
+ for (var i = 0; i < n; i++) { low[i] = b.AddVertex(); high[i] = b.AddVertex(); }
+ var lowEdges = new EdgeId[n]; var highEdges = new EdgeId[n]; var spans = new EdgeId[n];
+ for (var i = 0; i < n; i++) { var next = (i + 1) % n; lowEdges[i] = b.AddEdge(low[i], low[next]); highEdges[i] = b.AddEdge(high[i], high[next]); spans[i] = b.AddEdge(low[i], high[i]); }
+ var faces = new List<FaceId> { AddFace(b, lowEdges.Select(Use.F).ToArray()), AddFace(b, highEdges.Reverse().Select(Use.R).ToArray()) };
+ for (var i = 0; i < n; i++) { var next = (i + 1) % n; faces.Add(AddFace(b, [Use.R(lowEdges[i]), Use.F(spans[i]), Use.F(highEdges[i]), Use.R(spans[next])])); }
+ var shell = b.AddShell(faces); b.AddBody([shell]);
+ var lower = plan.CrossSection.ToArray(); var upper = lower.Select(p => new Point3D(p.X, plan.MaxY, p.Z)).ToArray();
+ var geo = new BrepGeometryStore(); var bindings = new BrepBindingModel(); int curve = 1;
+ void BindLine(EdgeId id, Point3D a, Point3D z) { var cid = new CurveGeometryId(curve++); geo.AddCurve(cid, CurveGeometry.FromLine(new Line3Curve(a, Direction3D.Create(z - a)))); bindings.AddEdgeBinding(new EdgeGeometryBinding(id, cid, new ParameterInterval(0, (z-a).Length))); }
+ void BindArc(EdgeId id, Circle3Curve arc) { var cid = new CurveGeometryId(curve++); geo.AddCurve(cid, CurveGeometry.FromCircle(arc)); bindings.AddEdgeBinding(new EdgeGeometryBinding(id, cid, new ParameterInterval(0d, double.Pi / 2d))); }
+ for (var i = 0; i < n; i++) { var next = (i + 1) % n; if (i == 2) { BindArc(lowEdges[i], witness.QuarterCircleStart); BindArc(highEdges[i], witness.QuarterCircleEnd); } else { BindLine(lowEdges[i], lower[i], lower[next]); BindLine(highEdges[i], upper[i], upper[next]); } BindLine(spans[i], lower[i], upper[i]); }
+ int surface = 1;
+ void BindPlane(FaceId id, Point3D origin, Vector3D normal, Vector3D u) { var sid = new SurfaceGeometryId(surface++); geo.AddSurface(sid, SurfaceGeometry.FromPlane(new PlaneSurface(origin, Direction3D.Create(normal), Direction3D.Create(u)))); bindings.AddFaceBinding(new FaceGeometryBinding(id, sid)); }
+ BindPlane(faces[0], lower[0], new Vector3D(0, -1, 0), new Vector3D(1, 0, 0));
+ BindPlane(faces[1], upper[0], new Vector3D(0, 1, 0), new Vector3D(1, 0, 0));
+ for (var i = 0; i < n; i++)
+ {
+ var next = (i + 1) % n;
+ if (i == 2) { var sid = new SurfaceGeometryId(surface++); geo.AddSurface(sid, SurfaceGeometry.FromCylinder(witness.BlendCylinder)); bindings.AddFaceBinding(new FaceGeometryBinding(faces[i + 2], sid)); }
+ else { var edge = lower[next] - lower[i]; BindPlane(faces[i + 2], lower[i], new Vector3D(0, 1, 0).Cross(edge), new Vector3D(0, 1, 0)); }
+ }
+ var points = new Dictionary<VertexId, Point3D>(); for (var i = 0; i < n; i++) { points[low[i]] = lower[i]; points[high[i]] = upper[i]; }
+ var body = new BrepBody(b.Model, geo, bindings, points); var check = BrepBindingValidator.Validate(body, true);
+ return check.IsSuccess ? new(true, body, ["localized-fillet-plan-emitted"]) : new(false, null, check.Diagnostics.Select(d => d.Message).ToArray());
+ }
+
+ private static FaceId AddFace(TopologyBuilder b, IReadOnlyList<Use> uses) { var loop = b.AllocateLoopId(); var ids = new CoedgeId[uses.Count]; for (var i = 0; i < ids.Length; i++) ids[i] = b.AllocateCoedgeId(); for (var i = 0; i < ids.Length; i++) b.AddCoedge(new Coedge(ids[i], uses[i].Id, loop, ids[(i + 1) % ids.Length], ids[(i + ids.Length - 1) % ids.Length], uses[i].Reverse)); b.AddLoop(new Loop(loop, ids)); return b.AddFace([loop]); }
+ private readonly record struct Use(EdgeId Id, bool Reverse) { public static Use F(EdgeId id) => new(id, false); public static Use R(EdgeId id) => new(id, true); }
+}
diff --git a/Aetheris.Kernel.Core/Air/ChamferCornerPolicy.cs b/Aetheris.Kernel.Core/Air/ChamferCornerPolicy.cs
new file mode 100644
index 00000000..ac1cc829
--- /dev/null
+++ b/Aetheris.Kernel.Core/Air/ChamferCornerPolicy.cs
@@ -0,0 +1,208 @@
+using Aetheris.Kernel.Core.Air.BRepPlan;
+
+namespace Aetheris.Kernel.Core.Air;
+
+internal enum ChamferCornerConvexity { Convex, Concave, Unknown }
+internal enum ChamferCornerMaterialSide { RetainInterior, RetainExterior, Ambiguous }
+internal enum ChamferCornerRule { UniformEqualDistance, Asymmetric, NonUniform }
+internal enum ChamferCornerTopologyKind { OpenChain, ClosedLoop, Junction }
+internal enum ChamferCornerSourceProvenance { GeneratedHistoryKnown, RecoveredTopology, ExplicitConceptWitness }
+internal enum ChamferCornerSupportSurfaceFamily { Plane, Cylinder, Cone, Other }
+
+// These are the only policies for which this repository contains either a modern exact
+// construction or a concrete legacy geometry experiment. They are deliberately not a
+// catalogue of every corner treatment a CAD kernel might someday support.
+internal enum ChamferCornerPolicy
+{
+ SectionTransitionJunction,
+ PlanarEdgePairCut,
+ PlanarTriangularCut,
+ ExplicitWitness,
+}
+
+internal enum ChamferCornerSelectionMode { Direct, Utility, Error }
+
+internal enum ChamferCornerAdmissionFailure
+{
+ None,
+ UnsupportedValence,
+ UnsupportedSurfaceCombination,
+ UnsupportedChamferRule,
+ UnsupportedHistory,
+ InvalidMaterialSide,
+ DistanceNotAdmissible,
+ SelfIntersection,
+ OpenReplacementRegion,
+ MissingRetainedRegion,
+ MissingReplacementRegion,
+ NonManifoldTopology,
+ ExactConstructionUnavailable,
+ MissingAuthoritativeBRepPlan,
+ PolicyDoesNotMatchClassification,
+}
+
+internal sealed record ChamferCornerConstructionWitness(
+ string WitnessId,
+ string ConstructionKind,
+ ChamferCornerPolicy Policy,
+ AirBRepPlan Plan,
+ ChamferCornerSourceProvenance Provenance);
+
+/// <summary>
+/// Construction-facing facts for one selected-edge junction. IDs are AIR/construction
+/// identities, never raw B-rep topology IDs and never Firmament syntax.
+/// </summary>
+internal sealed record ChamferCornerContext(
+ string CornerId,
+ ChamferCornerConvexity Convexity,
+ int IncidentSelectedEdgeCount,
+ int VertexValence,
+ IReadOnlyList<ChamferCornerSupportSurfaceFamily> SupportSurfaces,
+ ChamferCornerMaterialSide MaterialSide,
+ ChamferCornerRule Rule,
+ ChamferCornerTopologyKind TopologyKind,
+ bool HasConstructionHistory,
+ bool IsSymmetric,
+ ChamferCornerSourceProvenance SourceProvenance,
+ bool DistanceAdmissible,
+ bool NonSelfIntersecting,
+ bool HasClosedReplacementRegion,
+ bool HasRetainedRegionOwnership,
+ bool HasReplacementRegionOwnership,
+ bool PreservesManifoldTopology,
+ bool ExactConstructionAvailable,
+ ChamferCornerConstructionWitness? AvailableWitness = null);
+
+internal sealed record ChamferCornerCandidateEvidence(
+ ChamferCornerPolicy Policy,
+ bool Admitted,
+ ChamferCornerAdmissionFailure Failure,
+ string Reason,
+ double? UtilityScore = null,
+ IReadOnlyDictionary<string, double>? UtilityConsiderations = null);
+
+internal sealed record ChamferCornerConstruction(
+ ChamferCornerPolicy Policy,
+ ChamferCornerSelectionMode SelectionMode,
+ IReadOnlyList<ChamferCornerCandidateEvidence> Candidates,
+ ChamferCornerConstructionWitness Witness,
+ ChamferCornerSourceProvenance Provenance);
+
+/// <summary>
+/// Exhaustive structural classification plus hard geometric admission. No utility engine
+/// is called because the currently proven modern fixture set never leaves two admitted,
+/// authoritative constructions for the same context.
+/// </summary>
+internal static class ChamferCornerPolicyResolver
+{
+ public static ChamferLoweringResult<ChamferCornerConstruction> Resolve(ChamferCornerContext context)
+ {
+ var policies = EnumeratePolicies(context);
+ if (policies.Count == 0)
+ return Error(ChamferLoweringErrorKind.NoCandidatePolicy, "chamfer-corner-no-candidate-policy", "No corner policy matches the typed corner classification.", context, []);
+
+ var evidence = policies.Select(policy => Admit(context, policy)).ToArray();
+ var admitted = evidence.Where(candidate => candidate.Admitted).ToArray();
+ if (admitted.Length == 0)
+ return Error(ErrorKind(evidence), ErrorCode(evidence), "No candidate has an exact, hard-valid Construction AIR/BRepPlan witness.", context, evidence);
+
+ if (admitted.Length > 1)
+ return Error(ChamferLoweringErrorKind.AmbiguousWithoutPreference, "chamfer-corner-ambiguous-without-preference", "Several exact corner constructions are admitted, but no evidence-backed preference model is registered.", context, evidence);
+
+ var selected = admitted[0];
+ var witness = context.AvailableWitness!;
+ return ChamferLoweringResult<ChamferCornerConstruction>.Ok(new(
+ selected.Policy,
+ ChamferCornerSelectionMode.Direct,
+ evidence,
+ witness,
+ witness.Provenance));
+ }
+
+ private static IReadOnlyList<ChamferCornerPolicy> EnumeratePolicies(ChamferCornerContext context)
+ {
+ if (context.SourceProvenance == ChamferCornerSourceProvenance.ExplicitConceptWitness)
+ return [ChamferCornerPolicy.ExplicitWitness];
+
+ return (context.TopologyKind, context.Convexity, context.IncidentSelectedEdgeCount, context.VertexValence) switch
+ {
+ (ChamferCornerTopologyKind.ClosedLoop, ChamferCornerConvexity.Convex, 2, 3) => [ChamferCornerPolicy.SectionTransitionJunction],
+ (ChamferCornerTopologyKind.Junction, ChamferCornerConvexity.Convex, 2, 3) => [ChamferCornerPolicy.PlanarEdgePairCut],
+ (ChamferCornerTopologyKind.Junction, ChamferCornerConvexity.Convex, 3, 3) => [ChamferCornerPolicy.PlanarTriangularCut],
+ (ChamferCornerTopologyKind.Junction, ChamferCornerConvexity.Concave, _, _) => [ChamferCornerPolicy.ExplicitWitness],
+ _ => [],
+ };
+ }
+
+ private static ChamferCornerCandidateEvidence Admit(ChamferCornerContext context, ChamferCornerPolicy policy)
+ {
+ ChamferCornerCandidateEvidence Reject(ChamferCornerAdmissionFailure failure, string reason) => new(policy, false, failure, reason);
+
+ if (context.VertexValence is < 2 or > 3)
+ return Reject(ChamferCornerAdmissionFailure.UnsupportedValence, "Only bounded valence-two loop corners and valence-three junction experiments exist.");
+ if (context.SupportSurfaces.Count == 0 || context.SupportSurfaces.Any(surface => surface != ChamferCornerSupportSurfaceFamily.Plane))
+ return Reject(ChamferCornerAdmissionFailure.UnsupportedSurfaceCombination, "The current corner evidence is planar-only.");
+ if (context.Rule != ChamferCornerRule.UniformEqualDistance)
+ return Reject(ChamferCornerAdmissionFailure.UnsupportedChamferRule, "No asymmetric or nonuniform exact corner construction is registered.");
+ if (policy != ChamferCornerPolicy.ExplicitWitness && !context.HasConstructionHistory)
+ return Reject(ChamferCornerAdmissionFailure.UnsupportedHistory, "Automatic corner construction currently requires generated construction history.");
+ if (policy == ChamferCornerPolicy.SectionTransitionJunction && !context.IsSymmetric)
+ return Reject(ChamferCornerAdmissionFailure.PolicyDoesNotMatchClassification, "The section-transition control fixture is symmetric.");
+ if (context.MaterialSide == ChamferCornerMaterialSide.Ambiguous)
+ return Reject(ChamferCornerAdmissionFailure.InvalidMaterialSide, "Material side must be established before policy selection.");
+ if (!context.DistanceAdmissible)
+ return Reject(ChamferCornerAdmissionFailure.DistanceNotAdmissible, "Chamfer distance violates the local feature envelope.");
+ if (!context.NonSelfIntersecting)
+ return Reject(ChamferCornerAdmissionFailure.SelfIntersection, "Candidate replacement intersects itself or retained material.");
+ if (!context.HasClosedReplacementRegion)
+ return Reject(ChamferCornerAdmissionFailure.OpenReplacementRegion, "Replacement ownership does not form a closed region.");
+ if (!context.HasRetainedRegionOwnership)
+ return Reject(ChamferCornerAdmissionFailure.MissingRetainedRegion, "Retained face-region ownership is missing.");
+ if (!context.HasReplacementRegionOwnership)
+ return Reject(ChamferCornerAdmissionFailure.MissingReplacementRegion, "Replacement face-region ownership is missing.");
+ if (!context.PreservesManifoldTopology)
+ return Reject(ChamferCornerAdmissionFailure.NonManifoldTopology, "The bounded topology invariant is not proven.");
+ if (!context.ExactConstructionAvailable)
+ return Reject(ChamferCornerAdmissionFailure.ExactConstructionUnavailable, "No exact construction is available for this policy.");
+ if (context.AvailableWitness is null || context.AvailableWitness.Policy != policy || context.AvailableWitness.Plan is null)
+ return Reject(ChamferCornerAdmissionFailure.MissingAuthoritativeBRepPlan, "A concrete authoritative BRepPlan witness is required; legacy direct-BRep output is insufficient.");
+
+ return new(policy, true, ChamferCornerAdmissionFailure.None, "All hard invariants and the authoritative BRepPlan witness are present.");
+ }
+
+ private static ChamferLoweringErrorKind ErrorKind(IReadOnlyList<ChamferCornerCandidateEvidence> evidence)
+ {
+ var failures = evidence.Select(candidate => candidate.Failure).ToHashSet();
+ if (failures.Contains(ChamferCornerAdmissionFailure.UnsupportedValence)) return ChamferLoweringErrorKind.UnsupportedValence;
+ if (failures.Contains(ChamferCornerAdmissionFailure.UnsupportedSurfaceCombination)) return ChamferLoweringErrorKind.UnsupportedSurfaceCombination;
+ if (failures.Contains(ChamferCornerAdmissionFailure.UnsupportedChamferRule)) return ChamferLoweringErrorKind.UnsupportedSelection;
+ if (failures.Contains(ChamferCornerAdmissionFailure.UnsupportedHistory)) return ChamferLoweringErrorKind.UnsupportedHistory;
+ if (failures.Contains(ChamferCornerAdmissionFailure.InvalidMaterialSide)) return ChamferLoweringErrorKind.InvalidMaterialSide;
+ if (failures.Contains(ChamferCornerAdmissionFailure.SelfIntersection)) return ChamferLoweringErrorKind.SelfIntersection;
+ if (failures.Contains(ChamferCornerAdmissionFailure.MissingRetainedRegion)) return ChamferLoweringErrorKind.MissingRetainedRegion;
+ if (failures.Contains(ChamferCornerAdmissionFailure.MissingReplacementRegion) || failures.Contains(ChamferCornerAdmissionFailure.OpenReplacementRegion)) return ChamferLoweringErrorKind.MissingReplacementRegion;
+ return ChamferLoweringErrorKind.ConstructionWitnessRequired;
+ }
+
+ private static string ErrorCode(IReadOnlyList<ChamferCornerCandidateEvidence> evidence) =>
+ evidence.Any(candidate => candidate.Failure == ChamferCornerAdmissionFailure.MissingAuthoritativeBRepPlan)
+ ? "chamfer-corner-construction-witness-required:authoritative-brep-plan"
+ : $"chamfer-corner-hard-admission-rejected:{evidence[0].Failure}";
+
+ private static ChamferLoweringResult<ChamferCornerConstruction> Error(
+ ChamferLoweringErrorKind kind,
+ string code,
+ string message,
+ ChamferCornerContext context,
+ IReadOnlyList<ChamferCornerCandidateEvidence> evidence) =>
+ ChamferLoweringResult<ChamferCornerConstruction>.Err(new(
+ kind,
+ code,
+ message,
+ "FeatureAIR->CornerPolicy->ConstructionAIR",
+ [
+ $"corner={context.CornerId}",
+ $"classification={context.Convexity}/{context.TopologyKind}/selected:{context.IncidentSelectedEdgeCount}/valence:{context.VertexValence}",
+ .. evidence.Select(candidate => $"candidate={candidate.Policy};admitted={candidate.Admitted};failure={candidate.Failure};reason={candidate.Reason}"),
+ ]));
+}
diff --git a/Aetheris.Kernel.Core/Air/ChamferLoweringResult.cs b/Aetheris.Kernel.Core/Air/ChamferLoweringResult.cs
index eb536606..a6cddff9 100644
--- a/Aetheris.Kernel.Core/Air/ChamferLoweringResult.cs
+++ b/Aetheris.Kernel.Core/Air/ChamferLoweringResult.cs
@@ -18,6 +18,14 @@ internal enum ChamferLoweringErrorKind
UnsupportedJunction,
BackendMaterializationDefect,
VerificationFailure,
+ NoCandidatePolicy,
+ UnsupportedValence,
+ UnsupportedSurfaceCombination,
+ AmbiguousWithoutPreference,
+ InvalidMaterialSide,
+ MissingRetainedRegion,
+ MissingReplacementRegion,
+ ConstructionWitnessRequired,
}
internal sealed record ChamferLoweringError(
diff --git a/Aetheris.Kernel.Core/Brep/BrepExportPreflight.cs b/Aetheris.Kernel.Core/Brep/BrepExportPreflight.cs
new file mode 100644
index 00000000..9944d0fc
--- /dev/null
+++ b/Aetheris.Kernel.Core/Brep/BrepExportPreflight.cs
@@ -0,0 +1,240 @@
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Geometry.Curves;
+using Aetheris.Kernel.Core.Geometry.Surfaces;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Numerics;
+using Aetheris.Kernel.Core.Topology;
+
+namespace Aetheris.Kernel.Core.Brep;
+
+public enum BrepExportPreflightSeverity { Warning, Error }
+
+/// <summary>Why an export-facing preflight finding exists. Coverage gaps are deliberately non-fatal.</summary>
+public enum BrepExportPreflightFindingClassification
+{
+ InvalidGeometry,
+ InvalidTopology,
+ UnsupportedCheck,
+ ValidLegacyRepresentation,
+ SuspiciousNeedsReview,
+}
+
+/// <summary>Structured, export-facing evidence for a B-rep contradiction.</summary>
+public sealed record BrepExportPreflightDiagnostic(
+ string Code,
+ BrepExportPreflightSeverity Severity,
+ string Stage,
+ string Message,
+ int? BodyId = null,
+ int? FaceId = null,
+ int? LoopId = null,
+ int? CoedgeIndex = null,
+ int? EdgeId = null,
+ string? SurfaceFamily = null,
+ double? MeasuredDeviation = null,
+ double? AllowedTolerance = null,
+ BrepExportPreflightFindingClassification Classification = BrepExportPreflightFindingClassification.SuspiciousNeedsReview)
+{
+ public string Context => $"BrepExportPreflight{(BodyId is null ? string.Empty : $".Body:{BodyId}")}{(FaceId is null ? string.Empty : $".Face:{FaceId}")}{(LoopId is null ? string.Empty : $".Loop:{LoopId}")}{(EdgeId is null ? string.Empty : $".Edge:{EdgeId}")}";
+}
+
+public sealed record BrepExportPreflightResult(
+ bool IsValid,
+ IReadOnlyList<BrepExportPreflightDiagnostic> Diagnostics,
+ int CheckedBodies,
+ int CheckedFaces,
+ int CheckedLoops,
+ int CheckedEdges)
+{
+ public int ErrorCount => Diagnostics.Count(d => d.Severity == BrepExportPreflightSeverity.Error);
+ public int WarningCount => Diagnostics.Count(d => d.Severity == BrepExportPreflightSeverity.Warning);
+}
+
+/// <summary>
+/// Final common safety gate for analytic B-reps immediately before STEP serialization.
+/// It deliberately validates only topology and analytic geometry that the current model
+/// can prove; unsupported surface containment is reported as a non-blocking warning.
+/// </summary>
+public static class BrepExportPreflight
+{
+ private static readonly ToleranceContext Tolerances = ToleranceContext.Default;
+
+ public static BrepExportPreflightResult Validate(BrepBody body)
+ {
+ ArgumentNullException.ThrowIfNull(body);
+ var diagnostics = new List<BrepExportPreflightDiagnostic>();
+ var model = body.Topology;
+ int? bodyId = model.Bodies.Count() == 1 ? model.Bodies.Single().Id.Value : null;
+ var checkedEdges = new HashSet<EdgeId>();
+ var checkedFaces = 0;
+ var checkedLoops = 0;
+
+ foreach (var face in model.Faces.OrderBy(face => face.Id.Value))
+ {
+ checkedFaces++;
+ if (!body.TryGetFaceSurfaceGeometry(face.Id, out var surface) || surface is null)
+ {
+ AddError("brep-preflight-missing-support-surface", "face-support", "Face is missing its support surface.", faceId: face.Id.Value);
+ continue;
+ }
+
+ foreach (var loopId in face.LoopIds)
+ {
+ if (!model.TryGetLoop(loopId, out var loop) || loop is null)
+ {
+ AddError("brep-preflight-missing-loop", "loop", "Face references a missing loop.", faceId: face.Id.Value, loopId: loopId.Value);
+ continue;
+ }
+
+ checkedLoops++;
+ ValidateLoop(face.Id, loop, surface);
+ }
+ }
+
+ foreach (var edge in model.Edges.OrderBy(edge => edge.Id.Value))
+ {
+ if (!checkedEdges.Add(edge.Id)) continue;
+ ValidateEdge(edge);
+ }
+
+ // A shared edge is independently checked against every support surface which uses it.
+ // This catches e.g. a circle lying on its cylinder but not its conical neighbour.
+ foreach (var face in model.Faces)
+ {
+ if (!body.TryGetFaceSurfaceGeometry(face.Id, out var surface) || surface is null) continue;
+ foreach (var loopId in face.LoopIds)
+ {
+ if (!model.TryGetLoop(loopId, out var loop) || loop is null) continue;
+ foreach (var coedgeId in loop.CoedgeIds)
+ {
+ if (!model.TryGetCoedge(coedgeId, out var coedge) || coedge is null) continue;
+ if (!model.TryGetEdge(coedge.EdgeId, out var edge) || edge is null) continue;
+ ValidateTrimOnSurface(face.Id, loop.Id, coedge.EdgeId, edge, surface);
+ }
+ }
+ }
+
+ return new BrepExportPreflightResult(!diagnostics.Any(d => d.Severity == BrepExportPreflightSeverity.Error), diagnostics, model.Bodies.Count(), checkedFaces, checkedLoops, checkedEdges.Count);
+
+ void ValidateLoop(FaceId faceId, Loop loop, SurfaceGeometry surface)
+ {
+ if (loop.CoedgeIds.Count == 0)
+ {
+ AddError("brep-preflight-loop-not-closed", "loop", "Loop has no coedges.", faceId.Value, loop.Id.Value);
+ return;
+ }
+
+ var seen = new HashSet<CoedgeId>();
+ for (var i = 0; i < loop.CoedgeIds.Count; i++)
+ {
+ var coedgeId = loop.CoedgeIds[i];
+ if (!seen.Add(coedgeId))
+ AddError("brep-preflight-duplicate-coedge", "loop", "Loop reuses a coedge.", faceId.Value, loop.Id.Value, i);
+ if (!model.TryGetCoedge(coedgeId, out var coedge) || coedge is null)
+ {
+ AddError("brep-preflight-missing-coedge", "loop", "Loop references a missing coedge.", faceId.Value, loop.Id.Value, i);
+ continue;
+ }
+ if (coedge.LoopId != loop.Id)
+ AddError("brep-preflight-coedge-loop-mismatch", "loop", "Coedge belongs to another loop.", faceId.Value, loop.Id.Value, i, coedge.EdgeId.Value);
+ if (!model.TryGetEdge(coedge.EdgeId, out var edge) || edge is null)
+ {
+ AddError("brep-preflight-missing-edge", "loop", "Coedge references a missing edge.", faceId.Value, loop.Id.Value, i, coedge.EdgeId.Value);
+ continue;
+ }
+
+ var nextId = loop.CoedgeIds[(i + 1) % loop.CoedgeIds.Count];
+ if (!model.TryGetCoedge(nextId, out var next) || next is null || !model.TryGetEdge(next.EdgeId, out var nextEdge) || nextEdge is null) continue;
+ var end = coedge.IsReversed ? edge.StartVertexId : edge.EndVertexId;
+ var expectedStart = next.IsReversed ? nextEdge.EndVertexId : nextEdge.StartVertexId;
+ if (end != expectedStart)
+ AddError(i == loop.CoedgeIds.Count - 1 ? "brep-preflight-loop-not-closed" : "brep-preflight-coedge-disconnected", "loop", $"Coedge chain is disconnected: expected vertex {end.Value}, actual vertex {expectedStart.Value}.", faceId.Value, loop.Id.Value, i, coedge.EdgeId.Value);
+
+ if (coedge.NextCoedgeId != nextId)
+ AddError("brep-preflight-coedge-link-mismatch", "loop", "Coedge NextCoedgeId does not match declared loop order.", faceId.Value, loop.Id.Value, i, coedge.EdgeId.Value);
+ }
+ }
+
+ void ValidateEdge(Edge edge)
+ {
+ if (!model.TryGetVertex(edge.StartVertexId, out _) || !model.TryGetVertex(edge.EndVertexId, out _))
+ {
+ AddError("brep-preflight-missing-vertex", "edge", "Edge references a missing endpoint vertex.", edgeId: edge.Id.Value);
+ return;
+ }
+ if (!body.Bindings.TryGetEdgeBinding(edge.Id, out var binding) || !body.Geometry.TryGetCurve(binding.CurveGeometryId, out var curve) || curve is null || binding.TrimInterval is null)
+ {
+ AddError("brep-preflight-missing-curve", "edge", "Edge is missing a bound curve or trim interval.", edgeId: edge.Id.Value);
+ return;
+ }
+ if (edge.StartVertexId == edge.EndVertexId && curve.Kind is not CurveGeometryKind.Circle3 and not CurveGeometryKind.Ellipse3)
+ AddError("brep-preflight-edge-degenerate", "edge", "Non-periodic edge uses the same topology vertex at both endpoints.", edgeId: edge.Id.Value);
+ var a = Evaluate(curve, binding.TrimInterval.Value.Start);
+ var b = Evaluate(curve, binding.TrimInterval.Value.End);
+ if (a is null || b is null || !Finite(a.Value) || !Finite(b.Value))
+ AddError("brep-preflight-edge-degenerate", "edge", "Edge curve endpoint is non-finite or unsupported.", edgeId: edge.Id.Value);
+ if (a is not null && b is not null && curve.Kind is CurveGeometryKind.Line3 && Distance(a.Value, b.Value) <= Tolerances.Linear)
+ AddError("brep-preflight-edge-degenerate", "edge", "Line edge has zero geometric length.", edgeId: edge.Id.Value, deviation: Distance(a.Value, b.Value));
+ }
+
+ void ValidateTrimOnSurface(FaceId faceId, LoopId loopId, EdgeId edgeId, Edge edge, SurfaceGeometry surface)
+ {
+ if (!body.Bindings.TryGetEdgeBinding(edgeId, out var binding) || !body.Geometry.TryGetCurve(binding.CurveGeometryId, out var curve) || curve is null || binding.TrimInterval is null) return;
+ var parameters = new[] { binding.TrimInterval.Value.Start, binding.TrimInterval.Value.End, (binding.TrimInterval.Value.Start + binding.TrimInterval.Value.End) / 2d };
+ foreach (var parameter in parameters.Distinct())
+ {
+ var point = Evaluate(curve, parameter);
+ if (point is null) continue;
+ var deviation = SurfaceDeviation(surface, point.Value, out var supported);
+ if (!supported)
+ {
+ AddWarning("brep-preflight-check-unsupported", "trim-surface", $"Containment check is not implemented for {surface.Kind}.", faceId.Value, loopId.Value, edgeId: edgeId.Value, surface: surface.Kind.ToString());
+ return;
+ }
+ if (deviation > Tolerances.Linear)
+ AddError("brep-preflight-trim-off-surface", "trim-surface", $"Trim point does not lie on {surface.Kind}; deviation {deviation:G6} exceeds tolerance {Tolerances.Linear:G6}.", faceId.Value, loopId.Value, edgeId: edgeId.Value, surface: surface.Kind.ToString(), deviation: deviation);
+ }
+ }
+
+ void AddError(string code, string stage, string message, int? faceId = null, int? loopId = null, int? coedgeIndex = null, int? edgeId = null, string? surface = null, double? deviation = null) =>
+ diagnostics.Add(new(code, BrepExportPreflightSeverity.Error, stage, message, bodyId, faceId, loopId, coedgeIndex, edgeId, surface, deviation, deviation is null ? null : Tolerances.Linear, ClassificationFor(code, stage)));
+ void AddWarning(string code, string stage, string message, int? faceId = null, int? loopId = null, int? coedgeIndex = null, int? edgeId = null, string? surface = null, double? deviation = null) =>
+ diagnostics.Add(new(code, BrepExportPreflightSeverity.Warning, stage, message, bodyId, faceId, loopId, coedgeIndex, edgeId, surface, deviation, deviation is null ? null : Tolerances.Linear, ClassificationFor(code, stage)));
+ }
+
+ private static BrepExportPreflightFindingClassification ClassificationFor(string code, string stage) => code switch
+ {
+ "brep-preflight-check-unsupported" => BrepExportPreflightFindingClassification.UnsupportedCheck,
+ "brep-preflight-trim-off-surface" or "brep-preflight-missing-support-surface" => BrepExportPreflightFindingClassification.InvalidGeometry,
+ _ when stage is "loop" or "edge" => BrepExportPreflightFindingClassification.InvalidTopology,
+ _ => BrepExportPreflightFindingClassification.SuspiciousNeedsReview,
+ };
+
+ private static Point3D? Evaluate(CurveGeometry curve, double t) => curve.Kind switch
+ {
+ CurveGeometryKind.Line3 when curve.Line3 is Line3Curve line => line.Evaluate(t),
+ CurveGeometryKind.Circle3 when curve.Circle3 is Circle3Curve circle => circle.Evaluate(t),
+ CurveGeometryKind.Ellipse3 when curve.Ellipse3 is Ellipse3Curve ellipse => ellipse.Evaluate(t),
+ CurveGeometryKind.BSpline3 when curve.BSpline3 is BSpline3Curve spline => spline.Evaluate(t),
+ _ => null,
+ };
+
+ private static double SurfaceDeviation(SurfaceGeometry surface, Point3D point, out bool supported)
+ {
+ supported = true;
+ return surface.Kind switch
+ {
+ SurfaceGeometryKind.Plane when surface.Plane is PlaneSurface plane => double.Abs((point - plane.Origin).Dot(plane.Normal.ToVector())),
+ SurfaceGeometryKind.Cylinder when surface.Cylinder is CylinderSurface cylinder => double.Abs(RadialDistance(point, cylinder.Origin, cylinder.Axis) - cylinder.Radius),
+ SurfaceGeometryKind.Cone when surface.Cone is ConeSurface cone => double.Abs(RadialDistance(point, cone.Apex, cone.Axis) - double.Abs((point - cone.Apex).Dot(cone.Axis.ToVector())) * double.Tan(cone.SemiAngleRadians)),
+ SurfaceGeometryKind.Sphere when surface.Sphere is SphereSurface sphere => double.Abs(Distance(point, sphere.Center) - sphere.Radius),
+ SurfaceGeometryKind.Torus when surface.Torus is TorusSurface torus => double.Abs(double.Sqrt(double.Pow(RadialDistance(point, torus.Center, torus.Axis) - torus.MajorRadius, 2d) + double.Pow((point - torus.Center).Dot(torus.Axis.ToVector()), 2d)) - torus.MinorRadius),
+ _ => Unsupported(out supported),
+ };
+ }
+
+ private static double Unsupported(out bool supported) { supported = false; return 0d; }
+ private static double RadialDistance(Point3D point, Point3D origin, Direction3D axis) { var v = point - origin; var axial = v.Dot(axis.ToVector()); return (v - axis.ToVector() * axial).Length; }
+ private static double Distance(Point3D a, Point3D b) => (a - b).Length;
+ private static bool Finite(Point3D point) => double.IsFinite(point.X) && double.IsFinite(point.Y) && double.IsFinite(point.Z);
+}
diff --git a/Aetheris.Kernel.Core/Brep/EdgeFinishing/BrepBoundedChamfer.cs b/Aetheris.Kernel.Core/Brep/EdgeFinishing/BrepBoundedChamfer.cs
index b10b6ae1..bebaee14 100644
--- a/Aetheris.Kernel.Core/Brep/EdgeFinishing/BrepBoundedChamfer.cs
+++ b/Aetheris.Kernel.Core/Brep/EdgeFinishing/BrepBoundedChamfer.cs
@@ -83,12 +83,18 @@ public static class BrepBoundedChamfer
return KernelResult<BrepBody>.Failure([Failure($"Bounded chamfer corner resolution rejected: {reason}", "firmament.chamfer-bounded")]);
}
- if (!context.IsTrustedOrthogonalBody || !context.HasOrthogonalGeometryConstructor)
+ if (context.IsTrustedOrthogonalBody && context.HasOrthogonalGeometryConstructor)
{
- return CreateTrustedPolyhedralSingleCornerPlanarChamferBody(sourceBody, context);
+ // The trusted-body context does not carry AxisAlignedBoxExtents. Passing its
+ // default Box into CreateSingleCornerPlanarChamferBody used to throw while
+ // creating a zero-length edge. Reject before topology instead of claiming a
+ // geometry success; the synthetic constructor remains separately callable.
+ return KernelResult<BrepBody>.Failure([Failure(
+ "Bounded chamfer trusted orthogonal corner requires an explicit authoritative extents/topology witness.",
+ "firmament.chamfer-bounded")]);
}
- return CreateSingleCornerPlanarChamferBody(context);
+ return CreateTrustedPolyhedralSingleCornerPlanarChamferBody(sourceBody, context);
}
public static KernelResult<BrepBody> ChamferAxisAlignedBoxVerticalEdge(
diff --git a/Aetheris.Kernel.Core/Brep/Features/BrepExtrude.cs b/Aetheris.Kernel.Core/Brep/Features/BrepExtrude.cs
index 746e90a6..a760f5d6 100644
--- a/Aetheris.Kernel.Core/Brep/Features/BrepExtrude.cs
+++ b/Aetheris.Kernel.Core/Brep/Features/BrepExtrude.cs
@@ -64,7 +64,8 @@ public static class BrepExtrude
var faces = new List<FaceId>(n + 2)
{
AddFaceWithLoop(builder, bottomEdges.Select(EdgeUse.Forward).ToArray()),
- AddFaceWithLoop(builder, topEdges.Select(EdgeUse.Reversed).ToArray()),
+ // Reversing a boundary reverses both each coedge sense and its cyclic order.
+ AddFaceWithLoop(builder, topEdges.Reverse().Select(EdgeUse.Reversed).ToArray()),
};
for (var i = 0; i < n; i++)
diff --git a/Aetheris.Kernel.Core/Brep/Features/RevolvedProfileStackEmitter.cs b/Aetheris.Kernel.Core/Brep/Features/RevolvedProfileStackEmitter.cs
index 4fa7381b..e0d9083c 100644
--- a/Aetheris.Kernel.Core/Brep/Features/RevolvedProfileStackEmitter.cs
+++ b/Aetheris.Kernel.Core/Brep/Features/RevolvedProfileStackEmitter.cs
@@ -53,7 +53,9 @@ internal static class RevolvedProfileStackEmitter
var signature = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(signatureText)));
return KernelResult<RevolvedProfileTopologyPlan>.Success(new(
profile.ToArray(), frame, axis,
- ExpectedVertexCount: n * 2,
+ // A periodic rim and its generating seam meet at the same topology vertex.
+ // Keeping separate coincident vertices creates disconnected face loops.
+ ExpectedVertexCount: n,
ExpectedEdgeCount: (n - 1) + n,
ExpectedFaceCount: (n - 1) + 2,
ExpectedLoopCount: (n - 1) + 2,
@@ -72,9 +74,8 @@ internal static class RevolvedProfileStackEmitter
var rims = profile.Select((p, i) => centers[i] + radialDirection.ToVector() * p.X).ToArray();
var builder = new TopologyBuilder();
var seamVertices = profile.Select(_ => builder.AddVertex()).ToArray();
- var rimVertices = profile.Select(_ => builder.AddVertex()).ToArray();
var seamEdges = Enumerable.Range(0, profile.Count - 1).Select(i => builder.AddEdge(seamVertices[i], seamVertices[i + 1])).ToArray();
- var circleEdges = Enumerable.Range(0, profile.Count).Select(i => builder.AddEdge(rimVertices[i], rimVertices[i])).ToArray();
+ var circleEdges = Enumerable.Range(0, profile.Count).Select(i => builder.AddEdge(seamVertices[i], seamVertices[i])).ToArray();
var sideFaces = new FaceId[profile.Count - 1];
for (var i = 0; i < sideFaces.Length; i++)
@@ -137,7 +138,6 @@ internal static class RevolvedProfileStackEmitter
for (var i = 0; i < profile.Count; i++)
{
vertexPoints[seamVertices[i]] = rims[i];
- vertexPoints[rimVertices[i]] = rims[i];
}
var body = new BrepBody(builder.Model, geometry, bindings, vertexPoints);
var bindingValidation = BrepBindingValidator.Validate(body, requireAllEdgeAndFaceBindings: true);
diff --git a/Aetheris.Kernel.Core/Brep/Prismatic/PrismaticSectionTransitionTopologyPlan.cs b/Aetheris.Kernel.Core/Brep/Prismatic/PrismaticSectionTransitionTopologyPlan.cs
index f44a4df7..b0b9595b 100644
--- a/Aetheris.Kernel.Core/Brep/Prismatic/PrismaticSectionTransitionTopologyPlan.cs
+++ b/Aetheris.Kernel.Core/Brep/Prismatic/PrismaticSectionTransitionTopologyPlan.cs
@@ -62,7 +62,8 @@ internal static class PrismaticSectionTransitionTopologyPlanner
var faces = new List<PrismaticPlannedFace>
{
new("f:cap:bottom", PrismaticPlannedFaceKind.BottomCap, Enumerable.Range(0, n).Select(i => new PrismaticPlannedEdgeUse(sectionEdges[0, i], false)).ToArray(), null, null),
- new("f:cap:top", PrismaticPlannedFaceKind.TopCap, Enumerable.Range(0, n).Select(i => new PrismaticPlannedEdgeUse(sectionEdges[sections.Count - 1, i], true)).ToArray(), null, null),
+ // Reversing an oriented loop requires reversing its coedge order too.
+ new("f:cap:top", PrismaticPlannedFaceKind.TopCap, Enumerable.Range(0, n).Reverse().Select(i => new PrismaticPlannedEdgeUse(sectionEdges[sections.Count - 1, i], true)).ToArray(), null, null),
};
for (var s = 0; s < sections.Count - 1; s++)
for (var i = 0; i < n; i++)
diff --git a/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs b/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs
index 2549aad6..83b4fb17 100644
--- a/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs
@@ -1,5 +1,20 @@
namespace Aetheris.Kernel.Core.Step242;
+/// <summary>Controls whether export preflight findings are only reported or block serialization.</summary>
+public enum BrepExportPreflightMode
+{
+ Disabled,
+ Audit,
+ Enforce,
+}
+
+/// <summary>Named evidence tier for an export route; avoids fixture-specific exporter policy.</summary>
+public enum BrepExportPreflightPolicy
+{
+ LegacyRoute,
+ TrustedProductionRoute,
+}
+
public sealed class Step242ExportOptions
{
public string ProductName { get; init; } = "AetherisBody";
@@ -14,6 +29,15 @@ public sealed class Step242ExportOptions
public Step242HeaderMetadata HeaderMetadata { get; init; } = Step242HeaderMetadata.Deterministic;
+ /// <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.
+ /// </summary>
+ public BrepExportPreflightMode BrepExportPreflightMode { get; init; } = BrepExportPreflightMode.Audit;
+
+ /// <summary>Records why this route selected its preflight mode.</summary>
+ public BrepExportPreflightPolicy BrepExportPreflightPolicy { get; init; } = BrepExportPreflightPolicy.LegacyRoute;
+
public static Step242ExportOptions FromSourceMetadata(Step242SourceMetadata metadata)
{
static string Coalesce(string? value, string fallback) => string.IsNullOrWhiteSpace(value) ? fallback : value!;
diff --git a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
index 86ef9a0b..49830596 100644
--- a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs
@@ -21,6 +21,14 @@ public static class Step242Exporter
{
options ??= new Step242ExportOptions();
+ var preflight = options.BrepExportPreflightMode == BrepExportPreflightMode.Disabled
+ ? null
+ : BrepExportPreflight.Validate(body);
+ if (preflight is { IsValid: false } && options.BrepExportPreflightMode == BrepExportPreflightMode.Enforce)
+ {
+ return KernelResult<string>.Failure(ToKernelDiagnostics(preflight, errorsAsWarnings: false));
+ }
+
var model = body.Topology;
var bodyNodes = model.Bodies.OrderBy(b => b.Id.Value).ToArray();
if (bodyNodes.Length != 1)
@@ -112,7 +120,9 @@ public static class Step242Exporter
var shapeRepresentationId = writer.AddEntity("SHAPE_REPRESENTATION", Step242TextWriter.String(options.ProductName), Step242TextWriter.List(brepId), Step242TextWriter.Ref(repContextId));
writer.AddEntity("SHAPE_DEFINITION_REPRESENTATION", Step242TextWriter.Ref(shapeId), Step242TextWriter.Ref(shapeRepresentationId));
- return KernelResult<string>.Success(writer.Build(options.HeaderMetadata));
+ return KernelResult<string>.Success(
+ writer.Build(options.HeaderMetadata),
+ preflight is null ? null : ToKernelDiagnostics(preflight, errorsAsWarnings: true));
}
private static void EmitAuxiliaryVertexPointForVertexlessAnalyticBody(Step242TextWriter writer, BrepBody body, TopologyModel model)
@@ -185,7 +195,9 @@ public static class Step242Exporter
var loop = model.GetLoop(loopId);
var oriented = new List<string>();
- foreach (var coedgeId in loop.CoedgeIds.OrderBy(id => id.Value))
+ // Loop.CoedgeIds is the authoritative cyclic order. Sorting this list can
+ // silently turn a coherent loop into a disconnected STEP EDGE_LOOP.
+ foreach (var coedgeId in loop.CoedgeIds)
{
var coedge = model.GetCoedge(coedgeId);
@@ -687,7 +699,17 @@ public static class Step242Exporter
circleIds[edgeId] = circleId;
}
- geometryCurveId = circleId;
+ // EDGE_CURVE endpoints alone do not disambiguate the minor and major arcs
+ // of a CIRCLE for all downstream CAD kernels. Preserve the actual bounded
+ // analytic edge, rather than relying on a viewer to infer it from a wire.
+ var trim = edgeBinding.TrimInterval.Value;
+ var isFullCircle = double.Abs((trim.End - trim.Start) - (2d * double.Pi)) <= 1e-12d;
+ geometryCurveId = isFullCircle
+ ? circleId
+ : writer.AddEntity("TRIMMED_CURVE", "$", Step242TextWriter.Ref(circleId),
+ Step242TextWriter.List($"PARAMETER_VALUE({Step242TextWriter.Number(trim.Start)})"),
+ Step242TextWriter.List($"PARAMETER_VALUE({Step242TextWriter.Number(trim.End)})"),
+ Step242TextWriter.BooleanLogical(true), Step242TextWriter.Enum("PARAMETER"));
}
else if (curve.Kind == CurveGeometryKind.BSpline3 && curve.BSpline3 is BSpline3Curve spline)
{
@@ -988,6 +1010,17 @@ public static class Step242Exporter
source)
]);
+ private static IEnumerable<KernelDiagnostic> ToKernelDiagnostics(BrepExportPreflightResult result, bool errorsAsWarnings) =>
+ result.Diagnostics.Select(diagnostic => new KernelDiagnostic(
+ KernelDiagnosticCode.ValidationFailed,
+ errorsAsWarnings && diagnostic.Severity == BrepExportPreflightSeverity.Error
+ ? KernelDiagnosticSeverity.Warning
+ : diagnostic.Severity == BrepExportPreflightSeverity.Error
+ ? KernelDiagnosticSeverity.Error
+ : KernelDiagnosticSeverity.Warning,
+ $"{diagnostic.Code}: {diagnostic.Message}",
+ diagnostic.Context));
+
private static KernelResult<Point3D> FailurePoint(string message, string source) =>
KernelResult<Point3D>.Failure([
new KernelDiagnostic(
diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
index 6a10eb89..ebae54f6 100644
--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs
+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs
@@ -750,6 +750,32 @@ public static class Step242Importer
bool edgeSameSense,
int edgeCurveEntityId)
{
+ ParameterInterval? explicitTrim = null;
+ var trimmedConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "TRIMMED_CURVE");
+ if (trimmedConstructor is not null)
+ {
+ if (trimmedConstructor.Arguments.Count != 6
+ || trimmedConstructor.Arguments[1] is not Step242EntityReference basisReference)
+ {
+ return FailureCurveBinding("TRIMMED_CURVE must provide a basis curve and two parameter trims.", SourceFor(edgeCurveEntityId, "Importer.Geometry.TrimmedCurve"));
+ }
+
+ var trimResult = ReadParameterTrim(trimmedConstructor.Arguments[2], trimmedConstructor.Arguments[3], trimmedConstructor.Arguments[4], edgeCurveEntityId);
+ if (!trimResult.IsSuccess)
+ {
+ return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(trimResult.Diagnostics);
+ }
+
+ var basisResult = document.TryGetEntity(basisReference.TargetId);
+ if (!basisResult.IsSuccess)
+ {
+ return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(basisResult.Diagnostics);
+ }
+
+ curveEntity = basisResult.Value;
+ explicitTrim = trimResult.Value;
+ }
+
var lineConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "LINE");
if (lineConstructor is not null)
{
@@ -788,7 +814,9 @@ public static class Step242Importer
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(circleResult.Diagnostics);
}
- var trimResult = ComputeCircleTrim(circleResult.Value, startPoint, endPoint, edgeSameSense);
+ var trimResult = explicitTrim is { } specified
+ ? KernelResult<ParameterInterval>.Success(specified)
+ : ComputeCircleTrim(circleResult.Value, startPoint, endPoint, edgeSameSense);
if (!trimResult.IsSuccess)
{
return KernelResult<(CurveGeometry CurveGeometry, ParameterInterval TrimInterval)>.Failure(trimResult.Diagnostics);
@@ -880,6 +908,42 @@ public static class Step242Importer
return FailureCurveBinding($"EDGE_CURVE geometry '{curveEntity.Name}' is unsupported.", SourceFor(curveEntity.Id, "Importer.EntityFamily"));
}
+ private static KernelResult<ParameterInterval> ReadParameterTrim(
+ Step242Value startValue,
+ Step242Value endValue,
+ Step242Value senseValue,
+ int edgeCurveEntityId)
+ {
+ static bool TryReadParameter(Step242Value value, out double parameter)
+ {
+ parameter = double.NaN;
+ if (value is not Step242ListValue { Items.Count: 1 } list
+ || list.Items[0] is not Step242TypedValue { Name: var typeName, Arguments.Count: 1 } typed
+ || !string.Equals(typeName, "PARAMETER_VALUE", StringComparison.OrdinalIgnoreCase)
+ || typed.Arguments[0] is not Step242NumberValue number
+ || !double.IsFinite(number.Value))
+ {
+ return false;
+ }
+ parameter = number.Value;
+ return true;
+ }
+
+ if (!TryReadParameter(startValue, out var start) || !TryReadParameter(endValue, out var end)
+ || senseValue is not Step242BooleanValue { Value: var sameSense })
+ {
+ var failure = FailureCurveBinding("TRIMMED_CURVE parameter trim is malformed.", SourceFor(edgeCurveEntityId, "Importer.Geometry.TrimmedCurve"));
+ return KernelResult<ParameterInterval>.Failure(failure.Diagnostics);
+ }
+ if (!sameSense) (start, end) = (end, start);
+ if (end < start || !double.IsFinite(start) || !double.IsFinite(end))
+ {
+ var failure = FailureCurveBinding("TRIMMED_CURVE parameter interval is invalid.", SourceFor(edgeCurveEntityId, "Importer.Geometry.TrimmedCurve"));
+ return KernelResult<ParameterInterval>.Failure(failure.Diagnostics);
+ }
+ return KernelResult<ParameterInterval>.Success(new(start, end));
+ }
+
private static Step242ParsedEntity? ResolveBSplineCurveEntity(Step242ParsedEntity curveEntity)
{
var splineWithKnotsConstructor = Step242SubsetDecoder.TryGetConstructor(curveEntity.Instance, "B_SPLINE_CURVE_WITH_KNOTS");
diff --git a/Aetheris.Kernel.Firmament.Tests/AirTopFaceBoundaryChamferProductionTests.cs b/Aetheris.Kernel.Firmament.Tests/AirTopFaceBoundaryChamferProductionTests.cs
index aff9339e..c9e8ca22 100644
--- a/Aetheris.Kernel.Firmament.Tests/AirTopFaceBoundaryChamferProductionTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/AirTopFaceBoundaryChamferProductionTests.cs
@@ -1,4 +1,5 @@
using Aetheris.Kernel.Core.Air;
+using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Brep.Prismatic;
using Aetheris.Kernel.Firmament.FirmamentV2;
@@ -46,6 +47,7 @@ public sealed class AirTopFaceBoundaryChamferProductionTests
Assert.Equal(20, result.Body.Topology.Edges.Count());
Assert.Equal(10, result.Body.Topology.Faces.Count());
Assert.Contains("edge-prismatic-v1-authoritative-topology-plan-consumed", result.Diagnostics);
+ Assert.True(BrepExportPreflight.Validate(result.Body!).IsValid);
var top = result.BRepPlan.RealizationPlan.Vertices.Where(v => v.SectionIndex == 2).Select(v => v.Point).ToArray();
Assert.Equal((-width / 2d) + distance, top.Min(p => p.X), 9);
diff --git a/Aetheris.Kernel.Firmament.Tests/ChamferM6LoweringTests.cs b/Aetheris.Kernel.Firmament.Tests/ChamferM6LoweringTests.cs
index ee5090fb..a65dc680 100644
--- a/Aetheris.Kernel.Firmament.Tests/ChamferM6LoweringTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/ChamferM6LoweringTests.cs
@@ -1,4 +1,5 @@
using Aetheris.Kernel.Core.Air;
+using Aetheris.Kernel.Core.Brep;
using Aetheris.Kernel.Core.Geometry;
namespace Aetheris.Kernel.Firmament.Tests;
@@ -20,13 +21,16 @@ public sealed class ChamferM6LoweringTests
result.Construction.Witness.ReplacementProfile.Select(p => (p.X, p.Y)).ToArray());
Assert.True(result.BRepPlan!.IsAuthoritative);
Assert.NotNull(result.BRepPlan.RevolvedRealizationPlan);
- Assert.Equal(6, result.Body!.Topology.Vertices.Count());
+ // Periodic rims now share their seam vertices; the old six-vertex shape was
+ // coincident but topologically disconnected and could not be enforced.
+ Assert.Equal(3, result.Body!.Topology.Vertices.Count());
Assert.Equal(5, result.Body.Topology.Edges.Count());
Assert.Equal(4, result.Body.Topology.Faces.Count());
Assert.Equal(1, result.Body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Cylinder));
Assert.Equal(1, result.Body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Cone));
Assert.Equal(2, result.Body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Plane));
Assert.Contains("revolved-profile-authoritative-topology-plan-consumed", result.Diagnostics);
+ Assert.True(BrepExportPreflight.Validate(result.Body!).IsValid);
}
[Theory]
@@ -47,7 +51,7 @@ public sealed class ChamferM6LoweringTests
[Theory]
[InlineData("RectangularConcavePocketRim", "MissingConstructionWitness", "chamfer-missing-construction-witness:section-transition-does-not-support-holes")]
[InlineData("SingleStraightConvexEdge", "MissingConstructionWitness", "chamfer-missing-construction-witness:localized-planar-replacement-not-implemented")]
- [InlineData("AdjacentEdgeJunction", "CornerPolicyRequired", "chamfer-corner-policy-required:multiple-valid-corner-patches")]
+ [InlineData("AdjacentEdgeJunction", "ConstructionWitnessRequired", "chamfer-corner-construction-witness-required:authoritative-brep-plan")]
public void DeferredFamilies_ReturnPreciseConstructionErrors(
string family, string kind, string code)
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index 290bcdf6..f3ed2521 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -158,6 +158,10 @@ public static class FirmamentBuildAndExport
{
var finishes = (document.ModifyBlocks ?? []).SelectMany(m => (m.EdgeFinishes ?? []).Select(f => (Modify: m, Finish: f))).ToArray();
if (finishes.Length == 0) return null;
+ if (finishes.Length == 2 && finishes.All(x => string.Equals(x.Finish.Kind, "Fillet", StringComparison.Ordinal)))
+ return AirChamferFailure("localized-fillet-construction-witness-required:two-edge-junction");
+ if (finishes.Length == 2 && finishes.All(x => string.Equals(x.Finish.Kind, "Chamfer", StringComparison.Ordinal)))
+ return AirChamferFailure("localized-chamfer-construction-witness-required:two-edge-junction");
if (finishes.Length != 1 || document.Solids.Count != 1 || document.ModifyBlocks!.Count != 1
|| document.ModifyBlocks[0].Regions.Count != 0 || document.ModifyBlocks[0].SemanticHoles.Count != 0)
return AirChamferFailure("air-chamfer-production-route-requires-one-box-and-one-edge-finish");
@@ -169,6 +173,15 @@ public static class FirmamentBuildAndExport
if (solid?.Primitive is not FirmamentV2BoxRecord box || box.Size.Count != 3)
return AirChamferFailure("chamfer-unsupported-history:expected-history-known-box-or-right-circular-cylinder");
+ // AIR-FILLET-LOCALIZED-M1: semantic support-face selection only; emitted BRep IDs never enter Firmament.
+ if (string.Equals(finish.Kind, "Fillet", StringComparison.Ordinal))
+ return ExportV2LocalizedTangentBlendSingleEdgeFillet(document, solid, finish, box);
+
+ // AIR-CHAMFER-LOCALIZED-PLAN-A1: a semantic face-pair selector, never an emitted edge id.
+ if (string.Equals(finish.FaceAxis, "+X", StringComparison.Ordinal)
+ && string.Equals(finish.Target, "SharedEdgePlusZ", StringComparison.Ordinal))
+ return ExportV2LocalizedPlanarSingleEdgeChamfer(document, solid, finish, box);
+
var compiled = AirTopFaceBoundaryChamferCompiler.Compile(new(
solid.Name,
$"{solid.Name}.{finish.Name}",
@@ -186,6 +199,8 @@ public static class FirmamentBuildAndExport
{
ProductName = compiled.Feature.FeatureName,
ApplicationName = AirTopFaceBoundaryChamferCompileResult.ProductionRoute,
+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
});
if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
@@ -216,6 +231,99 @@ public static class FirmamentBuildAndExport
step.Value, compiled.Feature.FeatureId, 0, "air-chamfer", "top-face-boundary-chamfer", Air: report, ConceptIr: document.ConceptIr));
}
+ private static KernelResult<FirmamentStepExportResult> ExportV2LocalizedPlanarSingleEdgeChamfer(
+ FirmamentV2Document document,
+ FirmamentV2SolidBinding solid,
+ FirmamentV2EdgeFinishDecl finish,
+ FirmamentV2BoxRecord box)
+ {
+ var compiled = AirLocalizedPlanarReplacementChamferCompiler.Compile(new(
+ solid.Name, $"{solid.Name}.{finish.Name}", finish.Name, box.Size[0], box.Size[1], box.Size[2],
+ finish.FaceAxis, "+Z", finish.Kind, finish.Distance,
+ new AirSourceSpan(finish.SourceSpan.Start, finish.SourceSpan.Length, document.ModelName)));
+ if (!compiled.Succeeded || compiled.Body is null || compiled.Construction is null || compiled.BRepPlan?.LocalizedPlanarReplacementRealizationPlan is null)
+ return AirChamferFailure(compiled.Error?.Code ?? compiled.Feature.AdmissionReason, compiled.Diagnostics);
+
+ var body = compiled.Body;
+ var preflight = BrepExportPreflight.Validate(body);
+ if (!preflight.IsValid) return AirChamferFailure("localized-chamfer-preflight-verification-failed", preflight.Diagnostics.Select(d => d.Code));
+ if (!FirmamentManifoldChecker.IsManifold(body)) return AirChamferFailure("localized-chamfer-emitted-body-is-not-manifold");
+ var step = Step242Exporter.ExportBody(body, new Step242ExportOptions
+ {
+ ProductName = compiled.Feature.FeatureName,
+ ApplicationName = AirLocalizedPlanarReplacementChamferCompileResult.ProductionRoute,
+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
+ });
+ if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
+ var reimport = Step242Importer.ImportBody(step.Value);
+ if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value))
+ return AirChamferFailure("localized-chamfer-step-reimport-verification-failed");
+
+ var plan = compiled.Construction.TopologyPlan;
+ var witness = compiled.Construction.Witness;
+ var planes = body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Plane);
+ var report = new FirmamentAirChamferReport(
+ new("Chamfer", compiled.Feature.BodyId, compiled.Feature.FeatureId, compiled.Feature.FeatureName, "SharedEdge(+X,+Z)", finish.Distance, "mm",
+ $"{compiled.Feature.SourceSpan.Start}:{compiled.Feature.SourceSpan.Length}", compiled.Feature.Admission.ToString(), compiled.Feature.AdmissionReason,
+ new Dictionary<string, string> { ["Selection"] = "semantic Face(+X),Face(+Z)", ["MaterialSide"] = witness.MaterialSide }),
+ new("LocalizedPlanarReplacement", 0, [], "ordered-explicit-loops", "ExplicitOwnedEndpoints",
+ $"retainedFaces=2;replacementFaces=1;endpointPolicy={witness.EndpointPolicy}", true),
+ new(true, plan.ExpectedVertexCount, plan.ExpectedEdgeCount, plan.ExpectedFaceCount, plan.ExpectedLoopCount, plan.ExpectedCoedgeCount, 1,
+ "ExplicitOwnedEndpoints", plan.DeterministicSignature, "LocalizedPlanarReplacement"),
+ new(AirLocalizedPlanarReplacementChamferCompileResult.ProductionRoute, false, true, body.Topology.Vertices.Count(), body.Topology.Edges.Count(), body.Topology.Faces.Count(), Bounds(body), finish.Distance, finish.Distance, 0, 0, planes),
+ new("AP242", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true, reimport.Value.Topology.Vertices.Count(), reimport.Value.Topology.Edges.Count(), reimport.Value.Topology.Faces.Count(), Bounds(reimport.Value), true),
+ new("SharedEdge(+X,+Z)", "LocalizedPlanarReplacement", "Direct", 2, 1, "ExplicitOwnedEndpoints", new(true, plan.DeterministicSignature), "valid", false));
+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, compiled.Feature.FeatureId, 0, "air-chamfer", "localized-planar-single-edge-chamfer", Air: report, ConceptIr: document.ConceptIr));
+ }
+
+ private static KernelResult<FirmamentStepExportResult> ExportV2LocalizedTangentBlendSingleEdgeFillet(
+ FirmamentV2Document document,
+ FirmamentV2SolidBinding solid,
+ FirmamentV2EdgeFinishDecl finish,
+ FirmamentV2BoxRecord box)
+ {
+ var compiled = AirLocalizedTangentBlendFilletCompiler.Compile(new(
+ solid.Name, $"{solid.Name}.{finish.Name}", finish.Name, box.Size[0], box.Size[1], box.Size[2],
+ finish.FaceAxis, finish.Target switch { "SharedEdgePlusZ" => "+Z", "SharedEdgePlusY" => "+Y", _ => finish.Target }, finish.Kind, finish.Distance,
+ new AirSourceSpan(finish.SourceSpan.Start, finish.SourceSpan.Length, document.ModelName)));
+ if (!compiled.Succeeded || compiled.Body is null || compiled.Construction is null || compiled.BRepPlan?.LocalizedTangentBlendRealizationPlan is null)
+ return AirChamferFailure(compiled.Error?.Code ?? compiled.Feature.AdmissionReason, compiled.Diagnostics);
+
+ var body = compiled.Body;
+ var preflight = BrepExportPreflight.Validate(body);
+ if (!preflight.IsValid) return AirChamferFailure("localized-fillet-preflight-verification-failed", preflight.Diagnostics.Select(d => d.Code));
+ if (!FirmamentManifoldChecker.IsManifold(body)) return AirChamferFailure("localized-fillet-emitted-body-is-not-manifold");
+ var step = Step242Exporter.ExportBody(body, new Step242ExportOptions
+ {
+ ProductName = compiled.Feature.FeatureName,
+ ApplicationName = AirLocalizedTangentBlendFilletCompileResult.ProductionRoute,
+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
+ });
+ if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
+ var reimport = Step242Importer.ImportBody(step.Value);
+ if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value))
+ return AirChamferFailure("localized-fillet-step-reimport-verification-failed");
+
+ var plan = compiled.Construction.TopologyPlan;
+ var witness = compiled.Construction.Witness;
+ var cylinders = body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Cylinder);
+ var planes = body.Geometry.Surfaces.Count(s => s.Value.Kind == SurfaceGeometryKind.Plane);
+ var report = new FirmamentAirChamferReport(
+ new("Fillet", compiled.Feature.BodyId, compiled.Feature.FeatureId, compiled.Feature.FeatureName, "SharedEdge(+X,+Z)", finish.Distance, "mm",
+ $"{compiled.Feature.SourceSpan.Start}:{compiled.Feature.SourceSpan.Length}", compiled.Feature.Admission.ToString(), compiled.Feature.AdmissionReason,
+ new Dictionary<string, string> { ["Selection"] = "semantic Face(+X),Face(+Z)", ["MaterialSide"] = witness.MaterialSide, ["History"] = witness.Provenance }),
+ new("LocalizedTangentBlend", 0, [], "ordered-explicit-loops", "ExplicitOwnedEndpoints",
+ $"profile=QuarterCircle;sweep=Linear;radius={witness.Radius:R};axis=+Y;retainedFaces=2;replacementFaces=1", true),
+ new(true, plan.ExpectedVertexCount, plan.ExpectedEdgeCount, plan.ExpectedFaceCount, plan.ExpectedLoopCount, plan.ExpectedCoedgeCount, 0,
+ "ExplicitOwnedEndpoints", plan.DeterministicSignature, "LocalizedTangentBlend"),
+ new(AirLocalizedTangentBlendFilletCompileResult.ProductionRoute, false, true, body.Topology.Vertices.Count(), body.Topology.Edges.Count(), body.Topology.Faces.Count(), Bounds(body), finish.Distance, finish.Distance, cylinders, 0, planes),
+ new("AP242", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true, reimport.Value.Topology.Vertices.Count(), reimport.Value.Topology.Edges.Count(), reimport.Value.Topology.Faces.Count(), Bounds(reimport.Value), true),
+ LocalizedFillet: new("SharedEdge(+X,+Z)", "ConstantRadius", finish.Distance, "LocalizedTangentBlend", "QuarterCircle", "Linear", "Direct", 2, 1, "ExplicitOwnedEndpoints", new(true, plan.DeterministicSignature), "valid", false));
+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, compiled.Feature.FeatureId, 0, "air-fillet", "localized-tangent-blend-single-edge-fillet", Air: report, ConceptIr: document.ConceptIr));
+ }
+
private static KernelResult<FirmamentStepExportResult> ExportV2CircularRimChamfer(
FirmamentV2Document document,
FirmamentV2SolidBinding solid,
@@ -242,6 +350,8 @@ public static class FirmamentBuildAndExport
{
ProductName = compiled.Feature.FeatureName,
ApplicationName = AirCylinderTopRimChamferCompileResult.ProductionRoute,
+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,
+ BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute,
});
if (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
var reimport = Step242Importer.ImportBody(step.Value);
@@ -572,6 +682,8 @@ public static class FirmamentBuildAndExport
}
var semanticPmi = BuildV2SemanticPmi(document, semanticHoles, modifyTargets[0]);
+ // Semantic-hole/profile-stack and bounded-Boolean routes remain Audit until their
+ // historical coincident/seam topology is remediated producer-by-producer.
var step = Step242Exporter.ExportBody(body, semanticPmi);
if (!step.IsSuccess)
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
index b5e0035a..efcfc94c 100644
--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
@@ -44,7 +44,39 @@ public sealed record FirmamentAirChamferReport(
FirmamentAirChamferConstructionReport Construction,
FirmamentAirChamferBRepPlanReport BRepPlan,
FirmamentAirChamferMaterializationReport Materialization,
- FirmamentAirChamferStepReport Step);
+ FirmamentAirChamferStepReport Step,
+ FirmamentLocalizedChamferTrace? LocalizedChamfer = null,
+ FirmamentLocalizedFilletTrace? LocalizedFillet = null);
+
+/// <summary>Bounded report of the localized AIR path; it is evidence, never input to emission.</summary>
+public sealed record FirmamentLocalizedChamferTrace(
+ string Selection,
+ string Construction,
+ string SelectionMode,
+ int RetainedFaces,
+ int ReplacementFaces,
+ string EndpointPolicy,
+ FirmamentLocalizedChamferPlanTrace BRepPlan,
+ string Preflight,
+ bool LegacyFallback);
+
+public sealed record FirmamentLocalizedChamferPlanTrace(bool Authoritative, string Signature);
+
+/// <summary>Evidence emitted by the narrow AIR-FILLET-LOCALIZED-M1 production route.</summary>
+public sealed record FirmamentLocalizedFilletTrace(
+ string Selection,
+ string Rule,
+ double Radius,
+ string Construction,
+ string Profile,
+ string Sweep,
+ string SelectionMode,
+ int RetainedFaces,
+ int ReplacementFaces,
+ string EndpointPolicy,
+ FirmamentLocalizedChamferPlanTrace BRepPlan,
+ string Preflight,
+ bool LegacyFallback);
public sealed record FirmamentAirChamferFeatureReport(string Kind, string Body, string FeatureId, string FeatureName, string Selection, double Distance, string Unit, string SourceSpan, string Admission, string AdmissionReason, IReadOnlyDictionary<string, string>? Provenance = null);
public sealed record FirmamentAirChamferConstructionReport(
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index af66e2f9..c31286c1 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -720,11 +720,12 @@ public static class FirmamentV2Parser
var model = Regex.Match(source, @"^\s*Model\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s+(?<units>[A-Za-z_][A-Za-z0-9_]*)\b", RegexOptions.CultureInvariant);
var primitive = Regex.Match(source, @"\b(?<type>Box|Cylinder)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
var modify = Regex.Match(source, @"\bModify\s+(?<target>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
- var edge = Regex.Match(source, @"\bEdgeFinish\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
+ var edges = Regex.Matches(source, @"\bEdgeFinish\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant).Cast<Match>().ToArray();
+ var edge = edges.FirstOrDefault() ?? Match.Empty;
if (!model.Success || !primitive.Success || !modify.Success || !edge.Success || model.Groups["units"].Value != "mm"
|| Regex.Matches(source, @"\b(?:Box|Cylinder)\s+[A-Za-z_]", RegexOptions.CultureInvariant).Count != 1
|| Regex.Matches(source, @"\bModify\s+[A-Za-z_]", RegexOptions.CultureInvariant).Count != 1
- || Regex.Matches(source, @"\bEdgeFinish\s+[A-Za-z_]", RegexOptions.CultureInvariant).Count != 1)
+ || edges.Length is < 1 or > 2)
diagnostics.Add(Phase3EdgeFinishSyntaxInvalid);
if (diagnostics.Contains(Phase3EdgeFinishSyntaxInvalid))
@@ -769,8 +770,25 @@ public static class FirmamentV2Parser
? new FirmamentV2BoxRecord(values, [])
: new FirmamentV2CylinderRecord(radiusValue, heightValue);
var solid = new FirmamentV2SolidBinding(primitive.Groups["name"].Value, primitive.Groups["type"].Value, primitiveRecord);
- var finish = new FirmamentV2EdgeFinishDecl(edge.Groups["name"].Value, face.Groups["value"].Value, target.Groups["value"].Value, kind.Groups["value"].Value, distanceValue, new FirmamentV2SourceSpan(edge.Index, edgeClose - edge.Index + 1));
- var document = new FirmamentV2Document(model.Groups["name"].Value, "mm", [solid], [new FirmamentV2ModifyBlock(solid.Name, [], [], [finish])]);
+ var finishes = new List<FirmamentV2EdgeFinishDecl> { new(edge.Groups["name"].Value, face.Groups["value"].Value, target.Groups["value"].Value, kind.Groups["value"].Value, distanceValue, new FirmamentV2SourceSpan(edge.Index, edgeClose - edge.Index + 1)) };
+ foreach (var additionalEdge in edges.Skip(1))
+ {
+ var additionalOpen = source.IndexOf('{', additionalEdge.Index);
+ var additionalClose = FindMatchingBrace(source, additionalOpen);
+ var additionalBody = additionalClose < 0 ? string.Empty : source[(additionalOpen + 1)..additionalClose];
+ var additionalFace = Regex.Match(additionalBody, @"\bFace\s*:\s*(?<value>[+-][XYZ])", RegexOptions.CultureInvariant);
+ var additionalTarget = Regex.Match(additionalBody, @"\bTarget\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);
+ var additionalKind = Regex.Match(additionalBody, @"\bKind\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);
+ var additionalDistance = Regex.Match(additionalBody, @"\bDistance\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);
+ if (additionalClose < 0 || !additionalFace.Success || !additionalTarget.Success || !additionalKind.Success
+ || !additionalDistance.Success || !double.TryParse(additionalDistance.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var additionalDistanceValue) || !double.IsFinite(additionalDistanceValue))
+ {
+ diagnostics.Add(Phase3EdgeFinishSyntaxInvalid);
+ return FirmamentV2ParseResult.Failure(diagnostics.Append("firmament-v2-parse-failed").Order().ToArray());
+ }
+ finishes.Add(new(additionalEdge.Groups["name"].Value, additionalFace.Groups["value"].Value, additionalTarget.Groups["value"].Value, additionalKind.Groups["value"].Value, additionalDistanceValue, new FirmamentV2SourceSpan(additionalEdge.Index, additionalClose - additionalEdge.Index + 1)));
+ }
+ var document = new FirmamentV2Document(model.Groups["name"].Value, "mm", [solid], [new FirmamentV2ModifyBlock(solid.Name, [], [], finishes)]);
diagnostics.Add("firmament-v2-phase3-edge-finish-parsed");
diagnostics.Add("firmament-v2-parse-succeeded");
diagnostics.Sort(StringComparer.Ordinal);
diff --git a/docs/air-fillet-localized-m1.md b/docs/air-fillet-localized-m1.md
new file mode 100644
index 00000000..9d27157f
--- /dev/null
+++ b/docs/air-fillet-localized-m1.md
@@ -0,0 +1,58 @@
+# AIR-FILLET-LOCALIZED-M1 — exact localized tangent blend
+
+This production route is deliberately narrow. It admits one finite, straight, convex
+`SharedEdge(+X,+Z)` of a history-known axis-aligned rectangular `Box`, with two
+orthogonal planar supports, a positive constant radius, and no neighbouring selected
+edge or corner junction. It is not general fillet support.
+
+Firmament Phase 3 expresses the Feature AIR intent with one `EdgeFinish`:
+
+```firmament
+Model Localized mm
+Box Base { Size: [10mm, 8mm, 6mm] }
+Modify Base {
+ EdgeFinish RoundedEdge {
+ Face: +X
+ Target: SharedEdgePlusZ
+ Kind: Fillet
+ Distance: 1mm
+ }
+}
+```
+
+The source contains semantic face-pair selection, never emitted B-rep edge IDs. The
+Feature AIR preserves the body/feature identities, constant radius, material side,
+history provenance, and admission result.
+
+## Construction and plan
+
+`LocalizedTangentBlend` is the Construction AIR witness. It owns the two support
+planes, selected finite edge, material side, radius, tangent points, two quarter-circle
+profiles, cylinder axis, retained planar regions, and explicit endpoint ownership. Its
+profile is the exact circle with centre `(maxX-R, y, maxZ-R)`, swept linearly along `Y`.
+The replacement is therefore an exact `CylinderSurface`, not facets or a spline.
+
+An authoritative `LocalizedTangentBlend` BRepPlan is constructed before emission. It
+preserves the localized chamfer lane's 10 vertices, 15 edges, and 7 faces: six planes
+and one cylinder. The two tangent rails and two end arcs bound the cylinder. The emitter
+only consumes that immutable topology plan and construction witness; it does not mutate
+an existing B-rep or call the legacy bounded-filleting implementation.
+
+The common enforce-mode STEP preflight verifies closed ordered loops, shared coedge
+continuity, non-degenerate trims, and trim samples (endpoints plus midpoint) on every
+support plane and cylinder. The local route then exports AP242, reimports it, and checks
+an enclosed manifold with six planes and one cylinder.
+
+## Analytic evidence and limits
+
+For a 90-degree radius `R` fillet, the removed cross-sectional area is
+`R² - πR²/4`: the `R × R` sharp corner square minus the retained quarter-disc. Multiplying
+by the selected edge length gives the corresponding volume removal. Tests cover
+10×8×6 at R=1 and R=2, plus 12×5×7 at R=1; they also require deterministic STEP bytes,
+reimported cylinder radius/axis, tangent endpoint coordinates, and typed failures for
+zero/oversized radii, unsupported selection, and two-edge junctions.
+
+Deferred: concave or imported bodies, different support pairs, edge chains, multiple
+edges, endpoint/corner interactions, variable/asymmetric radius, and rolling-ball or
+toroidal corner resolution. The recommended next milestone is a second straight edge
+with an explicit junction Construction AIR witness and deterministic corner policy.
diff --git a/docs/air/localized-planar-single-edge-chamfer-a1.md b/docs/air/localized-planar-single-edge-chamfer-a1.md
new file mode 100644
index 00000000..71cdd640
--- /dev/null
+++ b/docs/air/localized-planar-single-edge-chamfer-a1.md
@@ -0,0 +1,27 @@
+# AIR-CHAMFER-LOCALIZED-PLAN-A1
+
+`AirLocalizedPlanarReplacementChamferCompiler` is the first production AIR route for a bounded
+edge replacement. It admits only a history-known axis-aligned Box and the semantic selector
+`Face: +X, Target: SharedEdgePlusZ` (the shared finite +X/+Z edge), with a positive equal distance
+smaller than the Box width and height.
+
+The Feature AIR selection has no emitted B-rep identifiers. Its Construction AIR witness owns the
+two planar support faces, the original finite edge, both trim lines, the chamfer quad, retained
+polygons, material side, and `ExplicitOwnedEndpoints`. The authoritative plan then owns all ten
+vertices, fifteen edges, seven ordered loops/faces, retained-face roles, the new chamfer face, and
+a deterministic signature. `AirLocalizedPlanarReplacementEmitter` consumes that plan directly;
+it does not call `BrepBoundedChamfer`, topology grafting, or a Boolean.
+
+Canonical `10 x 8 x 6, d=1` and variations `d=2` and `12 x 5 x 7, d=1` export with Enforce
+preflight and STEP reimport as 10 vertices, 15 edges, and 7 planar faces. The report records
+`LocalizedPlanarReplacement`, `Direct`, explicit endpoint ownership, an authoritative plan, and
+`legacyFallback: false`.
+
+Two simultaneous EdgeFinish declarations are intentionally parsed only far enough to return
+`localized-chamfer-construction-witness-required:two-edge-junction`. A deterministic junction
+patch and its retained/replacement ownership have not been proved, so no body or STEP is emitted.
+Utility scoring remains unused: the admitted single-edge context has exactly one candidate.
+
+The reusable fillet infrastructure is semantic selection, retained/replacement ownership,
+endpoint policy, authoritative plan emission, admission, preflight, and STEP proof. Fillets still
+need tangent arc/blend geometry, cylindrical/toroidal surfaces, and continuity/radius admission.
diff --git a/docs/implementation/air-chamfer-corner-policy-a0.md b/docs/implementation/air-chamfer-corner-policy-a0.md
new file mode 100644
index 00000000..2a55fc92
--- /dev/null
+++ b/docs/implementation/air-chamfer-corner-policy-a0.md
@@ -0,0 +1,367 @@
+# AIR-CHAMFER-CORNER-POLICY-A0 — chamfer corner-policy investigation
+
+Status: implemented investigation and typed admission prototype
+Date: 2026-08-03
+
+## Decision summary
+
+Aetheris does **not currently need utility scoring for any proven chamfer corner fixture**. Every modern hard-valid fixture has one construction family after typed classification. No fixture materializes two different authoritative BRepPlans for the same corner context.
+
+The old direct-BRep code does not provide contrary evidence. Its `JudgmentEngine` calls choose one constructive route over an always-admitted `reject` route, or choose between mutually exclusive single-edge/pair classifications. That is scored dispatch, not preference among multiple hard-valid constructions. The old claim that adjacent strips admit “miter, setback, or explicit corner face” had no materialized candidates, admission results, BRepPlans, or STEP artifacts. This milestone removes that claim from the executable deferred error.
+
+The implemented A0 rule is therefore:
+
+```text
+typed ChamferCornerContext
+ -> exhaustive structural Match
+ -> finite evidence-backed candidate set
+ -> hard admission
+ -> 0: typed error / explicit Concept witness required
+ -> 1: Direct
+ -> N: AmbiguousWithoutPreference (no invented score model)
+```
+
+`Utility` remains a representable selection mode, but no production or prototype case reaches it. It should be wired to `JudgmentEngine` only after a future fixture produces at least two distinct, exact, hard-valid, authoritative BRepPlans for the same typed context and demonstrates a real preference that is not a correctness condition.
+
+## Old JudgmentEngine review
+
+### Generic engine
+
+`Aetheris.Kernel.Core/Judgment/JudgmentEngine.cs` provides:
+
+- a candidate name;
+- an admissibility predicate;
+- a scalar score;
+- one rejection-reason callback;
+- deterministic tie breaking by priority, name, then input position.
+
+It correctly prevents an inadmissible candidate from winning. It does not itself distinguish geometric hard admission from route availability, fallback, error classification, or preference. That separation is the caller's responsibility.
+
+### Legacy direct-BRep paths
+
+| Path | Input state | Candidate choices | Hard constraints | Utility | Selection/fallback | Geometry/failure | Modern disposition |
+|---|---|---|---|---|---|---|---|
+| `ChamferAxisAlignedBoxSingleCorner` | synthetic extents, `XMaxYMaxZMax`, one distance | `planar_corner_cut`, `reject` | trihedral convexity, three incident edges, planar supports, equal/bounded distance, coherent cut, manifold flag | constant 200 for orthogonal, 150 otherwise | constructive candidate or selected `reject` | hand-authored corner body; current Enforce preflight finds disconnected coedges | Reject as modern route; useful negative archaeology only |
+| `ChamferTrustedPolyhedralSingleCorner` | trusted planar body and corner token | same two candidates | recovered points/normals, valence 3, convexity, bounds | 200/150, but there is still only one constructive candidate | old orthogonal branch passed default extents and threw; A0 now returns a diagnostic requiring an explicit witness; non-orthogonal uses local face rewrite | triangular-prism experiment exports/reimports, but has no BRepPlan | Do not admit in AIR until a topology plan owns the rewrite |
+| `ChamferTrustedPolyhedralIncidentEdgePair` | trusted orthogonal body plus two incident-axis tokens | `planar_edge_pair_cut`, `reject` | convex planar trihedron, equal/bounded distance, manifold flag, **orthogonal body** | 180 if orthogonal; the 140 non-orthogonal score is unreachable because admission requires orthogonal | constructive candidate or selected `reject` | selector-driven local face rewrite; changed STEP reimports | Geometry experiment only; no retained/replacement Construction AIR or BRepPlan |
+| `ChamferTrustedPolyhedralSingleInternalConcaveEdge` | occupied-cell preflight for one vertical concave edge, optionally one interacting edge | `planar_internal_concave_edge_cut`, `planar_concave_edge_pair_cut`, `reject` | planar source, exactly one of single/pair, equal distance, bounded envelope | constants 100 and 110 | candidates are mutually exclusive; reject otherwise | 2D loop modification followed by extrusion | Not a trihedral cavity-corner policy; preserve as legacy bounded feature code |
+
+The legacy `reject` candidate is always admissible and has score zero. When it wins, callers reinterpret a successful judgment selection as a kernel failure and splice rejection text from the losing candidates. This mixes fallback and error reporting into selection. None of these paths contains two competing geometry candidates admitted for the same context.
+
+### Friction-lab policy scoring
+
+`AirChamferPolicyLab` mixes recognition, correctness, deferral, fallback, and preference more aggressively. Candidate names include successes, invalid-input errors, deferrals, and `fallback-legacy-chamfer`; all are scored by the same engine. For example, both convex deferral candidates are admissible and constants choose `defer-convex-replacement-geometry`. Invalidity is represented as a high-scoring candidate rather than as a pre-selection failure. Its consideration values (`geometry-support`, `offset-stability`, `corner-policy`, `legacy-readiness`) were useful diagnostics during the strangler experiment, but they are not legitimate corner preferences.
+
+Keep the lab as historical evidence. Do not copy its decision-as-candidate design into modern AIR.
+
+### Modern route selection and lowering
+
+`AirRouteSelector` already has the correct simpler split:
+
+- canonical Construction AIR nodes use `Direct`;
+- finite structural Feature AIR classifications use `SwitchMatch`;
+- `JudgmentUtility` is reserved and unwired;
+- unsupported structures are explicit.
+
+`ChamferLoweringResult<T>` already prevents a failed feature-to-construction lowering from reaching topology emission. A0 extends its typed error kinds and uses it for corner resolution.
+
+## Actual corner-policy problem
+
+The first problem is not “which aesthetic patch wins?” It is whether a corner construction owns a closed, exact replacement region with coherent material side and an authoritative topology plan.
+
+The smallest fixture-supported context is `ChamferCornerContext`:
+
+```text
+CornerId AIR/construction identity, not a BRep topology ID
+Convexity Convex | Concave | Unknown
+IncidentSelectedEdgeCount selection fact
+VertexValence underlying construction-topology fact
+SupportSurfaces typed surface families
+MaterialSide RetainInterior | RetainExterior | Ambiguous
+Rule UniformEqualDistance | Asymmetric | NonUniform
+TopologyKind OpenChain | ClosedLoop | Junction
+HasConstructionHistory
+IsSymmetric
+SourceProvenance GeneratedHistoryKnown | RecoveredTopology | ExplicitConceptWitness
+hard-admission evidence flags
+AvailableWitness exact construction plus authoritative AirBRepPlan
+```
+
+Firmament does not see raw topology IDs. `CornerId` and witness identities live at the Construction AIR/BRepPlan boundary.
+
+## Fixture matrix
+
+| Fixture | Classification | Generated candidates | Hard admission | Selection | Proof/result |
+|---|---|---|---|---|---|
+| Rectangular top closed loop | convex; 2 selected edges at each valence-3 planar vertex; uniform equal distance; history-known; closed loop; symmetric | `SectionTransitionJunction` | admitted: generated profiles, closed replacement, retained/replacement ownership, manifold plan, exact authoritative BRepPlan | **Direct** | modern AIR; 12V/20E/10F; Enforce export; STEP reimport enclosed manifold; SHA-256 `DA592F...13A7` |
+| Two-edge convex box junction | convex; 2 selected of valence 3; planar; uniform; junction | `PlanarEdgePairCut` | rejected: no Construction AIR/BRepPlan **and CAD Assistant cannot read the STEP** | **Error** `ConstructionWitnessRequired` | legacy experiment changes geometry and passes Aetheris Enforce/reimport at 10V/15E/7F, exposing a false-negative internal gate; SHA-256 `DE1499...9D0F` |
+| Three-edge convex triangular-prism vertex | convex; 3 selected at valence 3; planar; uniform; junction | `PlanarTriangularCut` | rejected: no authoritative BRepPlan **and CAD Assistant cannot read the STEP** | **Error** `ConstructionWitnessRequired` | legacy experiment passes Aetheris Enforce/reimport at 8V/12E/6F, exposing the same interop gap; SHA-256 `212284...95CF` |
+| Three-edge convex synthetic box vertex | same structural class | `planar_corner_cut` in legacy code | rejected by proof gate | **Error** before trusted modern topology | nominal legacy construction fails Enforce with `brep-preflight-coedge-disconnected`; trusted orthogonal entry now fails before topology rather than throwing on default extents |
+| Concave internal trihedral corner | concave; 3 selected; valence 3; cavity material side | `ExplicitWitness` only | rejected: no exact patch/ownership/BRepPlan fixture exists | **Error** `ConstructionWitnessRequired` | old concave vertical-edge pair extrusion is a different 2D-profile family and is not evidence for this corner |
+| Asymmetric/policy constrained | closed-loop structural class with asymmetric rule | structural candidate is generated, then `UnsupportedChamferRule` | hard-rejected: no asymmetric exact construction | **Error** `UnsupportedSelection` | no syntax or score model added; verified as unscored hard rejection |
+
+The legacy two-edge and three-edge STEP files have different hashes and geometry, but they answer different selections. They are not alternative policies for one context.
+
+## Candidate-policy model
+
+A0 contains only policies backed by code or a concrete fixture:
+
+- `SectionTransitionJunction`: the modern rectangular closed-loop construction;
+- `PlanarEdgePairCut`: the legacy two-selected-edge experiment;
+- `PlanarTriangularCut`: the legacy all-three-edge corner experiment;
+- `ExplicitWitness`: the route for a validated Concept-supplied construction.
+
+`Miter`, `Setback`, `PreservePrimaryEdge`, `PreserveLargestSupportFace`, and generic `PlanarPatch` are not enums in A0. The repository has prose suggesting them but no distinct exact constructions for a common context. Adding them would turn an old assertion into type-level fiction.
+
+Each candidate produces `ChamferCornerCandidateEvidence`. Admission requires a matching `ChamferCornerConstructionWitness`, and that witness contains the authoritative `AirBRepPlan`. A direct-BRep artifact alone cannot make a candidate modern-valid.
+
+## Hard admission model
+
+The resolver treats these as elimination conditions, never scores:
+
+- supported valence and finite structural classification;
+- support-surface compatibility;
+- unambiguous material side;
+- distance inside the local envelope;
+- non-self-intersection;
+- closed replacement region;
+- retained-region ownership;
+- replacement-region ownership;
+- manifold topology;
+- exact construction availability;
+- matching authoritative BRepPlan witness.
+
+Failures are recorded per candidate as typed `ChamferCornerAdmissionFailure` values. A failed candidate has no utility score.
+
+The prototype uses evidence booleans at the boundary because each construction family currently proves them differently. A production next milestone should replace each boolean supplied by callers with validation output computed from the localized topology plan; it must not trust arbitrary authored claims.
+
+## Utility considerations
+
+No utility model is active in A0. If future fixtures prove multiple admitted plans, legitimate considerations are likely:
+
+- explicit user policy preference;
+- symmetry preservation;
+- analytic-surface preference;
+- topology simplicity / fewer added faces;
+- primary semantic edge or larger support-face preservation;
+- history continuity;
+- sliver-risk margin after hard non-self-intersection admission.
+
+The following old considerations are rejected as utility inputs:
+
+- whether geometry is supported;
+- offset/distance validity;
+- whether a corner policy exists;
+- whether legacy topology is required;
+- accept/defer/reject route status.
+
+Those are admission, availability, or error facts. Scoring them can let a large constant conceal a missing predicate.
+
+If utility becomes necessary, use the existing `JudgmentEngine<ChamferCornerUtilityContext>` only on the already-admitted evidence list. The engine must not classify the corner, construct fallback candidates, mutate BRep, or produce witnesses.
+
+## Selection traces
+
+### Closed-loop control
+
+```json
+{
+ "corner": "TopLoop.Corner0",
+ "classification": { "convexity": "Convex", "incidentSelectedEdges": 2, "vertexValence": 3, "supportSurfaces": ["Plane", "Plane", "Plane"], "topologyKind": "ClosedLoop" },
+ "candidates": [
+ { "policy": "SectionTransitionJunction", "admitted": true, "score": null, "reason": "hard invariants and authoritative PrismaticSectionTransition BRepPlan present" }
+ ],
+ "selectionMode": "Direct",
+ "selectedPolicy": "SectionTransitionJunction",
+ "constructionWitness": "PrismaticSectionTransition",
+ "bRepPlan": "authoritative; 12V/20E/10F",
+ "stepReimport": "enclosed-manifold"
+}
+```
+
+### Two-edge convex junction
+
+```json
+{
+ "corner": "Box.MaxCorner",
+ "classification": { "convexity": "Convex", "incidentSelectedEdges": 2, "vertexValence": 3, "supportSurfaces": ["Plane", "Plane", "Plane"], "topologyKind": "Junction" },
+ "candidates": [
+ { "policy": "PlanarEdgePairCut", "admitted": false, "score": null, "reason": "MissingAuthoritativeBRepPlan" }
+ ],
+ "selectionMode": "Error",
+ "error": "ConstructionWitnessRequired",
+ "legacyEvidence": { "topology": "10V/15E/7F", "enforcePreflight": "false-negative pass", "aetherisReimport": "enclosed-manifold", "cadAssistant": "read error" }
+}
+```
+
+### Three-edge convex vertex
+
+```json
+{
+ "corner": "TriangularPrism.MaxCorner",
+ "classification": { "convexity": "Convex", "incidentSelectedEdges": 3, "vertexValence": 3, "supportSurfaces": ["Plane", "Plane", "Plane"], "topologyKind": "Junction" },
+ "candidates": [
+ { "policy": "PlanarTriangularCut", "admitted": false, "score": null, "reason": "MissingAuthoritativeBRepPlan" }
+ ],
+ "selectionMode": "Error",
+ "error": "ConstructionWitnessRequired",
+ "legacyEvidence": { "topology": "8V/12E/6F", "enforcePreflight": "false-negative pass", "aetherisReimport": "enclosed-manifold", "cadAssistant": "read error" }
+}
+```
+
+### Concave trihedral corner
+
+```json
+{
+ "corner": "Pocket.CavityCorner0",
+ "classification": { "convexity": "Concave", "incidentSelectedEdges": 3, "vertexValence": 3, "supportSurfaces": ["Plane", "Plane", "Plane"], "topologyKind": "Junction" },
+ "candidates": [
+ { "policy": "ExplicitWitness", "admitted": false, "score": null, "reason": "MissingAuthoritativeBRepPlan" }
+ ],
+ "selectionMode": "Error",
+ "error": "ConstructionWitnessRequired"
+}
+```
+
+No trace has `selectionMode: Utility` because no trace has more than one admitted candidate.
+
+## Result and error model
+
+The result boundary is:
+
+```csharp
+ChamferLoweringResult<ChamferCornerConstruction>
+```
+
+The success value retains policy, selection mode, all candidate evidence, construction witness, authoritative BRepPlan, and provenance. The existing lowering error enum now includes:
+
+```text
+NoCandidatePolicy
+UnsupportedValence
+UnsupportedSurfaceCombination
+AmbiguousWithoutPreference
+InvalidMaterialSide
+MissingRetainedRegion
+MissingReplacementRegion
+ConstructionWitnessRequired
+```
+
+Existing `SelfIntersection`, `CornerPolicyRequired`, `MissingConstructionWitness`, and other lowering errors remain available. `AmbiguousWithoutPreference` is deliberately an error today; it prevents an unproved local score model from silently deciding geometry.
+
+## Implemented prototype changes
+
+- Added `ChamferCornerPolicyResolver`, the typed context, evidence, policy, selection, and witness records.
+- Extended the shared chamfer lowering error vocabulary.
+- Added direct-selection and hard-rejection tests, including proof that hard failures have no score.
+- Added an asymmetric-rule pressure test; it is hard-rejected rather than utility-ranked.
+- Corrected `AirDeferredChamferLowerer` so adjacent junctions report missing authoritative construction evidence rather than asserting several valid patches.
+- Added Enforce-export/reimport tests for legacy two-edge and non-orthogonal three-edge experiments.
+- Added a regression proving the synthetic three-edge constructor fails Enforce preflight.
+- Replaced the trusted-orthogonal three-edge exception path with a typed pre-topology failure requiring an explicit witness.
+
+No Firmament syntax, production route, STEP format, or BRepPlan semantics were expanded.
+
+## BRepPlan, STEP, and visual evidence
+
+Artifacts are under `artifacts/air-chamfer-corner-policy-a0/`:
+
+| Artifact | Authority | Enforce | Reimport/analyze | SHA-256 |
+|---|---|---|---|---|
+| `modern-closed-loop.step` | authoritative AIR BRepPlan | pass | 12V/20E/10F, 10 planes, enclosed manifold | `DA592F28636D3F1D46A5BD3B798545F67E72CC79931DBCBE3B073DC91E8713A7` |
+| `legacy-two-edge-convex-junction.step` | direct-BRep experiment only | false-negative pass | Aetheris: 10V/15E/7F enclosed; CAD Assistant: read error | `DE14995B4B99DEC293DE2D7A3CCE9D2E8083580CF3F6A0DCCC619165C1759D0F` |
+| `legacy-three-edge-convex-vertex.step` | direct-BRep experiment only | false-negative pass | Aetheris: 8V/12E/6F enclosed; CAD Assistant: read error | `212284BD9BDD6FC26D041D6C232BA796E2A8E6B5803F337EE7B9C47842CF95CF` |
+
+The two legacy artifacts prove only that Aetheris can serialize and re-read its own changed planar topology. They do **not** prove STEP interoperability or a hard-valid corner: CAD Assistant reports “Error occurred reading STEP file” for both. Neither has Construction AIR retained/replacement ownership or an authoritative BRepPlan. The fact that `BrepExportPreflight` Enforce and `Step242Importer` accept both is a concrete validation gap to close before either route can be admitted.
+
+CAD Assistant independently rejected both legacy corner artifacts at import. The user supplied the three-edge error capture; the same read failure occurred for the two-edge file. No legacy junction artifact is credited with an independent visual pass. The modern rectangular loop remains covered by its existing CAD/STEP evidence. This is a hard-admission failure for the legacy candidates and a false negative in the current internal preflight/reimport combination.
+
+The CLI planar volume result was not used for admission: a 10×8×6 control box reports 160 rather than 480, so the current signed-shell volume path is not a reliable comparison oracle for these fixtures.
+
+## Recommended modern architecture
+
+1. Feature AIR owns semantic edge-finish intent and typed selection.
+2. A construction-family classifier creates `ChamferCornerContext` without raw Firmament BRep IDs.
+3. Exhaustive Match enumerates only implemented candidates for that classification.
+4. Each candidate planner attempts an exact localized Construction AIR witness and authoritative BRepPlan.
+5. A shared hard-admission validator checks plan topology, ownership, material side, distance, intersections, exactness, and manifold closure.
+6. Zero admitted plans returns a typed error or validates an explicit Concept witness.
+7. One admitted plan is selected directly.
+8. More than one admitted plan is initially `AmbiguousWithoutPreference`. Once fixture evidence establishes stable considerations, pass only those admitted plans to `JudgmentEngine`.
+9. The selected witness alone enters BRep emission. There is no legacy fallback.
+
+This is option **D** for JudgmentEngine: keep it available for future ambiguous cases, while Match/direct selection is the complete architecture for today's supported fixtures.
+
+## Fillet-readiness assessment
+
+Reusable for fillets now:
+
+- typed corner classification;
+- finite candidate enumeration;
+- hard admission before ranking;
+- candidate evidence and typed errors;
+- retained/replacement ownership requirements;
+- direct-versus-ambiguous selection mode;
+- explicit Concept witness path;
+- authoritative BRepPlan boundary.
+
+Fillet-specific work still required:
+
+- tangent arc profiles;
+- cylinders, tori, rolling-ball or other blend surfaces;
+- radius propagation;
+- tangent/curvature continuity checks;
+- fillet-specific self-intersection and setback construction.
+
+The architecture is ready for a **single bounded fillet construction with no interacting junction**. It is not mature enough to claim a corner-bearing fillet milestone: even chamfer two-edge and trihedral junctions lack authoritative localized BRepPlans, and no ambiguous preference case is proven.
+
+## Decision record
+
+**Keep:**
+
+- `JudgmentEngine` as the repository's deterministic utility ranker;
+- `ChamferLoweringResult<T>` as the Feature AIR → Construction AIR result boundary;
+- direct/switch selection for canonical and closed structural cases;
+- legacy chamfer experiments as regression and negative evidence;
+- explicit Concept witnesses for cases automatic lowering cannot prove.
+
+**Change:**
+
+- move all correctness predicates into hard admission;
+- make construction witnesses and authoritative BRepPlans prerequisites for candidate admission;
+- make adjacent-junction deferral say what is actually missing;
+- fail trusted orthogonal legacy corner requests before topology rather than throwing;
+- treat internal Enforce/reimport success as insufficient when independent OCCT import fails;
+- use `JudgmentEngine` only on an admitted candidate list if that list ever has size greater than one.
+
+**Reject:**
+
+- scoring `accept`, `reject`, `defer`, and `fallback` as peer candidates;
+- always-admitted synthetic reject candidates;
+- the unproved assertion that miter, setback, and explicit patch are all valid;
+- speculative policy enums without geometry fixtures;
+- metadata-only success or silent legacy fallback;
+- utility penalties for manifoldness, support compatibility, material side, distance, intersection, ownership, exactness, or plan boundedness.
+
+**Defer:**
+
+- a utility weight model;
+- `PreservePrimaryEdge` / `PreserveLargestSupportFace` / symmetry preferences;
+- asymmetric and nonuniform junctions;
+- recovered/imported topology corner resolution;
+- concave trihedral construction;
+- Firmament corner-policy syntax;
+- corner-bearing fillets.
+
+**Next implementation milestone:**
+
+`AIR-CHAMFER-LOCALIZED-PLAN-A1` — implement one history-known planar localized replacement as Construction AIR plus authoritative BRepPlan, first for a single straight convex edge with explicit end ownership; then extend that same plan to the two-edge convex junction and materialize at least two policies only if the geometry genuinely supports them. Add plan-derived hard-admission validators and CAD Assistant smoke before introducing utility ranking.
+
+## Validation record
+
+- `dotnet restore Aetheris.slnx`: passed.
+- `dotnet build Aetheris.slnx -f net10.0 --no-restore /m:1`: passed with 0 errors; existing C#/xUnit and JavaScript package-audit warnings remain.
+- Core requested filter (`Judgment|Utility|Corner|Chamfer|BrepPlan|Air`): 113 passed, 0 failed.
+- Firmament requested filter (`Corner|Chamfer|Air|Concept|Construction|Step`): 249 passed, 0 failed.
+- CLI requested filter (`Corner|Chamfer|Air|Step|Analyze`): 221 passed, 4 failed. All four are ordinary box volume assertions: expected 480/576/672-family volumes are reported at one third of the expected value. The failure reproduces sequentially and matches the A0 control-box observation. A0 does not touch volume analysis; this is recorded rather than hidden.
+- Focused A0 resolver/legacy evidence tests and `ChamferM6LoweringTests`: passed.
+- Modern rectangular loop fixture built through the real CLI path; authoritative BRepPlan, Enforce export, Aetheris STEP reimport, and changed topology passed.
+- Both legacy junction STEP artifacts passed Aetheris Enforce/reimport but failed CAD Assistant import. They remain hard-rejected and expose an internal validation false negative.
diff --git a/docs/implementation/brep-export-preflight-a1-remediation.md b/docs/implementation/brep-export-preflight-a1-remediation.md
new file mode 100644
index 00000000..eee924c3
--- /dev/null
+++ b/docs/implementation/brep-export-preflight-a1-remediation.md
@@ -0,0 +1,49 @@
+# BREP-EXPORT-PREFLIGHT-A1 remediation
+
+## Decision
+
+**B. Keep global `Audit`; enforce trusted AIR chamfer production routes.**
+`Step242ExportOptions` remains Audit/LegacyRoute by default. The two explicitly bounded
+Firmament V2 AIR routes request Enforce/TrustedProductionRoute immediately before STEP
+writer construction:
+
+- `AirPrismaticTopFaceBoundaryChamfer` (rectangular top-loop chamfer)
+- `AirRevolutionProfileTopRimChamfer` (circular top-rim chamfer)
+
+Both routes export, reimport, and are manifold after preflight. Semantic-hole,
+template-hole, ordinary box/extrusion, imported legacy, and bounded Boolean paths stay
+Audit until their independent producer corpus is clean.
+
+## Audit inventory and classification
+
+| Code | Producer / fixture family | Classification | A1 result |
+| --- | --- | --- | --- |
+| `brep-preflight-trim-off-surface` | malformed plane/cylinder/cone trim fixtures | InvalidGeometry | Enforce blocks before STEP text; retained negative coverage. |
+| `brep-preflight-coedge-disconnected` | `RevolvedProfileStackEmitter`, circular top-rim chamfer | InvalidTopology | Fixed: periodic rim now reuses the generating seam vertex. |
+| `brep-preflight-coedge-disconnected` | `PrismaticSectionTransitionTopologyPlanner`, rectangular top-loop chamfer | InvalidTopology | Fixed: reversed top cap also reverses coedge order. |
+| `brep-preflight-check-unsupported` | linear extrusion, surface-of-revolution, B-spline surface imports | UnsupportedCheck | Warning only; not an enforcement failure by itself. |
+| periodic single-edge circle seam | cylinder/cone analytic fixtures | ValidLegacyRepresentation | Accepted when endpoint topology and closed loop agree. |
+| older hole/profile-stack and Boolean topology | semantic holes, templates, bounded Boolean corpus | SuspiciousNeedsReview | Remains Audit; no serialization repair is applied. |
+
+The report now carries the machine-readable `Classification` enum on every diagnostic.
+Topology/edge contradictions are `InvalidTopology`; trim/support contradictions are
+`InvalidGeometry`; unavailable containment coverage is `UnsupportedCheck`.
+
+## Producer proof and artifacts
+
+The circular producer changed from six coincident vertices to three shared seam vertices;
+edge count (5), face count (4), analytic cylinder/cone/plane surfaces, and reimport remain
+unchanged. Its representative artifact hash is
+`B64A56F1ECD65324E3A2ED54302FFEF9188F4800E2D6DBE008E09C8F450C9699`.
+The rectangular cap change alters only oriented top-cap coedge order; its representative
+artifact hash is `DA592F28636D3F1D46A5BD3B798545F67E72CC79931DBCBE3B073DC91E8713A7`.
+These are intentional topology corrections, not snapshot updates.
+
+## Global Enforce blockers
+
+Global Enforce is blocked by legacy semantic-hole/profile-stack and bounded-Boolean
+producers, plus unsupported containment checks for imported non-analytic surface families.
+Before changing the default, each producer needs a clean audit corpus, reimport proof, and
+an explicit determination that remaining warnings are UnsupportedCheck or
+ValidLegacyRepresentation. CAD Assistant was not available in this environment; CLI
+reimport/manifold checks are the authoritative evidence recorded here.