Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add imported through-hole removal planning
Yuechen Li1933f805b112
diff --git a/Aetheris.CLI.Tests/ImportedFeatureAssistanceTests.cs b/Aetheris.CLI.Tests/ImportedFeatureAssistanceTests.csindex d15ed4c5..16ecad2d 100644--- a/Aetheris.CLI.Tests/ImportedFeatureAssistanceTests.cs+++ b/Aetheris.CLI.Tests/ImportedFeatureAssistanceTests.cs@@ -68,4 +68,38 @@ public sealed class ImportedFeatureAssistanceTestsAssert.Contains("firmament-lock-rebind-required",stdout.ToString());Assert.Equal(receipt,File.ReadAllText(lockPath));}+ [Theory] [InlineData(false)] [InlineData(true)]+ public void Ftc09_PrincipalYHole_PlanAndLockedBuildAgree(bool remove)+ {+ var root = new DirectoryInfo(AppContext.BaseDirectory);+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx"))) root = root.Parent;+ var input = Path.Combine(root!.FullName, "testdata/step242/nist/FTC/nist_ftc_09_asme1_ap242-e1.stp");+ var directory = Path.Combine(root.FullName, "artifacts/local/ftc09-direct-edit/tests", Guid.NewGuid().ToString("N"));+ var source = Path.Combine(directory, "revision.firmament");+ var stdout = new StringWriter(); var stderr = new StringWriter();+ var args = new List<string> { "imported-features", "plan", input, "--candidate", "through-hole:step-1255+1282", "--as", "MountHole",+ "--geometry-only", "--source-out", source, "--json" };+ args.AddRange(remove ? new[]{"--remove"} : new[]{"--offset", "15.09", "0.05"});+ Assert.Equal(0, CliRunner.Run(args.ToArray(), stdout, stderr));+ using var plan = JsonDocument.Parse(stdout.ToString());+ Assert.Equal("Built", plan.RootElement.GetProperty("plan").GetProperty("admission").GetString());+ var authored = File.ReadAllText(source);+ Assert.DoesNotContain("textSha256", authored);+ Assert.DoesNotContain("999999", authored);+ Assert.Contains("Source.MountHole.exit.Y", authored);+ if (!remove) Assert.Contains("diameter: Source.MountHole.diameter", authored);+ Assert.True(File.Exists(Path.Combine(directory,"firmament.lock.toml")));+ stdout.GetStringBuilder().Clear();+ Assert.Equal(0, CliRunner.Run(["validate", source, "--locked", "--json"], stdout, stderr));+ using var validation = JsonDocument.Parse(stdout.ToString());+ Assert.Equal("Built", validation.RootElement.GetProperty("firmamentV2Validation").GetProperty("validationLevel").GetString());+ stdout.GetStringBuilder().Clear();+ Assert.Equal(0, CliRunner.Run(["build", source, "--locked", "--output", Path.Combine(directory,"revision.step"), "--json"], stdout, stderr));+ using var build = JsonDocument.Parse(stdout.ToString());+ Assert.Equal(1, build.RootElement.GetProperty("featureCount").GetInt32());+ var report = build.RootElement.GetProperty(remove ? "importedHoleRemoval" : "importedHoleRevision");+ Assert.Equal(156, report.GetProperty("preservedFaces").GetInt32());+ Assert.Equal(6.35, report.GetProperty("diameter").GetDouble(), 8);+ Assert.Empty(stderr.ToString());+ }}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex e39746fa..1c343980 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -589,9 +589,10 @@ public static class CliRunnerpiping = build.Value.Export.Piping,gear = build.Value.Export.Gear,thread = build.Value.Export.Thread,- featureCount = (build.Value.Export.Features?.Count ?? 0) + (build.Value.Export.EngineeringFeatures?.Count ?? 0) + (build.Value.Export.Perforation is null ? 0 : 1) + (build.Value.Export.ImportedHoleRevision is null ? 0 : 1),+ featureCount = (build.Value.Export.Features?.Count ?? 0) + (build.Value.Export.EngineeringFeatures?.Count ?? 0) + (build.Value.Export.Perforation is null ? 0 : 1) + (build.Value.Export.ImportedHoleRevision is null ? 0 : 1) + (build.Value.Export.ImportedHoleRemoval is null ? 0 : 1),inlineStepMigration = build.Value.Export.InlineStepMigration,importedHoleRevision = build.Value.Export.ImportedHoleRevision,+ importedHoleRemoval = build.Value.Export.ImportedHoleRemoval,inlineStepReplacementAssist = build.Value.Export.InlineStepReplacementAssist,diagnostics = build.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, sourcePath, diagnosticSource)),pmiExportEvidence = newdiff --git a/Aetheris.CLI/ImportedFeaturesCommand.cs b/Aetheris.CLI/ImportedFeaturesCommand.csindex bdb9077a..035878ec 100644--- a/Aetheris.CLI/ImportedFeaturesCommand.cs+++ b/Aetheris.CLI/ImportedFeaturesCommand.cs@@ -12,7 +12,7 @@ namespace Aetheris.CLI;internal static class ImportedFeaturesCommand{const string Usage = "Usage: aetheris imported-features inspect <part.step> [--import-tolerance <mm>] [--json]\n"- + " aetheris imported-features plan <part.step> --candidate <id> --as <name> (--offset <dx> <dy> | --to <x> <y> <z>) --geometry-only [--clearance <mm>] [--source-out <file.firmament>] [--import-tolerance <mm>] [--json]";+ + " aetheris imported-features plan <part.step> --candidate <id> --as <name> (--offset <du> <dv> | --to <x> <y> <z> | --remove) --geometry-only [--clearance <mm>] [--source-out <file.firmament>] [--import-tolerance <mm>] [--json]";internal static int Run(string[] args, TextWriter stdout, TextWriter stderr, JsonSerializerOptions options){@@ -25,7 +25,7 @@ internal static class ImportedFeaturesCommandvar input = Path.GetFullPath(args[1]);string? candidate = null, alias = null, output = null;Point3D? target = null; (double X, double Y)? offset = null;- var geometryOnly = false; var tolerance = .001; var clearance = .1;+ var remove = false; var geometryOnly = false; var tolerance = .001; var clearance = .1;var seen = new HashSet<string>();for (var i = 2; i < args.Length; i++){@@ -41,6 +41,7 @@ internal static class ImportedFeaturesCommandcase "--as": alias = Next(); break;case "--source-out": output = Next(); break;case "--geometry-only": geometryOnly = true; break;+ case "--remove": remove = true; break;case "--import-tolerance": tolerance = Number(); break;case "--clearance": clearance = Number(); break;case "--to": target = new(Number(), Number(), Number()); break;@@ -64,41 +65,57 @@ internal static class ImportedFeaturesCommand}return 0;}- if (candidate is null || alias is null || target.HasValue == offset.HasValue)- throw new ArgumentException("Plan requires --candidate, --as and exactly one of --offset/--to.");+ if (candidate is null || alias is null || (target.HasValue ? 1 : 0) + (offset.HasValue ? 1 : 0) + (remove ? 1 : 0) != 1)+ throw new ArgumentException("Plan requires --candidate, --as and exactly one of --offset/--to/--remove.");if (offset is { } delta){var selected = inspection.Discovery.Candidates.SingleOrDefault(c => c.Id == candidate);if (selected?.Center is not { } center) throw new ArgumentException("Candidate has no proved through-hole center; inspect again.");- target = new(center.X + delta.X, center.Y + delta.Y, center.Z);+ target = selected.AxisIndex switch { 0 => new(center.X, center.Y + delta.X, center.Z + delta.Y), 1 => new(center.X + delta.X, center.Y, center.Z + delta.Y), _ => new(center.X + delta.X, center.Y + delta.Y, center.Z) };}var outputPath = Path.GetFullPath(output ?? Path.Combine("artifacts", "local", "imported-features", "revision.firmament"));if (string.Equals(outputPath, input, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) throw new ArgumentException("Source output must not overwrite the imported STEP.");if (!Path.GetExtension(outputPath).Equals(".firmament", StringComparison.OrdinalIgnoreCase)) throw new ArgumentException("Source output must use .firmament extension.");var directory = Path.GetDirectoryName(outputPath)!;- var plan = FirmamentImportedFeatures.PlanMove(inspection, candidate, alias, target!.Value, geometryOnly,- Path.GetRelativePath(directory, input).Replace('\\', '/'), directory, clearance);- if (!plan.IsSuccess) return Failure(plan.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, "generated revision")));- var dependencies = FirmamentDependencies.InspectSource(plan.Value.Source, outputPath);+ string generatedSource; object details; IReadOnlyList<KernelDiagnostic> planDiagnostics;+ var reference = Path.GetRelativePath(directory, input).Replace('\\', '/');+ if (remove)+ {+ var plan = FirmamentImportedFeatures.PlanRemove(inspection, candidate, alias, geometryOnly, reference, directory, clearance);+ if (!plan.IsSuccess) return Failure(plan.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, "generated removal")));+ generatedSource = plan.Value.Source; details = plan.Value; planDiagnostics = plan.Diagnostics;+ }+ else+ {+ var plan = FirmamentImportedFeatures.PlanMove(inspection, candidate, alias, target!.Value, geometryOnly, reference, directory, clearance);+ if (!plan.IsSuccess) return Failure(plan.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, "generated revision")));+ generatedSource = plan.Value.Source; details = plan.Value; planDiagnostics = plan.Diagnostics;+ }+ var dependencies = FirmamentDependencies.InspectSource(generatedSource, outputPath);if (!dependencies.IsSuccess) return Failure(DependencyLockCommand.Present(dependencies.Diagnostics, outputPath));// The normal AST owns the field span; the generated source keeps// engineering intent while the generated receipt keeps byte identity.- var pin = FirmamentSyntaxTraversal.Statements(FirmamentSyntaxParser.Parse(plan.Value.Source).Document)+ var pin = FirmamentSyntaxTraversal.Statements(FirmamentSyntaxParser.Parse(generatedSource).Document).OfType<FieldSyntax>().Single(f => f.Name.Text == "textSha256");- var authored = plan.Value.Source.Remove(pin.Span.Start, pin.Span.Length);+ var authored = generatedSource.Remove(pin.Span.Start, pin.Span.Length);var lockPath = Path.Combine(directory, FirmamentDependencyLock.FileName);Directory.CreateDirectory(directory);var previousSource = File.Exists(outputPath) ? File.ReadAllBytes(outputPath) : null;var previousLock = File.Exists(lockPath) ? File.ReadAllBytes(lockPath) : null;var committed = false;- var savedPlan = plan.Value;+ object savedPlan = details;try{File.WriteAllText(lockPath, dependencies.Manifest!.ToToml());File.WriteAllText(outputPath, authored);var qualified = FirmamentBuildAndExport.CompileSource(authored, directory);if (!qualified.IsSuccess) return Failure(qualified.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, outputPath)));- savedPlan = plan.Value with { Source = authored, Revision = qualified.Value.ImportedHoleRevision!, Export = qualified.Value };+ savedPlan = details switch+ {+ ImportedFeatureMovePlan move => move with { Source = authored, Revision = qualified.Value.ImportedHoleRevision!, Export = qualified.Value },+ ImportedFeatureRemovalPlan removal => removal with { Source = authored, Removal = qualified.Value.ImportedHoleRemoval!, Export = qualified.Value },+ _ => throw new InvalidOperationException("Unknown imported edit plan.")+ };committed = true;}finally@@ -109,9 +126,16 @@ internal static class ImportedFeaturesCommandif (previousLock is null) File.Delete(lockPath); else File.WriteAllBytes(lockPath, previousLock);}}- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { success = true, input, sourcePath = outputPath, lockPath, plan = savedPlan,- diagnostics = plan.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, "generated revision")) }, options));- else stdout.WriteLine($"Built plan for {alias}: {outputPath}\nOriginal source PMI excluded explicitly; replacement PMI is generated.");+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new+ {+ success = true,+ input,+ sourcePath = outputPath,+ lockPath,+ plan = savedPlan,+ diagnostics = planDiagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, "generated revision"))+ }, options));+ else stdout.WriteLine($"Built {(remove ? "removal" : "move")} plan for {alias}: {outputPath}\nOriginal source PMI excluded explicitly; {(remove ? "the retired hole has no successor PMI" : "replacement PMI is generated")}.");return 0;}catch (Exception error) when (error is ArgumentException or IOException or UnauthorizedAccessException)diff --git a/Aetheris.Kernel.Core.Tests/Brep/Features/Ftc09ThroughHoleTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Features/Ftc09ThroughHoleTests.csnew file mode 100644index 00000000..f9c1caaa--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Brep/Features/Ftc09ThroughHoleTests.cs@@ -0,0 +1,147 @@+using System.Text.Json;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Brep.Queries;+using Aetheris.Kernel.Core.Import;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Core.Tests.Step242;++namespace Aetheris.Kernel.Core.Tests.Brep.Features;++public sealed class Ftc09ThroughHoleTests+{+ const string Path = "testdata/step242/nist/FTC/nist_ftc_09_asme1_ap242-e1.stp";+ const string Candidate = "through-hole:step-1255+1282";+ static BrepBody Source => Step242Corpus.Body(Path);++ [Fact, Trait("Category", "SlowCorpus")]+ public void SelectedSolid_DoesNotAcquireFacesFromSeparateSurfaceModels()+ {+ var source = Source;+ Assert.Equal(158, source.Topology.Faces.Count());+ Assert.Equal(454, source.Topology.Edges.Count());+ Assert.Equal(300, source.Topology.Vertices.Count());+ Assert.DoesNotContain(source.Bindings.FaceBindings, f => f.SourceStepEntityId == 6064);+ Assert.Equal(ImportQualificationStatus.Qualified, source.ImportQualification!.GeometryStatus);+ Assert.All(source.Topology.Coedges.GroupBy(c => c.EdgeId), g =>+ {+ Assert.Equal(2, g.Count()); Assert.NotEqual(g.First().IsReversed, g.Last().IsReversed);+ });+ var discovery = BrepThroughHoleRevision.Discover(source);+ Assert.True(discovery.Qualified);+ Assert.Equal(59, discovery.Candidates.Count);+ Assert.Equal(25, discovery.Candidates.Count(c => c.CanPlan));+ Assert.All(discovery.Candidates.Where(c => !c.Recognized), c => Assert.NotEmpty(c.Diagnostics));+ var hole = Assert.Single(discovery.Candidates, c => c.Id == Candidate);+ Assert.Equal(1, hole.AxisIndex); Assert.Equal(6.35, hole.Diameter, 6);+ Assert.Equal(3.03784, hole.Depth!.Value, 6);+ // A cylindrical fragment of a slot or countersink cannot masquerade as a round hole.+ foreach (var id in new[]{"through-hole:step-198", "through-hole:step-811+838", "through-hole:step-3558"})+ {+ var unsupported = discovery.Candidates.Single(c => c.Id == id);+ Assert.False(unsupported.CanPlan);+ Assert.False(BrepThroughHoleRevision.PlanRemove(source, id, "Unsafe").IsSuccess);+ Assert.False(BrepThroughHoleRevision.PlanMove(source, id, "Unsafe", new(-70,3.03784,19.1)).IsSuccess);+ }+ }++ [Theory, Trait("Category", "SlowCorpus")]+ [InlineData(false)]+ [InlineData(true)]+ public void MoveOrRemove_PreservesResidualGeometryAndChangesOnlyTheSelectedVoid(bool remove)+ {+ var source = Source; var before = JsonSerializer.Serialize(source.Topology);+ var selected = BrepThroughHoleRevision.Discover(source).Candidates.Single(c => c.Id == Candidate);+ var target = new Point3D(-70, selected.Center!.Value.Y, 19.1);+ var planned = BrepThroughHoleRevision.PlanMove(source, Candidate, "MountHole", target);+ Assert.True(planned.IsSuccess, string.Join(" | ", planned.Diagnostics.Select(d => d.Message)));+ BrepBody body;+ if (remove)+ {+ var removed = BrepThroughHoleRevision.PlanRemove(source, Candidate, "MountHole");+ Assert.True(removed.IsSuccess, string.Join(" | ", removed.Diagnostics.Select(d => d.Message)));+ body = removed.Value.Removal.Body;+ Assert.Equal(156, removed.Value.Removal.FaceCorrespondence.Count);+ Assert.All(removed.Value.Removal.RetiredWallFaces, id => Assert.False(removed.Value.Removal.FaceCorrespondence.ContainsKey(id)));+ }+ else body = planned.Value.Revision.Body;+ Assert.Equal(remove ? 156 : 158, body.Topology.Faces.Count());+ Assert.Equal(remove ? 448 : 454, body.Topology.Edges.Count());+ Assert.Equal(remove ? 296 : 300, body.Topology.Vertices.Count());+ foreach (var face in source.Topology.Faces.Where(f => !selected.WallFaces.Contains(f.Id.Value)))+ {+ Assert.Equal(source.GetFaceSurface(face.Id), body.GetFaceSurface(face.Id));+ Assert.Equal(source.Bindings.GetFaceBinding(face.Id), body.Bindings.GetFaceBinding(face.Id));+ if (face.Id.Value != selected.EntryFace && face.Id.Value != selected.ExitFace)+ Assert.Equal(face.LoopIds, body.Topology.GetFace(face.Id).LoopIds);+ }+ foreach (var edge in source.Topology.Edges.Where(e => body.Topology.Edges.Any(b => b.Id == e.Id)))+ {+ Assert.Equal(edge, body.Topology.GetEdge(edge.Id));+ Assert.Equal(source.GetEdgeCurve(edge.Id), body.GetEdgeCurve(edge.Id));+ Assert.Equal(source.Bindings.GetEdgeBinding(edge.Id), body.Bindings.GetEdgeBinding(edge.Id));+ }+ foreach (var vertex in source.Topology.Vertices.Where(v => body.Topology.Vertices.Any(b => b.Id == v.Id)))+ {+ Assert.True(source.TryGetVertexPoint(vertex.Id, out var oldPoint));+ Assert.True(body.TryGetVertexPoint(vertex.Id, out var newPoint)); Assert.Equal(oldPoint, newPoint);+ }+ var coedges = body.Topology.Coedges.Select(c => c.Id).ToHashSet();+ Assert.All(source.Bindings.PcurveBindings.Where(p => coedges.Contains(p.CoedgeId)), p => Assert.Contains(p, body.Bindings.PcurveBindings));+ Assert.Equal(before, JsonSerializer.Serialize(source.Topology));+ AssertPlateBounds(body);+ // Independent trimmed-support queries witness stock versus an opening.+ // Whole-body ray consensus is Unknown for this mixed-spline corpus body;+ // do not weaken that query or pretend an unknown result proves occupancy.+ AssertSupport(source, selected.Center.Value, false);+ AssertSupport(body, selected.Center.Value, true);+ AssertSupport(body, target, remove);+ Assert.True(BrepPcurveValidator.Validate(body, .001, requireEveryCoedge: true, samples: 1025).IsValid);+ var exported = Step242Exporter.ExportBody(body, new Step242ExportOptions { BrepExportPreflightMode = BrepExportPreflightMode.Enforce });+ Assert.True(exported.IsSuccess, string.Join(" | ", exported.Diagnostics.Select(d => d.Message)));+ var imported = Step242Importer.ImportBody(exported.Value);+ Assert.True(imported.IsSuccess);+ Assert.Equal(ImportQualificationStatus.Qualified, imported.Value.ImportQualification!.GeometryStatus);+ Assert.Equal(body.Topology.Faces.Count(), imported.Value.Topology.Faces.Count());+ AssertPlateBounds(imported.Value);+ AssertSupport(imported.Value, selected.Center.Value, true);+ AssertSupport(imported.Value, target, remove);+ }++ static void AssertSupport(BrepBody body, Point3D point, bool expectedMaterial)+ {+ foreach (var y in new[] { 0d, point.Y })+ {+ var support = body.Topology.Faces.Where(f => body.GetFaceSurface(f.Id).Plane is { } p+ && System.Math.Abs(p.Origin.Y - y) < 1e-6 && System.Math.Abs(p.Normal.Y) > .99)+ .MaxBy(f => f.LoopIds.Count)!;+ Assert.True(AnalyticPlanarFaceDomain.TryContainsInPlanarFace(body, support.Id, point with { Y = y },+ Core.Numerics.ToleranceContext.Default, default, out var material));+ Assert.Equal(expectedMaterial, material);+ }+ }++ static void AssertPlateBounds(BrepBody body)+ {+ var points = body.Topology.Vertices.Select(v => { Assert.True(body.TryGetVertexPoint(v.Id, out var p)); return p; }).ToArray();+ Assert.Equal(-95.25, points.Min(p => p.X), 7); Assert.Equal(95.25, points.Max(p => p.X), 7);+ Assert.Equal(0, points.Min(p => p.Y), 7); Assert.Equal(3.03784, points.Max(p => p.Y), 7);+ Assert.Equal(-139.7, points.Min(p => p.Z), 7); Assert.Equal(139.7, points.Max(p => p.Z), 7);+ }++ [Fact, Trait("Category", "SlowCorpus")]+ public void UnprovedDestinationsAndIncompleteSelections_AreRejected()+ {+ var source = Source; var before = JsonSerializer.Serialize(source.Topology);+ var candidates = BrepThroughHoleRevision.Discover(source).Candidates;+ var hole = candidates.Single(c => c.Id == Candidate);+ var occupied = candidates.First(c => c.CanPlan && c.Id != Candidate).Center!.Value;+ Assert.False(BrepThroughHoleRevision.PlanMove(source, Candidate, "Occupied", occupied).IsSuccess);+ Assert.False(BrepThroughHoleRevision.PlanMove(source, Candidate, "OffPlane", new(-70, 4, 19.1)).IsSuccess);+ Assert.False(BrepThroughHoleRevision.PlanMove(source, Candidate, "Outside", new(1000, hole.Center!.Value.Y, 19.1)).IsSuccess);+ var plan = BrepThroughHoleRevision.PlanRemove(source, Candidate, "Valid").Value;+ Assert.False(BrepThroughHoleRevision.Remove(source, plan.Request with { WallFaces = [plan.Request.WallFaces[0]] }).IsSuccess);+ Assert.Equal(before, JsonSerializer.Serialize(source.Topology));+ }+}diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.csindex 00198365..fbc836c1 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242ExporterTests.cs@@ -318,15 +318,26 @@ END-ISO-10303-21;";[Fact][Trait("Category", "SlowCorpus")]- public void ExportBody_Ctc02RoundTrip_PreservesPlanarFaceWithCircularBoundaryNearExpectedCenter()+ public void ExportBody_Ctc02RoundTrip_ExcludesSeparatelyOwnedPlanarCircularSurfaces(){var source = Step242Corpus.Text("testdata/step242/nist/CTC/nist_ctc_02_asme1_ap242-e2.stp");var import = Step242Corpus.Import("testdata/step242/nist/CTC/nist_ctc_02_asme1_ap242-e2.stp");Assert.True(import.IsSuccess);+ // These circular planar caps belong to independent Fill.1 / Split.1+ // surface models, not the PartBody closed shell. The historical test+ // accidentally required grafting those surfaces into the material solid.+ var parsed = Step242SubsetParser.Parse(source).Value;+ Assert.Equal(3148, Assert.Single(Step242SubsetDecoder.ReadReferenceList(parsed.TryGetEntity(1334, "OPEN_SHELL").Value, 1, "Fill.1").Value).TargetId);+ Assert.Equal(3149, Assert.Single(Step242SubsetDecoder.ReadReferenceList(parsed.TryGetEntity(1335, "OPEN_SHELL").Value, 1, "Split.1").Value).TargetId);+ var sourceCircle = Step242SubsetDecoder.ReadCircleCurve(parsed, parsed.TryGetEntity(4317, "CIRCLE").Value).Value;+ Assert.Equal(42.5, sourceCircle.Radius, 6);+ Assert.Equal(812, sourceCircle.Center.Y, 6); Assert.Equal(-140, sourceCircle.Center.Z, 6);+ Assert.DoesNotContain(import.Value.Bindings.FaceBindings, f => f.SourceStepEntityId is 3148 or 3149);+ Assert.Equal(635, import.Value.Topology.Faces.Count());var sourceFace = FindPlanarFaceWithCircle(import.Value, new Aetheris.Kernel.Core.Math.Point3D(0d, 812d, -140d), 42.5d);- Assert.True(sourceFace.HasValue);+ Assert.False(sourceFace.HasValue);var export = Step242Exporter.ExportBody(import.Value);Assert.True(export.IsSuccess);@@ -335,7 +346,8 @@ END-ISO-10303-21;";Assert.True(roundTrip.IsSuccess);var roundTripFace = FindPlanarFaceWithCircle(roundTrip.Value, new Aetheris.Kernel.Core.Math.Point3D(0d, 812d, -140d), 42.5d);- Assert.True(roundTripFace.HasValue);+ Assert.False(roundTripFace.HasValue);+ Assert.Equal(635, roundTrip.Value.Topology.Faces.Count());}diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242SelectedSolidOwnershipTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242SelectedSolidOwnershipTests.csnew file mode 100644index 00000000..c6edab0b--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242SelectedSolidOwnershipTests.cs@@ -0,0 +1,49 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Kernel.Core.Tests.Step242;++public sealed class Step242SelectedSolidOwnershipTests+{+ [Theory, Trait("Category", "SlowCorpus")]+ [InlineData("CTC/nist_ctc_02_asme1_ap242-e2.stp", 635)]+ [InlineData("CTC/nist_ctc_04_asme1_ap242-e1.stp", 483)]+ [InlineData("FTC/nist_ftc_07_asme1_ap242-e2.stp", 304)]+ [InlineData("FTC/nist_ftc_09_asme1_ap242-e1.stp", 158)]+ [InlineData("FTC/nist_ftc_10_asme1_ap242-e2.stp", 264)]+ [InlineData("STC/nist_stc_07_asme1_ap242-e3.stp", 304)]+ [InlineData("STC/nist_stc_08_asme1_ap242-e3.stp", 270)]+ public void MaterialFaces_EqualTheSelectedSourceClosedShell(string path, int expectedCount)+ {+ var relative = "testdata/step242/nist/" + path;+ var parsed = Step242SubsetParser.Parse(Step242Corpus.Text(relative)).Value;+ var root = Assert.Single(parsed.Entities, e => e.Name == "MANIFOLD_SOLID_BREP");+ var shellId = Step242SubsetDecoder.ReadEntityRefOrInlineConstructor(root, 1, "solid shell").Value.ReferenceId!.Value;+ var shell = parsed.TryGetEntity(shellId, "CLOSED_SHELL").Value;+ var faces = Step242SubsetDecoder.ReadReferenceList(shell, 1, "material faces").Value.Select(r => r.TargetId).Order().ToArray();+ Assert.Equal(expectedCount, faces.Length);+ var body = Step242Corpus.Body(relative);+ Assert.Equal(faces, body.Bindings.FaceBindings.Select(b => b.SourceStepEntityId!.Value).Order());+ }++ [Theory, Trait("Category", "SlowCorpus")]+ [InlineData(false)]+ [InlineData(true)]+ public void UnownedLegacyFace_RemainsCompatible_ButOwnedAuxiliaryFaceIsExcluded(bool owned)+ {+ const string path = "testdata/step242/nist/FTC/nist_ftc_09_asme1_ap242-e1.stp";+ var step = Step242Corpus.Text(path);+ // Policy-specific source variant deliberately removes the auxiliary shell+ // owner, retaining its planar face and all of its independent trim geometry.+ if (!owned)+ {+ const string owner = "#6072=OPEN_SHELL('',(#6064));";+ Assert.Contains(owner, step);+ step = step.Replace(owner, "#6072=OPEN_SHELL('',());");+ }+ var imported = owned ? Step242Corpus.Import(path) : Step242Importer.ImportBody(step);+ Assert.True(imported.IsSuccess, string.Join(" | ", imported.Diagnostics.Select(d => d.Message)));+ Assert.Equal(owned ? 158 : 159, imported.Value.Topology.Faces.Count());+ Assert.Equal(!owned, imported.Value.Bindings.FaceBindings.Any(b => b.SourceStepEntityId == 6064));+ }+}diff --git a/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleDiscovery.cs b/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleDiscovery.csindex a092b09c..914018ac 100644--- a/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleDiscovery.cs+++ b/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleDiscovery.cs@@ -12,6 +12,7 @@ public sealed record ThroughHoleCandidate(string Id, bool Recognized, bool CanPlPoint3D AxisOrigin, Vector3D Axis, double Diameter, Point3D? Center,double? Depth, int? EntryFace, int? ExitFace, IReadOnlyList<string> Diagnostics){+ public int? AxisIndex { get; init; }public string Kind => Recognized ? "RoundThroughHole" : "CylindricalGroup";public string Status => !Recognized ? "UnsupportedFamily" : CanPlan ? "Recognized" : "BlockedByImportQualification";}@@ -21,6 +22,7 @@ public sealed record ThroughHoleDiscovery(bool Qualified, double ImportTolerancepublic sealed record ThroughHoleMovePlan(ThroughHoleRevisionRequest Request,ThroughHoleRevisionResult Revision);+public sealed record ThroughHoleRemovalPlan(ThroughHoleRemovalRequest Request, ThroughHoleRemovalResult Removal);public static partial class BrepThroughHoleRevision{@@ -52,12 +54,13 @@ public static partial class BrepThroughHoleRevisionvar reasons = new List<string>(diagnostics);try { region = Recognize(source, face.Id); }catch (Exception error) when (IsRecognitionFailure(error)) { reasons.Add(error.Message); }- var entry = region?.Openings.MaxBy(o => Surface(source, o.Face.Id).Plane!.Value.Origin.Z).Face;- var exit = region?.Openings.MinBy(o => Surface(source, o.Face.Id).Plane!.Value.Origin.Z).Face;+ var entry = region?.Openings.MaxBy(o => Coordinate(Surface(source, o.Face.Id).Plane!.Value.Origin, region!.Axis)).Face;+ var exit = region?.Openings.MinBy(o => Coordinate(Surface(source, o.Face.Id).Plane!.Value.Origin, region!.Axis)).Face;candidates.Add(new(id, region is not null, qualified && region is not null, ids, entities,cylinder.Origin, cylinder.Axis.ToVector(), 2 * cylinder.Radius,- region is null ? null : new(cylinder.Origin.X, cylinder.Origin.Y, region.HighZ),- region is null ? null : region.HighZ - region.LowZ, entry?.Id.Value, exit?.Id.Value, reasons));+ region is null ? null : WithCoordinate(cylinder.Origin, region.Axis, region.High),+ region is null ? null : region.High - region.Low, entry?.Id.Value, exit?.Id.Value, reasons)+ { AxisIndex = region?.Axis });}return new(qualified, importToleranceMillimetres, candidates, diagnostics);}@@ -78,7 +81,7 @@ public static partial class BrepThroughHoleRevisionThroughHoleEditBounds BoundsAt(Point3D center){var r = candidate.Diameter / 2 + clearanceMillimetres;- return new(new(center.X - r, center.Y - r, region.LowZ), new(center.X + r, center.Y + r, region.HighZ));+ return new(WithCoordinate(center - new Vector3D(r, r, r), region.Axis, region.Low), WithCoordinate(center + new Vector3D(r, r, r), region.Axis, region.High));}var request = new ThroughHoleRevisionRequest(featureId, candidate.WallFaces.Select(id => new FaceId(id)).ToArray(),new(candidate.EntryFace!.Value), destination, candidate.Diameter, BoundsAt(candidate.Center!.Value), importToleranceMillimetres)@@ -89,6 +92,23 @@ public static partial class BrepThroughHoleRevision}static bool IsRecognitionFailure(Exception error) => error is ArgumentException or InvalidOperationException or KeyNotFoundException or NotSupportedException;+ public static KernelResult<ThroughHoleRemovalPlan> PlanRemove(BrepBody source, string candidateId, string featureId,+ double importToleranceMillimetres = .001, double clearanceMillimetres = .1)+ {+ if (!double.IsFinite(clearanceMillimetres) || clearanceMillimetres <= System.Math.Max(Tol, importToleranceMillimetres))+ return KernelResult<ThroughHoleRemovalPlan>.Failure([new(KernelDiagnosticCode.ValidationFailed,KernelDiagnosticSeverity.Error,+ "firmament-imported-hole-plan-rejected: Clearance must exceed numerical import uncertainty.","Brep.ThroughHoleRevision")]);+ var candidate = Discover(source, importToleranceMillimetres).Candidates.SingleOrDefault(c => c.Id == candidateId);+ if (candidate?.CanPlan != true) return KernelResult<ThroughHoleRemovalPlan>.Failure([new(KernelDiagnosticCode.ValidationFailed,KernelDiagnosticSeverity.Error,+ "firmament-imported-hole-plan-rejected: " + (candidate is null?"Candidate does not exist in this pinned source.":string.Join(" | ",candidate.Diagnostics)),"Brep.ThroughHoleRevision")]);+ var region = Recognize(source, new(candidate.WallFaces[0])); var center = candidate.Center!.Value;+ var r = candidate.Diameter / 2 + clearanceMillimetres;+ var bounds = new ThroughHoleEditBounds(WithCoordinate(center - new Vector3D(r, r, r), region.Axis, region.Low), WithCoordinate(center + new Vector3D(r, r, r), region.Axis, region.High));+ var request = new ThroughHoleRemovalRequest(featureId, candidate.WallFaces.Select(f => new FaceId(f)).ToArray(), bounds, importToleranceMillimetres);+ var result = Remove(source, request);+ return result.IsSuccess ? KernelResult<ThroughHoleRemovalPlan>.Success(new(request, result.Value), result.Diagnostics)+ : KernelResult<ThroughHoleRemovalPlan>.Failure(result.Diagnostics);+ }static KernelResult<ThroughHoleMovePlan> PlanFailure(string reason) => KernelResult<ThroughHoleMovePlan>.Failure([new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,"firmament-imported-hole-plan-rejected: " + reason, "Brep.ThroughHoleRevision")]);diff --git a/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleRevision.cs b/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleRevision.csindex 6c3ae42a..380c9073 100644--- a/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleRevision.cs+++ b/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleRevision.cs@@ -26,14 +26,20 @@ public sealed record ThroughHoleRevisionResult(BrepBody Body, string FeatureId,public ThroughHoleEditBounds? DestinationWithin { get; init; }}+public sealed record ThroughHoleRemovalRequest(string FeatureId, IReadOnlyList<FaceId> WallFaces,+ ThroughHoleEditBounds Within, double ImportToleranceMillimetres = .001);+public sealed record ThroughHoleRemovalResult(BrepBody Body, string FeatureId, IReadOnlyList<FaceId> RetiredWallFaces,+ FaceId EntryFace, FaceId ExitFace, double Diameter, double Depth, ThroughHoleEditBounds Within,+ IReadOnlyDictionary<FaceId, FaceId> FaceCorrespondence, int PreservedFaces, int PreservedEdges);+/// <summary>Atomic, same-size through-hole replacement in a certified constant-stock/// prism. It retains the residual BRep and constructs new analytic hole geometry.-/// The first admitted family is Z-axis, isolated, round and through two planar supports.</summary>+/// The admitted family is principal-axis, isolated, round and through two planar supports.</summary>public static partial class BrepThroughHoleRevision{const double Tol = 1e-6;sealed record Region(HashSet<FaceId> Walls, (Face Face, Loop Loop)[] Openings,- HashSet<EdgeId> Edges, HashSet<VertexId> Vertices, CylinderSurface Cylinder, double LowZ, double HighZ);+ HashSet<EdgeId> Edges, HashSet<VertexId> Vertices, CylinderSurface Cylinder, int Axis, double Low, double High);sealed record Box(Point3D Min, Point3D Max){public bool Overlaps(Box other, double uncertainty) => Min.X <= other.Max.X + uncertainty && Max.X >= other.Min.X - uncertainty@@ -58,37 +64,24 @@ public static partial class BrepThroughHoleRevisionthrow new ArgumentException("The entry face must be one of the proved planar supports.");if (!double.IsFinite(request.Diameter) || request.Diameter <= 0 || System.Math.Abs(request.Diameter / 2 - region.Cylinder.Radius) > Tol)throw new ArgumentException("This revision admits unchanged diameter only; resizing is unsupported.");- if (!Finite(request.Center) || System.Math.Abs(request.Center.Z - Surface(source, entry.Id).Plane!.Value.Origin.Z) > Tol)+ if (!Finite(request.Center) || System.Math.Abs(Coordinate(request.Center, region.Axis) - Coordinate(Surface(source, entry.Id).Plane!.Value.Origin, region.Axis)) > Tol)throw new ArgumentException("The world-space center must lie on the selected entry plane.");var sourceBox = new Box(request.Within.Min, request.Within.Max);var destination = request.DestinationWithin ?? request.Within;var destinationBox = new Box(destination.Min, destination.Max);- foreach (var box in new[] { sourceBox, destinationBox })- if (!Finite(box.Min) || !Finite(box.Max) || box.Min.X >= box.Max.X || box.Min.Y >= box.Max.Y- || System.Math.Abs(box.Min.Z - region.LowZ) > Tol || System.Math.Abs(box.Max.Z - region.HighZ) > Tol)- throw new ArgumentException("Each edit region must be finite and span exactly the two support planes.");- var r = request.Diameter / 2;- foreach (var (center, box) in new[] { (region.Cylinder.Origin, sourceBox), (request.Center, destinationBox) })- if (center.X - r <= box.Min.X + Tol || center.X + r >= box.Max.X - Tol || center.Y - r <= box.Min.Y + Tol || center.Y + r >= box.Max.Y - Tol)- throw new ArgumentException("The source/destination region must contain its complete hole with positive clearance.");- var authorized = region.Walls.Concat(region.Openings.Select(o => o.Face.Id)).ToHashSet();- var conflicts = source.Topology.Faces.Where(f => !authorized.Contains(f.Id)- && new[] { sourceBox, destinationBox }.Any(box => box.Overlaps(FaceBounds(source, f), System.Math.Max(Tol, request.ImportToleranceMillimetres))))- .Select(f => f.Id.Value).ToArray();- if (conflicts.Length > 0)- throw new ArgumentException($"The stock envelope may intersect unrelated boundary faces: {string.Join(',', conflicts)}. Narrow the operation or choose another destination.");+ Authorize(source, region, [(sourceBox, region.Cylinder.Origin), (destinationBox, request.Center)], request.ImportToleranceMillimetres);if (request.DestinationWithin is not null)foreach (var opening in region.Openings){// Boundary exclusion proves the entire destination prism has// constant stock only after anchoring it inside both supports.- var probe = new Point3D(request.Center.X, request.Center.Y, Surface(source, opening.Face.Id).Plane!.Value.Origin.Z);+ var probe = WithCoordinate(request.Center, region.Axis, Coordinate(Surface(source, opening.Face.Id).Plane!.Value.Origin, region.Axis));var tolerance = new ToleranceContext(System.Math.Max(Tol, request.ImportToleranceMillimetres), 1e-9);if (!AnalyticPlanarFaceDomain.TryContainsInPlanarFace(source, opening.Face.Id, probe, tolerance, opening.Loop.Id, out var inside))throw new ArgumentException("Separate edit regions require proved line/circle trim boundaries on both planar supports; use one qualified envelope for other support outlines.");if (!inside) throw new ArgumentException("The destination is outside the support face material domain; no material column exists there.");}- var patch = MaterializeHolePatch(source, region, request.Center, r);+ var patch = MaterializeHolePatch(source, region, request.Center, request.Diameter / 2);var suppressed = Suppress(source, region);RequireQualified(suppressed, request.ImportToleranceMillimetres);var body = SuppressThenInsert(source, suppressed, patch, region);@@ -99,7 +92,7 @@ public static partial class BrepThroughHoleRevisionvar exit = region.Openings.Single(o => o.Face.Id != entry.Id).Face.Id;return KernelResult<ThroughHoleRevisionResult>.Success(new(body, request.FeatureId,region.Walls.OrderBy(id => id.Value).ToArray(), walls, entry.Id, exit, request.Center, request.Diameter,- region.HighZ - region.LowZ, request.Within, map, source.Topology.Faces.Count() - region.Walls.Count,+ region.High - region.Low, request.Within, map, source.Topology.Faces.Count() - region.Walls.Count,source.Topology.Edges.Count() - region.Edges.Count, request.ImportToleranceMillimetres) { DestinationWithin = request.DestinationWithin });}catch (Exception error) when (error is ArgumentException or InvalidOperationException or KeyNotFoundException or NotSupportedException)@@ -110,6 +103,63 @@ public static partial class BrepThroughHoleRevision}}+ /// <summary>Closes the proved openings by removing their inner loops and the+ /// complete void wall set. No guessed cap, stock rebuild or Boolean is used.</summary>+ public static KernelResult<ThroughHoleRemovalResult> Remove(BrepBody source, ThroughHoleRemovalRequest request)+ {+ ArgumentNullException.ThrowIfNull(source); ArgumentNullException.ThrowIfNull(request);+ try+ {+ if (string.IsNullOrWhiteSpace(request.FeatureId)) throw new ArgumentException("A stable removal feature name is required.");+ RequireQualified(source, request.ImportToleranceMillimetres);+ if (request.WallFaces.Count == 0 || request.WallFaces.Distinct().Count() != request.WallFaces.Count)+ throw new ArgumentException("Select the complete distinct cylindrical wall set.");+ var region = Recognize(source, request.WallFaces[0]);+ if (!region.Walls.SetEquals(request.WallFaces)) throw new ArgumentException("The selected faces do not equal the complete connected cylindrical wall group.");+ Authorize(source, region, [(new(request.Within.Min, request.Within.Max), region.Cylinder.Origin)], request.ImportToleranceMillimetres);+ var body = Suppress(source, region);+ RequireQualified(body, request.ImportToleranceMillimetres);+ var map = body.Topology.Faces.ToDictionary(f => f.Id, f => f.Id);+ var entry = region.Openings.MaxBy(o => Coordinate(Surface(source, o.Face.Id).Plane!.Value.Origin, region.Axis)).Face.Id;+ var exit = region.Openings.Single(o => o.Face.Id != entry).Face.Id;+ return KernelResult<ThroughHoleRemovalResult>.Success(new(body, request.FeatureId, region.Walls.OrderBy(f => f.Value).ToArray(),+ entry, exit, 2 * region.Cylinder.Radius, region.High - region.Low, request.Within, map, map.Count,+ body.Topology.Edges.Count()));+ }+ catch (Exception error) when (IsRecognitionFailure(error))+ {+ return KernelResult<ThroughHoleRemovalResult>.Failure([new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,+ "firmament-imported-hole-removal-rejected: " + error.Message, "Brep.ThroughHoleRevision")]);+ }+ }++ static int PrincipalAxis(CylinderSurface cylinder)+ {+ var v = cylinder.Axis.ToVector();+ for (var i = 0; i < 3; i++) if (v.Cross(AxisVector(i)).Length <= Tol) return i;+ throw new ArgumentException("Only principal-axis (X, Y or Z) holes are admitted; oblique holes require a qualified edit frame.");+ }+ static Vector3D AxisVector(int axis) => axis switch { 0 => new(1,0,0), 1 => new(0,1,0), _ => new(0,0,1) };+ static double Coordinate(Point3D p, int axis) => axis switch { 0 => p.X, 1 => p.Y, _ => p.Z };+ static Point3D WithCoordinate(Point3D p, int axis, double value) => axis switch { 0 => new(value,p.Y,p.Z), 1 => new(p.X,value,p.Z), _ => new(p.X,p.Y,value) };+ static Vector3D Radial(Vector3D v, int axis) => v - AxisVector(axis) * v.Dot(AxisVector(axis));+ static void Authorize(BrepBody source, Region region, (Box Bounds, Point3D Center)[] edits, double tolerance)+ {+ foreach (var (box, center) in edits)+ {+ if (!Finite(box.Min) || !Finite(box.Max) || box.Min.X >= box.Max.X || box.Min.Y >= box.Max.Y || box.Min.Z >= box.Max.Z+ || System.Math.Abs(Coordinate(box.Min, region.Axis) - region.Low) > Tol || System.Math.Abs(Coordinate(box.Max, region.Axis) - region.High) > Tol)+ throw new ArgumentException("Each edit region must be finite and span exactly the two support planes.");+ for (var i = 0; i < 3; i++) if (i != region.Axis && (Coordinate(center,i) - region.Cylinder.Radius <= Coordinate(box.Min,i) + Tol+ || Coordinate(center,i) + region.Cylinder.Radius >= Coordinate(box.Max,i) - Tol))+ throw new ArgumentException("The source/destination region must contain its complete hole with positive clearance.");+ }+ var authorized = region.Walls.Concat(region.Openings.Select(o => o.Face.Id)).ToHashSet();+ var conflicts = source.Topology.Faces.Where(f => !authorized.Contains(f.Id) && edits.Any(e => e.Bounds.Overlaps(FaceBounds(source,f), System.Math.Max(Tol,tolerance))))+ .Select(f => f.Id.Value).ToArray();+ if (conflicts.Length > 0) throw new ArgumentException($"The stock envelope may intersect unrelated boundary faces: {string.Join(',',conflicts)}. Narrow the operation or choose another destination.");+ }+static bool Finite(Point3D p) => double.IsFinite(p.X) && double.IsFinite(p.Y) && double.IsFinite(p.Z);static void RequireQualified(BrepBody body, double tolerance){@@ -125,7 +175,7 @@ public static partial class BrepThroughHoleRevisionstatic Region Recognize(BrepBody body, FaceId seed){var cylinder = Surface(body, seed).Cylinder ?? throw new ArgumentException("Seed must be cylindrical.");- if (cylinder.Axis.ToVector().Cross(new Vector3D(0, 0, 1)).Length > Tol) throw new ArgumentException("Only Z-axis holes are admitted.");+ var axis = PrincipalAxis(cylinder);var incidence = Incidence(body);var walls = ConnectedWalls(body, seed, cylinder, incidence);if (walls.Any(id => body.Bindings.GetFaceBinding(id).Orientation.IsAlignedWithSurface)) throw new ArgumentException("Not an inward cylindrical void wall.");@@ -137,16 +187,16 @@ public static partial class BrepThroughHoleRevisionvar edges = loop.CoedgeIds.Select(id => body.Topology.GetCoedge(id).EdgeId).ToArray();if (!edges.Any(wallEdges.Contains)) continue;if (!edges.All(wallEdges.Contains) || Surface(body, face.Id).Plane is not { } plane- || plane.Normal.ToVector().Cross(new Vector3D(0, 0, 1)).Length > Tol+ || plane.Normal.ToVector().Cross(AxisVector(axis)).Length > Tol|| body.Bindings.GetFaceBoundaryRoleBinding(loop.Id).Role != FaceBoundaryRole.Inner)- throw new ArgumentException("Void boundary is not two isolated circular inner loops on Z-normal planes.");+ throw new ArgumentException("Void boundary is not two isolated circular inner loops on axis-normal planes; slots and stepped/countersunk holes require a complete feature-family proof.");var angularCoverage = 0d;foreach (var edge in edges){var circle = Curve(body, edge).Circle3 ?? throw new ArgumentException("Non-circular opening.");var offset = circle.Center - cylinder.Origin;- if (System.Math.Abs(circle.Radius - cylinder.Radius) > Tol || circle.Normal.ToVector().Cross(new Vector3D(0, 0, 1)).Length > Tol- || System.Math.Sqrt(offset.X * offset.X + offset.Y * offset.Y) > Tol) throw new ArgumentException("Non-coaxial opening.");+ if (System.Math.Abs(circle.Radius - cylinder.Radius) > Tol || circle.Normal.ToVector().Cross(AxisVector(axis)).Length > Tol+ || Radial(offset, axis).Length > Tol) throw new ArgumentException("Non-coaxial opening.");var trim = body.Bindings.GetEdgeBinding(edge).TrimInterval ?? throw new ArgumentException("Missing arc trim.");angularCoverage += System.Math.Abs(trim.End - trim.Start);}@@ -154,22 +204,22 @@ public static partial class BrepThroughHoleRevisionopenings.Add((face, loop));}if (openings.Count != 2 || openings.Select(o => o.Face.Id).Distinct().Count() != 2) throw new ArgumentException("Expected two distinct planar supports.");- var z = openings.Select(o => Surface(body, o.Face.Id).Plane!.Value.Origin.Z).Order().ToArray();- if (z[1] - z[0] <= Tol) throw new ArgumentException("Zero depth.");+ var stations = openings.Select(o => Coordinate(Surface(body, o.Face.Id).Plane!.Value.Origin, axis)).Order().ToArray();+ if (stations[1] - stations[0] <= Tol) throw new ArgumentException("Zero depth.");foreach (var id in walls){var arcs = Edges(body, body.Topology.GetFace(id)).Where(e => Curve(body, e).Circle3 is not null).ToArray();- if (arcs.Length != 2 || arcs.Select(e => Curve(body, e).Circle3!.Value.Center.Z).Order().Zip(z).Any(p => System.Math.Abs(p.First - p.Second) > Tol))+ if (arcs.Length != 2 || arcs.Select(e => Coordinate(Curve(body, e).Circle3!.Value.Center, axis)).Order().Zip(stations).Any(p => System.Math.Abs(p.First - p.Second) > Tol))throw new ArgumentException("Wall patches must span the full same depth.");}foreach (var edge in wallEdges){if (incidence[edge].Length != 2) throw new ArgumentException("Non-manifold wall boundary.");- if (Curve(body, edge).Line3 is { } line && line.Direction.ToVector().Cross(new Vector3D(0, 0, 1)).Length > Tol) throw new ArgumentException("Non-axial seam.");+ if (Curve(body, edge).Line3 is { } line && line.Direction.ToVector().Cross(AxisVector(axis)).Length > Tol) throw new ArgumentException("Non-axial seam.");if (Curve(body, edge).Kind is not (CurveGeometryKind.Line3 or CurveGeometryKind.Circle3)) throw new ArgumentException("Unsupported wall edge.");}var vertices = wallEdges.SelectMany(e => { var edge = body.Topology.GetEdge(e); return new[] { edge.StartVertexId, edge.EndVertexId }; }).ToHashSet();- return new(walls, openings.ToArray(), wallEdges, vertices, cylinder, z[0], z[1]);+ return new(walls, openings.ToArray(), wallEdges, vertices, cylinder, axis, stations[0], stations[1]);}static Dictionary<EdgeId, FaceId[]> Incidence(BrepBody body) => body.Topology.Faces@@ -202,11 +252,11 @@ public static partial class BrepThroughHoleRevision|| source.Bindings.FaceBindings.Any(b => changedSurfaces.Contains(b.SurfaceGeometryId) && !region.Walls.Contains(b.FaceId)))throw new ArgumentException("Shared geometry outside edit region requires copy-on-write IDs.");var geometry = new BrepGeometryStore();- foreach (var (id, curve) in source.Geometry.Curves) geometry.AddCurve(id, changedCurves.Contains(id) ? MaterializeCurve(curve, region.Cylinder.Origin, center, radius) : curve);+ foreach (var (id, curve) in source.Geometry.Curves) geometry.AddCurve(id, changedCurves.Contains(id) ? MaterializeCurve(curve, region.Cylinder.Origin, center, radius, region.Axis) : curve);foreach (var (id, surface) in source.Geometry.Surfaces){var c = surface.Cylinder;- geometry.AddSurface(id, changedSurfaces.Contains(id) ? SurfaceGeometry.FromCylinder(new(new Point3D(center.X, center.Y, c!.Value.Origin.Z), c.Value.Axis, radius, c.Value.XAxis)) : surface);+ geometry.AddSurface(id, changedSurfaces.Contains(id) ? SurfaceGeometry.FromCylinder(new(c!.Value.Origin + Radial(center - region.Cylinder.Origin, region.Axis), c.Value.Axis, radius, c.Value.XAxis)) : surface);}var bindings = new BrepBindingModel();foreach (var b in source.Bindings.EdgeBindings) bindings.AddEdgeBinding(b);@@ -240,8 +290,8 @@ public static partial class BrepThroughHoleRevisionforeach (var id in region.Vertices){var p = points[id]; var d = p - region.Cylinder.Origin;- var length = System.Math.Sqrt(d.X * d.X + d.Y * d.Y);- points[id] = new(center.X + radius * d.X / length, center.Y + radius * d.Y / length, p.Z);+ var radial = Radial(d, region.Axis);+ points[id] = p + Radial(center - region.Cylinder.Origin, region.Axis) + radial * (radius / radial.Length - 1);}return new(source.Topology.Clone(), geometry, bindings, points, null, source.ShellRepresentation);}@@ -351,13 +401,13 @@ public static partial class BrepThroughHoleRevision}static Box Bounds(Point3D[] p) => new(new(p.Min(v => v.X), p.Min(v => v.Y), p.Min(v => v.Z)), new(p.Max(v => v.X), p.Max(v => v.Y), p.Max(v => v.Z)));- static CurveGeometry MaterializeCurve(CurveGeometry c, Point3D oldCenter, Point3D center, double radius)+ static CurveGeometry MaterializeCurve(CurveGeometry c, Point3D oldCenter, Point3D center, double radius, int axis){- if (c.Circle3 is { } circle) return CurveGeometry.FromCircle(new(new(center.X, center.Y, circle.Center.Z), circle.Normal, radius, circle.XAxis));+ if (c.Circle3 is { } circle) return CurveGeometry.FromCircle(new(circle.Center + Radial(center - oldCenter, axis), circle.Normal, radius, circle.XAxis));if (c.Line3 is { } line){- var d = line.Origin - oldCenter; var length = System.Math.Sqrt(d.X * d.X + d.Y * d.Y);- return CurveGeometry.FromLine(new(new(center.X + radius * d.X / length, center.Y + radius * d.Y / length, line.Origin.Z), line.Direction));+ var radial = Radial(line.Origin - oldCenter, axis);+ return CurveGeometry.FromLine(new(line.Origin + Radial(center - oldCenter, axis) + radial * (radius / radial.Length - 1), line.Direction));}throw new NotSupportedException("Only circular rims and axial seams are admitted.");}diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.csindex 9fd8cc0f..a55ac187 100644--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs@@ -789,6 +789,14 @@ public static class Step242Importerprivate static void AppendSupportedOrphanPlanarFaces(Step242ParsedDocument document, IList<int> faceEntityIds){var known = new HashSet<int>(faceEntityIds);+ // An auxiliary OPEN_SHELL (often a datum/annotation surface model) owns+ // its faces independently. Such faces are not orphans of the selected+ // solid and must never be appended to its closed material shell.+ foreach (var shell in document.Entities.Where(e => e.Name is "OPEN_SHELL" or "CLOSED_SHELL"))+ {+ var faces = Step242SubsetDecoder.ReadReferenceList(shell, 1, "auxiliary shell faces");+ if (faces.IsSuccess) known.UnionWith(faces.Value.Select(r => r.TargetId));+ }foreach (var entity in document.Entities){diff --git a/Aetheris.Kernel.Firmament.Tests/Ftc09ImportedEditingTests.cs b/Aetheris.Kernel.Firmament.Tests/Ftc09ImportedEditingTests.csnew file mode 100644index 00000000..479abc97--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/Ftc09ImportedEditingTests.cs@@ -0,0 +1,119 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Import;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class Ftc09ImportedEditingTests+{+ static string DirectoryPath+ {+ get+ {+ var root = new DirectoryInfo(AppContext.BaseDirectory);+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx"))) root = root.Parent;+ return Path.Combine(root!.FullName, "fixtures/Regression/InlineStep/production");+ }+ }+ static string Source(bool remove) => File.ReadAllText(Path.Combine(DirectoryPath, remove ? "ftc09-round-remove.firmament" : "ftc09-round-move.firmament"));+ static FirmamentV2ValidationReport Validate(string source) => FirmamentBuildAdmissionValidation.Admit(+ FirmamentV2ValidationReportBuilder.Build(FirmamentV2Parser.Parse(source, DirectoryPath), "revision.firmament", sourceText: source), source, DirectoryPath);++ [Theory]+ [InlineData(false)]+ [InlineData(true)]+ public void GoldenSource_AdmitsAndExportsTheRealEditedBody(bool remove)+ {+ var source = Source(remove); var validation = Validate(source);+ Assert.Equal("valid", validation.Status); Assert.Equal("Built", validation.ValidationLevel);+ var build = FirmamentBuildAndExport.CompileSource(source, DirectoryPath);+ Assert.True(build.IsSuccess, string.Join(" | ", build.Diagnostics.Select(d => d.Message)));+ Assert.Equal(remove ? 156 : 158, build.Value.RuntimeBody!.Topology.Faces.Count());+ if (remove)+ {+ var report = build.Value.ImportedHoleRemoval!;+ Assert.Equal(156, report.PreservedFaces); Assert.Equal(448, report.PreservedEdges);+ Assert.Equal(new[] { 31, 32 }, report.RetiredWallFaces);+ Assert.DoesNotContain(31, report.FaceCorrespondence.Keys);+ Assert.Equal(1, build.Value.InlineStepMigration!.Removals.EmittedCount);+ Assert.Equal(2, build.Value.InlineStepMigration.Removals.RemovedFaceCount);+ Assert.Equal(0, build.Value.InlineStepMigration.Replacements.EmittedCount);+ Assert.Empty(build.Value.InlineStepMigration.ReplacementStates);+ Assert.Empty(Step242SemanticPmiInspector.Inspect(build.Value.StepText).Items);+ }+ else+ {+ var report = build.Value.ImportedHoleRevision!;+ Assert.Equal(156, report.PreservedFaces); Assert.Equal(448, report.PreservedEdges);+ Assert.Equal(6.35, report.Diameter, 8); Assert.Equal(3.03784, report.Depth, 8);+ var pmi = Assert.Single(Step242SemanticPmiInspector.Inspect(build.Value.StepText).Items, i => i.Kind == "Diameter");+ Assert.Equal(report.Diameter, pmi.Value);+ var walls = build.Value.RuntimeBody.Topology.Faces.Where(f => build.Value.RuntimeBody.GetFaceSurface(f.Id).Cylinder is { } c && System.Math.Abs(c.Origin.X + 70) < 1e-8).ToArray();+ Assert.Equal(2, walls.Length);+ Assert.All(walls, f => Assert.Equal(19.1, build.Value.RuntimeBody.GetFaceSurface(f.Id).Cylinder!.Value.Origin.Z, 8));+ }+ Assert.Contains(build.Diagnostics, d => d.Message.StartsWith("firmament-inline-step-source-semantics-excluded"));+ var reimport = Step242Importer.ImportBody(build.Value.StepText);+ Assert.True(reimport.IsSuccess);+ Assert.Equal(ImportQualificationStatus.Qualified, reimport.Value.ImportQualification!.GeometryStatus);+ }++ [Theory]+ [InlineData(0)]+ [InlineData(2)]+ public void PrincipalXAndZ_UseTheSameCertificateAfterRigidPlacement(int axis)+ {+ var built = FirmamentBuildAndExport.CompileSource(Source(false), DirectoryPath).Value;+ var transform = axis == 0 ? Core.Math.Transform3D.CreateRotationZ(double.Pi / 2)+ : Core.Math.Transform3D.CreateRotationX(double.Pi / 2);+ var placed = Aetheris.Kernel.Firmament.Assembly.FirmasmAssemblyExecutor.TransformBody(built.RuntimeBody!, transform);+ var discovery = BrepThroughHoleRevision.Discover(placed);+ var expected = transform.Apply(new Core.Math.Point3D(-70, 3.03784, 19.1));+ var hole = Assert.Single(discovery.Candidates, c => c.CanPlan && c.AxisIndex == axis+ && (axis == 0 ? System.Math.Abs(c.Center!.Value.Y - expected.Y) : System.Math.Abs(c.Center!.Value.X - expected.X)) < 1e-6+ && System.Math.Abs(c.Diameter - 6.35) < 1e-6);+ var destination = axis == 0 ? hole.Center!.Value with { Y = -55 } : hole.Center!.Value with { X = -55 };+ var move = BrepThroughHoleRevision.PlanMove(placed, hole.Id, "Placed", destination);+ Assert.True(move.IsSuccess, string.Join(" | ", move.Diagnostics.Select(d => d.Message)));+ Assert.Equal(158, move.Value.Revision.Body.Topology.Faces.Count());+ var remove = BrepThroughHoleRevision.PlanRemove(placed, hole.Id, "Placed");+ Assert.True(remove.IsSuccess, string.Join(" | ", remove.Diagnostics.Select(d => d.Message)));+ Assert.Equal(156, remove.Value.Removal.Body.Topology.Faces.Count());+ var oblique = Aetheris.Kernel.Firmament.Assembly.FirmasmAssemblyExecutor.TransformBody(built.RuntimeBody!,+ Core.Math.Transform3D.CreateRotationX(double.Pi / 4));+ var unsupported = BrepThroughHoleRevision.Discover(oblique);+ Assert.DoesNotContain(unsupported.Candidates, c => c.CanPlan);+ Assert.Contains(unsupported.Candidates, c => c.Diagnostics.Any(d => d.Contains("oblique")));+ }++ [Theory]+ [InlineData("measurement")]+ [InlineData("field")]+ [InlineData("pin")]+ [InlineData("bounds")]+ [InlineData("diameter")]+ [InlineData("off-plane")]+ [InlineData("remove-pmi")]+ [InlineData("remove-field")]+ public void InvalidIntent_ValidationAndBuildRejectWithLocation(string kind)+ {+ var source = Source(kind.StartsWith("remove"));+ source = kind switch+ {+ "measurement" => source.Replace("Source.MountHole.diameter", "Source.MountHole.diammeter"),+ "field" => source.Replace("diameter:", "diammeter:"),+ "pin" => source.Replace("daad9815", "0aad9815"),+ "bounds" => source.Replace("min:", "minimum:"),+ "diameter" => source.Replace("Source.MountHole.diameter", "6.4mm"),+ "off-plane" => source.Replace("Source.MountHole.center.Y", "4mm"),+ "remove-field" => source.Replace("within:", "wthin:"),+ _ => source[..source.LastIndexOf('}')] + "Pmi { HoleDiameter Old { target: Source.region(\"MountHole\"); value: 6.35mm } } }"+ };+ var validation = Validate(source);+ Assert.Equal("invalid", validation.Status);+ Assert.False(FirmamentBuildAndExport.CompileSource(source, DirectoryPath).IsSuccess);+ Assert.Contains(validation.Diagnostics, d => d.SourceSpan is not null && d.Severity is "error" or "fatal");+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 27065d72..ed1da513 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -522,7 +522,7 @@ public static partial class FirmamentBuildAndExport}if (v2Parse.Document.Solids.Any(s => s.InlineStep?.SourceHashPin is not null)- && (v2Parse.Document.Solids.Count != 1 || v2Parse.Document.Replacements is { Count: > 0 }+ && (v2Parse.Document.Solids.Count != 1 || v2Parse.Document.Replacements is { Count: > 0 } || v2Parse.Document.Removals.Count > 0|| v2Parse.Document.ModifyBlocks is { Count: > 0 }))return ExportPinnedImportedRevision(v2Parse.Document);diff --git a/Aetheris.Kernel.Firmament/FirmamentImportedFeatures.cs b/Aetheris.Kernel.Firmament/FirmamentImportedFeatures.csindex fd976a56..cfe9dd31 100644--- a/Aetheris.Kernel.Firmament/FirmamentImportedFeatures.cs+++ b/Aetheris.Kernel.Firmament/FirmamentImportedFeatures.cs@@ -37,6 +37,11 @@ public sealed record ImportedFeatureMovePlan(string Source, string Candidate, stpublic double AuthoringIncrementMillimetres => FirmamentImportedFeatures.AuthoringIncrementMillimetres;[JsonIgnore] public FirmamentStepExportResult Export { get; init; } = null!;}+public sealed record ImportedFeatureRemovalPlan(string Source, string Candidate, string Alias, string SourceHash, string Admission,+ FirmamentImportedHoleRemovalReport Removal)+{+ [JsonIgnore] public FirmamentStepExportResult Export { get; init; } = null!;+}/// <summary>Agent-facing recovery assistance. Selection is explicit; geometric/// admission belongs exclusively to the existing production kernel/compiler.</summary>@@ -84,14 +89,28 @@ public static class FirmamentImportedFeaturestry { resourcePath = Assembly.FirmamentProjectSnapshot.NormalizePath(sourceReference); }catch (ArgumentException) { return Failure<ImportedFeatureMovePlan>("Snapshot source reference must remain inside the resource project."); }}- var authoredDestination = new Point3D(Nominal(destination.X), Nominal(destination.Y), Nominal(destination.Z));+ var candidate = inspection.Discovery.Candidates.SingleOrDefault(c => c.Id == candidateId);+ if (candidate?.AxisIndex is not { } axis || candidate.Center is not { } original)+ return Failure<ImportedFeatureMovePlan>("Select a proved principal-axis round through-hole before planning.");+ double Component(Point3D p) => axis switch { 0 => p.X, 1 => p.Y, _ => p.Z };+ if (System.Math.Abs(Component(destination) - Component(original)) > 1e-6)+ return Failure<ImportedFeatureMovePlan>("The destination must remain on the proved entry plane; only in-plane positions are rounded.");+ var authoredDestination = axis switch+ {+ 0 => new Point3D(original.X, Nominal(destination.Y), Nominal(destination.Z)),+ 1 => new(Nominal(destination.X), original.Y, Nominal(destination.Z)),+ _ => new(Nominal(destination.X), Nominal(destination.Y), original.Z)+ };var planned = BrepThroughHoleRevision.PlanMove(inspection.Body, candidateId, alias, authoredDestination,inspection.Discovery.ImportToleranceMillimetres, clearanceMillimetres);if (!planned.IsSuccess) return KernelResult<ImportedFeatureMovePlan>.Failure(planned.Diagnostics);var request = planned.Value.Request;var entryEntity = inspection.Body.Bindings.GetFaceBinding(request.EntryFace).SourceStepEntityId;if (entryEntity is null) return Failure<ImportedFeatureMovePlan>("Entry support has no imported source entity binding.");- var source = Emit(inspection, candidateId, alias, sourceReference, entryEntity.Value, request);+ var source = axis == 2 && System.Math.Abs(Nominal(request.Diameter) - request.Diameter) < 1e-6+ && System.Math.Abs(Nominal(request.Within.Min.Z) - request.Within.Min.Z) < 1e-6 && System.Math.Abs(Nominal(request.Within.Max.Z) - request.Within.Max.Z) < 1e-6+ ? Emit(inspection, candidateId, alias, sourceReference, entryEntity.Value, request)+ : EmitMeasured(inspection, candidate, alias, sourceReference, request.Within, request.DestinationWithin, request.Center, entryEntity.Value);// Resource snapshots use exactly the inspected immutable text. File-backed// callers re-enter the ordinary loader, which rechecks the persisted pin.IReadOnlyDictionary<string, string>? resources = sourceDirectory is null@@ -99,7 +118,63 @@ public static class FirmamentImportedFeaturesvar build = FirmamentBuildAndExport.CompileSource(source, sourceDirectory ?? "", resources);if (!build.IsSuccess) return KernelResult<ImportedFeatureMovePlan>.Failure(build.Diagnostics);return KernelResult<ImportedFeatureMovePlan>.Success(new(source, candidateId, alias, inspection.SourceHash,- "Built", build.Value.ImportedHoleRevision!) { Export = build.Value }, build.Diagnostics);+ "Built", build.Value.ImportedHoleRevision!)+ { Export = build.Value }, build.Diagnostics);+ }++ public static KernelResult<ImportedFeatureRemovalPlan> PlanRemove(ImportedFeatureInspection inspection, string candidateId, string alias,+ bool geometryOnly, string sourceReference = "input.step", string? sourceDirectory = null, double clearanceMillimetres = .1)+ {+ ArgumentNullException.ThrowIfNull(inspection);+ if (!geometryOnly) return Failure<ImportedFeatureRemovalPlan>("Explicit geometry-only approval is required; source PMI migration is not admitted.");+ var name = FirmamentSyntaxParser.ParseExpression(alias);+ if (name.Diagnostics.Count > 0 || name.Expression is not ReferenceSyntax r || r.Name.Text != alias)+ return Failure<ImportedFeatureRemovalPlan>("Alias must be one Firmament identifier.");+ if (string.IsNullOrWhiteSpace(sourceReference) || Path.IsPathRooted(sourceReference)) return Failure<ImportedFeatureRemovalPlan>("The STEP path must be relative to its source document.");+ string? resourcePath = null;+ if (sourceDirectory is null)+ {+ try { resourcePath = Assembly.FirmamentProjectSnapshot.NormalizePath(sourceReference); }+ catch (ArgumentException) { return Failure<ImportedFeatureRemovalPlan>("Snapshot source reference must remain inside the resource project."); }+ }+ var planned = BrepThroughHoleRevision.PlanRemove(inspection.Body, candidateId, alias, inspection.Discovery.ImportToleranceMillimetres, clearanceMillimetres);+ if (!planned.IsSuccess) return KernelResult<ImportedFeatureRemovalPlan>.Failure(planned.Diagnostics);+ var candidate = inspection.Discovery.Candidates.Single(c => c.Id == candidateId);+ var source = EmitMeasured(inspection, candidate, alias, sourceReference, planned.Value.Request.Within, null, null, null);+ IReadOnlyDictionary<string, string>? resources = sourceDirectory is null ? new Dictionary<string, string> { [resourcePath!] = inspection.SourceText } : null;+ var build = FirmamentBuildAndExport.CompileSource(source, sourceDirectory ?? "", resources);+ return build.IsSuccess ? KernelResult<ImportedFeatureRemovalPlan>.Success(new(source, candidateId, alias, inspection.SourceHash, "Built", build.Value.ImportedHoleRemoval!) { Export = build.Value }, build.Diagnostics)+ : KernelResult<ImportedFeatureRemovalPlan>.Failure(build.Diagnostics);+ }++ static string EmitMeasured(ImportedFeatureInspection inspection, ThroughHoleCandidate candidate, string alias, string path,+ ThroughHoleEditBounds within, ThroughHoleEditBounds? destination, Point3D? center, int? entryEntity)+ {+ var strings = new JsonSerializerOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping };+ var axis = candidate.AxisIndex!.Value; var prefix = "Source." + alias; var axisName = new[] { "X", "Y", "Z" }[axis];+ static double Component(Point3D p, int i) => i switch { 0 => p.X, 1 => p.Y, _ => p.Z };+ string Point(Point3D p, string? axial = null, bool? minimum = null) => "Point3(" + string.Join(", ", Enumerable.Range(0, 3).Select(i => i == axis+ ? prefix + "." + (axial ?? "center") + "." + axisName+ : (minimum is { } min ? Outward(Component(p, i), min) : Nominal(Component(p, i))).ToString("0.#", CultureInfo.InvariantCulture) + "mm")) + ")";+ string Bounds(ThroughHoleEditBounds b) => "{ min: " + Point(b.Min, "exit", true) + "; max: " + Point(b.Max, "entry", false) + " }";+ var operation = destination is null ? "Remove " + prefix + " {\n within: " + Bounds(within) + "\n }"+ : $"Replace {prefix} with Hole<Shaft> {alias} {{\n on: Source.Face(\"#{entryEntity}\")\n center: {Point(center!.Value)}\n diameter: {prefix}.diameter\n end: ThroughAll\n within: [{Bounds(within)}, {Bounds(destination)}]\n }}";+ return $$"""+ // New in-plane positions use a 0.1mm grid. Source size/supports remain exact.+ Model ImportedRevision {+ units: mm+ InlineStep Source {+ path: {{JsonSerializer.Serialize(path)}}+ textSha256: "{{inspection.SourceHash}}"+ importTolerance: {{inspection.Discovery.ImportToleranceMillimetres.ToString("R", CultureInfo.InvariantCulture)}}mm+ geometryOnly: true+ }+ Recognize Source {+ Region {{alias}} { kind: HoleShaft; candidate: {{JsonSerializer.Serialize(candidate.Id, strings)}}; }+ }+ {{operation}}+ }+ """;}static string Emit(ImportedFeatureInspection inspection, string candidate, string alias,diff --git a/Aetheris.Kernel.Firmament/FirmamentImportedHoleRemoval.cs b/Aetheris.Kernel.Firmament/FirmamentImportedHoleRemoval.csnew file mode 100644index 00000000..58319ccf--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentImportedHoleRemoval.cs@@ -0,0 +1,74 @@+using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Import;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Core.Topology;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament;++public sealed record FirmamentImportedHoleRemovalReport(string Feature, string SourceHash, string SourceHashKind, string? SourceByteHash,+ string Strategy, bool SourceSemanticsExcluded, double ImportToleranceMillimetres, IReadOnlyList<int> RetiredWallFaces,+ int EntryFace, int ExitFace, double Diameter, double Depth, ThroughHoleEditBounds Within, int PreservedFaces, int PreservedEdges,+ IReadOnlyDictionary<int, int> FaceCorrespondence);++public static partial class FirmamentBuildAndExport+{+ static KernelResult<FirmamentStepExportResult> ExportImportedHoleRemoval(FirmamentV2Document document,+ FirmamentV2SolidBinding solid, FirmamentV2RemovalDecl removal)+ {+ KernelResult<FirmamentStepExportResult> Failure(string message) => KernelResult<FirmamentStepExportResult>.Failure([+ new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, "FirmamentV2.ImportedHoleRemoval")+ { SourceSpan = new(removal.SourceSpan.Start, removal.SourceSpan.Length) }]);+ var imported = solid.InlineStep!;+ var tolerance = imported.ImportToleranceMillimetres ?? .001;+ if (!imported.GeometryOnly) return Failure("firmament-imported-hole-source-semantics-unsupported: Remove requires explicit geometryOnly: true; imported annotation migration is not qualified.");+ if (imported.RuntimeBody is not { } body || body.ImportQualification?.GeometryStatus != ImportQualificationStatus.Qualified)+ return Failure("firmament-imported-hole-import-unqualified: Remove requires the pinned, qualified source body.");+ if (document.Pmi is { Count: > 0 } || document.PmiBlock?.Records.Count > 0)+ return Failure("firmament-imported-hole-removal-pmi-unsupported: Explicit PMI rebinding across removal is not qualified. Annotate the successor separately; source PMI is excluded only by explicit geometryOnly permission.");+ var region = document.RecognizedRegions!.Single(r => r.BodyName == solid.Name && r.RegionName == removal.RecognizedRegionName);+ FaceId? Resolve(string entity) => imported.TopologyMap.TryResolveFaceEntity(entity, out var id)+ && int.TryParse(id.AsSpan("face-".Length), out var number) ? new(number) : null;+ var selected = region.FaceRefs.Select(Resolve).ToArray();+ if (selected.Any(f => f is null)) return Failure("firmament-imported-hole-selection-unresolved: Remove requires complete resolved wall selection.");+ var edit = BrepThroughHoleRevision.Remove(body, new(removal.RecognizedRegionName, selected.Select(f => f!.Value).ToArray(), removal.Within, tolerance));+ if (!edit.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(edit.Diagnostics.Select(d => d with { SourceSpan = new(removal.SourceSpan.Start, removal.SourceSpan.Length) }));+ var revised = edit.Value;+ if (!ImportedHoleEvidenceAgrees(region, body, selected.Select(f => f!.Value), revised.Diameter))+ return Failure("firmament-imported-hole-evidence-mismatch: Authored evidence disagrees with the proved through-hole geometry.");+ var exported = Step242Exporter.ExportBody(revised.Body, new Step242ExportOptions+ {+ ProductName = document.ModelName,+ ApplicationName = "Aetheris.Firmament.ImportedHoleRemoval",+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,+ ImportedRecoveryToleranceMillimetres = tolerance,+ DistanceAccuracyMillimetres = System.Math.Max(body.ImportQualification.SourceDistanceAccuracyMillimetres ?? 0, tolerance)+ });+ if (!exported.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(exported.Diagnostics);+ var roundtrip = Step242Importer.ImportBody(exported.Value, new ImportPolicy(PcurveQualificationToleranceMillimetres: tolerance));+ if (!roundtrip.IsSuccess || roundtrip.Value.ImportQualification?.GeometryStatus != ImportQualificationStatus.Qualified)+ return Failure("firmament-imported-hole-roundtrip-unqualified: The removal successor failed qualified STEP roundtrip.");+ var map = imported.TopologyMap.FaceEntityToFaceId.Where(p => Resolve(p.Key) is { } id && revised.FaceCorrespondence.ContainsKey(id)).ToDictionary(p => p.Key, p => p.Value);+ var bound = document with { Solids = [solid with { Primitive = imported with { RuntimeBody = revised.Body, TopologyMap = new(map, map.ToDictionary(p => p.Value, p => p.Key)) } }] };+ var migration = InlineStepMigrationReportBuilder.Build(document, solid, emissionStrategy: "through-hole-suppression", residualSurgery: true) with+ {+ Removals = new(1, 1, 1, revised.RetiredWallFaces.Count),+ Residual = new(revised.PreservedFaces, revised.PreservedFaces),+ ReplacementStates = []+ };+ return KernelResult<FirmamentStepExportResult>.Success(new(exported.Value, solid.Name, 0, "inline-step-removal", "through-hole-suppression", InlineStepMigration: migration)+ {+ DocumentName = document.ModelName,+ RuntimeBody = revised.Body,+ RuntimeBodySourceName = solid.Name,+ RuntimeAdmissionDocument = bound,+ ImportedHoleRemoval = new(removal.RecognizedRegionName, imported.SourceHashPin!, imported.TextHashPin ? "sha256-utf8-lf" : "sha256-bytes", imported.SourceByteHash,+ "ThroughHoleSuppression", true, tolerance, revised.RetiredWallFaces.Select(f => f.Value).ToArray(), revised.EntryFace.Value, revised.ExitFace.Value, revised.Diameter, revised.Depth,+ removal.Within, revised.PreservedFaces, revised.PreservedEdges, revised.FaceCorrespondence.ToDictionary(p => p.Key.Value, p => p.Value.Value))+ },+ [new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Warning, "firmament-inline-step-source-semantics-excluded: geometryOnly explicitly excludes source annotations. The removed hole has no successor diameter PMI.", "FirmamentV2.InlineStep")+ { SourceSpan = solid.SourceSpan is {} span ? new(span.Start, span.Length) : null }]);+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentImportedHoleRevision.cs b/Aetheris.Kernel.Firmament/FirmamentImportedHoleRevision.csindex 351e41ee..1dd127eb 100644--- a/Aetheris.Kernel.Firmament/FirmamentImportedHoleRevision.cs+++ b/Aetheris.Kernel.Firmament/FirmamentImportedHoleRevision.cs@@ -1,4 +1,5 @@using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Diagnostics;using Aetheris.Kernel.Core.Import;using Aetheris.Kernel.Core.Results;@@ -26,12 +27,14 @@ public static partial class FirmamentBuildAndExportif (document.Solids.Count != 1 || document.ModifyBlocks is { Count: > 0 }|| document.Panels is { Count: > 0 } || document.LatticeFills is { Count: > 0 }|| document.StandaloneLatticeFills is { Count: > 0 } || document.Threads is { Count: > 0 }- || document.Replacements is not { Count: 1 } || document.Replacements[0].Within is null)+ || (document.Replacements?.Count ?? 0) + document.Removals.Count != 1+ || document.Replacements is { Count: 1 } && document.Replacements[0].Within is null)return KernelResult<FirmamentStepExportResult>.Failure([new(KernelDiagnosticCode.ValidationFailed,KernelDiagnosticSeverity.Error,- "firmament-inline-step-revision-required: Pinned imports currently admit one bounded Replace with a within envelope and no additional Modify operations. No imported geometry was emitted.", "FirmamentV2.InlineStep")+ "firmament-inline-step-revision-required: Pinned imports admit one bounded Replace or Remove with a within envelope and no additional Modify operations. No imported geometry was emitted.", "FirmamentV2.InlineStep"){ SourceSpan = solid.SourceSpan is { } span ? new(span.Start, span.Length) : null }]);- return ExportImportedHoleRevision(document, solid, document.Replacements[0]);+ return document.Removals.Count == 1 ? ExportImportedHoleRemoval(document, solid, document.Removals[0])+ : ExportImportedHoleRevision(document, solid, document.Replacements![0]);}private static KernelResult<FirmamentStepExportResult> ExportImportedHoleRevision(FirmamentV2Document document,@@ -67,12 +70,7 @@ public static partial class FirmamentBuildAndExportSourceSpan = replacement.SourceSpan is { } span ? new(span.Start, span.Length) : null}));var revised = edit.Value;- if (region.Evidence is { } evidence && (- evidence.Radius is { } radius && System.Math.Abs(radius * 2 - revised.Diameter) > 1e-6 || evidence.Through == false- || evidence.SurfaceFamilies.Any(f => f != "cylindrical")- || evidence.Axis is { } axis && axis is not ("Z" or "+Z" or "-Z")- || evidence.Center is { } oldCenter && selected.Any(id => !body.TryGetFaceSurfaceGeometry(id!.Value, out var s) || s?.Cylinder is not { } c- || System.Math.Abs(c.Origin.X - oldCenter.U) > 1e-6 || System.Math.Abs(c.Origin.Y - oldCenter.V) > 1e-6)))+ if (!ImportedHoleEvidenceAgrees(region,body,selected.Select(id=>id!.Value),revised.Diameter))return Failure("firmament-imported-hole-evidence-mismatch: Authored evidence disagrees with the proved through-hole geometry.");var pmiAdmission = ValidateV2PmiExportSupport(document);if (!pmiAdmission.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(pmiAdmission.Diagnostics);@@ -122,4 +120,29 @@ public static partial class FirmamentBuildAndExportrevised.Diameter, revised.Depth, revised.Within, revised.PreservedFaces, revised.PreservedEdges, revised.FaceCorrespondence.ToDictionary(p => p.Key.Value, p => p.Value.Value)) { DestinationWithin = revised.DestinationWithin }}, warnings);}++ static bool ImportedHoleEvidenceAgrees(FirmamentV2RecognizedRegion region, BrepBody body,+ IEnumerable<FaceId> selected, double diameter)+ {+ if (region.Evidence is not {} evidence) return true;+ if (evidence.Radius is {} r && System.Math.Abs(r * 2 - diameter) > 1e-6 || evidence.Through == false+ || evidence.SurfaceFamilies.Any(f => f != "cylindrical")) return false;+ foreach (var id in selected)+ {+ if (body.GetFaceSurface(id).Cylinder is not {} cylinder) return false;+ var axis = System.Math.Abs(cylinder.Axis.X) > .99 ? 0 : System.Math.Abs(cylinder.Axis.Y) > .99 ? 1 : 2;+ if (evidence.Axis is {} word && word.TrimStart('+', '-').ToUpperInvariant() != new[]{"X", "Y", "Z"}[axis]) return false;+ if (evidence.Center is {} point)+ {+ var radial = axis switch+ {+ 0 => new[]{cylinder.Origin.Y, cylinder.Origin.Z},+ 1 => new[]{cylinder.Origin.X, cylinder.Origin.Z},+ _ => new[]{cylinder.Origin.X, cylinder.Origin.Y}+ };+ if (System.Math.Abs(radial[0] - point.U) > 1e-6 || System.Math.Abs(radial[1] - point.V) > 1e-6) return false;+ }+ }+ return true;+ }}diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.csindex 830b117a..4e026ffe 100644--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs@@ -39,6 +39,7 @@ public sealed record FirmamentStepExportResult({public string? DocumentName { get; init; }public FirmamentImportedHoleRevisionReport? ImportedHoleRevision { get; init; }+ public FirmamentImportedHoleRemovalReport? ImportedHoleRemoval { get; init; }// Lowerer-owned receipts distinguish generated feature PMI from authored projections.[JsonIgnore] public IReadOnlyList<Aetheris.Kernel.Core.Step242.Step242SemanticPmi> GeneratedSemanticPmi { get; init; } = [];public IReadOnlyList<FirmamentV2.FirmamentGeometryAssertionResult> GeometryAssertions { get; init; } = [];diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.csindex a7b2e9c9..fbc48c81 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs@@ -7,6 +7,7 @@ public sealed record FirmamentV2Document(string ModelName, string Units, IReadOn{public IReadOnlyList<FirmamentV2DataSymbolBinding> DataBindings { get; init; } = [];public IReadOnlyList<FirmamentGeometryAssertion> GeometryAssertions { get; init; } = [];+ public IReadOnlyList<FirmamentV2RemovalDecl> Removals { get; init; } = [];public FirmamentV2SolidBinding Solid => Solids[^1];public FirmamentV2SideHoleIntent? SideHoleIntent => ModifyBlocks?.SelectMany(m => m.Regions.Select(r =>{@@ -196,6 +197,8 @@ public sealed record FirmamentV2ReplacementDecl(string ImportedBodyName, stringpublic Aetheris.Kernel.Core.Brep.Features.ThroughHoleEditBounds? DestinationWithin { get; init; }public FirmamentV2SourceSpan? SourceSpan { get; init; }}+public sealed record FirmamentV2RemovalDecl(string ImportedBodyName, string RecognizedRegionName,+ Aetheris.Kernel.Core.Brep.Features.ThroughHoleEditBounds Within, FirmamentV2SourceSpan SourceSpan);public sealed record FirmamentV2ImportedStepFaceTarget(string BodySymbol, string EntityRef){diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ImportedEditingBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ImportedEditingBinding.csindex eb8d3fd2..95f5d3b7 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ImportedEditingBinding.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ImportedEditingBinding.cs@@ -154,7 +154,8 @@ public static partial class FirmamentV2Parserif (kind != region.Kind) diagnostics.Add(ReplacementKindMismatch);var name = (declaration.Initializer as ReferenceSyntax)?.Name.Text;if (name is null) { diagnostics.Add(CanonicalDeclarationUnrecognized); continue; }- var fields = new FirmamentSyntaxFields(declaration with { ResultType = null, Initializer = null }, diagnostics);+ var measurements = new ImportedHoleMeasurements(solid, region, diagnostics);+ var fields = new FirmamentSyntaxFields(declaration with { ResultType = null, Initializer = null }, diagnostics, bind: measurements.Expression);var placement = fields.Take("On");string? faceEntity = null;if (placement is CallSyntax { Target: MemberSyntax { Target: ReferenceSyntax owner, Member.Text: "Face" or "face" } member, Arguments.Count: 1 } call && owner.Name.Text == solid.Name@@ -209,6 +210,39 @@ public static partial class FirmamentV2Parserreturn result;}+ private static IReadOnlyList<FirmamentV2RemovalDecl> BindImportedRemovals(IEnumerable<DeclarationSyntax> declarations,+ Dictionary<string,FirmamentV2SolidBinding> solids, IReadOnlyList<FirmamentV2RecognizedRegion> regions,+ List<string> diagnostics, Action<DeclarationSyntax,int> capture)+ {+ var result = new List<FirmamentV2RemovalDecl>();+ foreach (var declaration in declarations.Where(d => d.Type.Name.Text == "Remove"))+ {+ var start = diagnostics.Count;+ try+ {+ var target = declaration.Name?.Text.Split('.') ?? [];+ if (target.Length != 2 || !solids.TryGetValue(target[0],out var solid) || solid.InlineStep is null)+ { diagnostics.Add(UnknownReplacementBody); continue; }+ var region = regions.SingleOrDefault(r => r.BodyName == target[0] && r.RegionName == target[1]);+ if (region is null) { diagnostics.Add(UnknownReplacementRegion); continue; }+ if (region.Kind != "holeShaft") diagnostics.Add("firmament-imported-hole-removal-kind-unsupported: Remove currently requires a proved HoleShaft region.");+ if (solid.InlineStep.SourceHashPin is null) diagnostics.Add("firmament-inline-step-source-pin-required: Remove requires a pinned STEP source.");+ var fields = new FirmamentSyntaxFields(declaration,diagnostics,bind: new ImportedHoleMeasurements(solid,region,diagnostics).Expression);+ if (fields.Take("Within") is ObjectSyntax obj)+ {+ var bounds = ImportedObject(obj,"EditBounds",diagnostics);+ var min = Point(bounds.Take("Min")); var max = Point(bounds.Take("Max")); bounds.Complete();+ if (min is not null && max is not null) result.Add(new(solid.Name,target[1],new(min.Value,max.Value),declaration.Span));+ else fields.Invalid("Within");+ }+ else fields.Invalid("Within");+ fields.Complete();+ }+ finally { capture(declaration,start); }+ }+ return result;+ }+private static FirmamentSyntaxFields ImportedObject(ObjectSyntax obj, string type, List<string> diagnostics){if (obj.Type is not null && FirmamentSyntaxValues.Reference(obj.Type) != type || obj.Name is not null)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.csindex db40fca9..e37b4295 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs@@ -206,6 +206,7 @@ public static partial class FirmamentV2Parservar bodyText = source.Substring(model.Body.Span.Start + 1, model.Body.Span.Length - 2);var recognized = BindImportedRegions(declarations, solids, diagnostics, CaptureFieldDiagnostics);var replacements = BindImportedReplacements(declarations, solids, recognized, diagnostics, source, CaptureFieldDiagnostics);+ var removals = BindImportedRemovals(declarations, solids, recognized, diagnostics, CaptureFieldDiagnostics);var selections = ParseCanonicalSelections(bodyText, model.Body.Span.Start + 1, diagnostics);ValidateCanonicalSelectionSources(bodyText, selections, [], diagnostics);var (pmi, pmiBlock, boundPmi) = ParsePmi(source, solids, modifies, recognized, staticValues.Values, [], diagnostics);@@ -216,7 +217,7 @@ public static partial class FirmamentV2Parserreturn FirmamentV2ParseResult.Success(new(model.Name!.Text, "mm", solids.Values.ToArray(), modifies,Pmi: pmi, RecognizedRegions: recognized, Replacements: replacements, PmiBlock: pmiBlock, BoundPmi: boundPmi, Selections: selections,Lets: staticValues.Declarations, BoundLets: staticValues.Values,- TemplateInstantiations: templateInstantiations is { Count: > 0 } ? templateInstantiations : null),+ TemplateInstantiations: templateInstantiations is { Count: > 0 } ? templateInstantiations : null) { Removals = removals },diagnostics.Append("firmament-v2-unified-canonical-parsed").Append("firmament-v2-parse-succeeded").Distinct(StringComparer.Ordinal).Order().ToArray())with { SyntaxDiagnostics = locatedDiagnostics };}@@ -576,7 +577,7 @@ public static partial class FirmamentV2Parsercase "Box" or "Cylinder" or "Cone" or "Sphere" or "Ellipsoid" or "Polyhedron" or "Torus" or "RoundedBox" or "Frustum" or "StandardPart" or "ExactCoaxialPart":case "Plane" or "Axis" or "Axis2" or "Point2" or "Line2" or "CubicBezier2" or "Rect2" or "Square2" or "Triangle2" or "Polygon2" or "RegularPolygon2" or "Circle2" or "Ellipse2" or "Ellipse2Guide" or "Slot2" or "RoundedRect2" or "SmoothRoundedRect2" or "Path":case "Plateau" or "Concept" or "Struct" or "Profile" or "Span" or "Compose" or "Boss" or "Pocket" or "AddOffset" or "RemoveOffset" or "EdgeFinish" or "Extrude":- case "Enum" or "Expose" or "Record" or "Template" or "template" or "Feature" or "Pattern" or "ProfileDelta" or "Selection" or "InlineStep" or "Recognize" or "Replace" or "Pmi" or "Modify" or "Match" or "Require" or "Assert" or "Thread":+ case "Enum" or "Expose" or "Record" or "Template" or "template" or "Feature" or "Pattern" or "ProfileDelta" or "Selection" or "InlineStep" or "Recognize" or "Replace" or "Remove" or "Pmi" or "Modify" or "Match" or "Require" or "Assert" or "Thread":break;case "Solid": diagnostics.Add(CanonicalConstructNotYetSupported + ":Solid"); break;default: diagnostics.Add(CanonicalDeclarationUnrecognized); diagnostics.Add($"{CanonicalDeclarationUnknown}:{declaration.Type.Name.Text}"); break;diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ImportedHoleMeasurements.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ImportedHoleMeasurements.csnew file mode 100644index 00000000..792e757f--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ImportedHoleMeasurements.cs@@ -0,0 +1,51 @@+using System.Globalization;+using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++/// <summary>Source-derived engineering facts, scoped to one proved recognized+/// hole. Binding happens at the imported edit owner, without a text macro pass.</summary>+internal sealed class ImportedHoleMeasurements(FirmamentV2SolidBinding solid, FirmamentV2RecognizedRegion region,+ List<string> diagnostics) : FirmamentSyntaxRewriter+{+ ThroughHoleCandidate? measured;+ bool inspected;+ internal override ExpressionSyntax Expression(ExpressionSyntax expression)+ {+ var prefix = solid.Name + "." + region.RegionName + ".";+ var path = FirmamentSyntaxValues.Reference(expression);+ if (path?.StartsWith(prefix, StringComparison.Ordinal) != true) return base.Expression(expression);+ if (!inspected)+ {+ inspected = true;+ if (solid.InlineStep is { SourceHashPin: not null, RuntimeBody: { } body } imported)+ measured = BrepThroughHoleRevision.Discover(body, imported.ImportToleranceMillimetres ?? .001).Candidates+ .SingleOrDefault(c => c.CanPlan && c.StepFaceEntities.Select(id => "#" + id).Order().SequenceEqual(region.FaceRefs.Order()));+ }+ if (measured is null)+ { diagnostics.Add("firmament-imported-hole-measurement-unresolved: Source measurements require a pinned, proved isolated round through-hole."); return expression; }+ var field = path[prefix.Length..];+ var center = measured.Center!.Value;+ Point3D point = field.StartsWith("exit", StringComparison.Ordinal) ? Shift(center, measured.AxisIndex!.Value, -measured.Depth!.Value) : center;+ double? value = field switch+ {+ "diameter" => measured.Diameter,+ "depth" => measured.Depth,+ "center.X" or "entry.X" or "exit.X" => point.X,+ "center.Y" or "entry.Y" or "exit.Y" => point.Y,+ "center.Z" or "entry.Z" or "exit.Z" => point.Z,+ _ => null+ };+ if (value is not null) return Length(value.Value, expression.Span);+ if (field is "center" or "entry" or "exit")+ return new CallSyntax(new ReferenceSyntax(new("Point3", expression.Span), expression.Span),+ new[] { point.X, point.Y, point.Z }.Select(v => new ArgumentSyntax(null, Length(v, expression.Span), null, expression.Span)).ToArray(), expression.Span);+ diagnostics.Add("firmament-imported-hole-measurement-unknown: Unknown recovered measurement '" + field + "'. Use diameter, depth, center, entry or exit.");+ return expression;+ }+ static ExpressionSyntax Length(double value, FirmamentV2SourceSpan span) => new QuantitySyntax(+ new LiteralSyntax(LiteralKind.Number, value.ToString("R", CultureInfo.InvariantCulture), span), new("mm", span), span);+ static Point3D Shift(Point3D p, int axis, double distance) => axis switch { 0 => new(p.X + distance, p.Y, p.Z), 1 => new(p.X, p.Y + distance, p.Z), _ => new(p.X, p.Y, p.Z + distance) };+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/InlineStepMigrationReport.cs b/Aetheris.Kernel.Firmament/FirmamentV2/InlineStepMigrationReport.csindex 2579fbf3..d5a823f2 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/InlineStepMigrationReport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/InlineStepMigrationReport.cs@@ -12,7 +12,11 @@ public sealed record InlineStepMigrationReport(string EmissionStrategy,bool ResidualSurgery,IReadOnlyList<string> ReplacementStates,- IReadOnlyList<string> Diagnostics);+ IReadOnlyList<string> Diagnostics)+{+ public InlineStepRemovalAccounting Removals { get; init; } = new(0, 0, 0, 0);+}+public sealed record InlineStepRemovalAccounting(int PlannedCount, int VerifiedCount, int EmittedCount, int RemovedFaceCount);public sealed record InlineStepOriginalTopologyAccounting(int FaceCount, int EdgeCount, int VertexCount);public sealed record InlineStepRecognizedAccounting(int RegionCount, int ReferencedFaceCount, int DuplicateReferencedFaceCount, int UnresolvedReferenceCount, int EvidenceCount = 0, int ProposalCount = 0, int ProposalVerifiedCount = 0, int ProposalUnverifiedCount = 0, int ProposalAssistReadyCount = 0, int ProposalAssistBlockedCount = 0);@@ -94,7 +98,8 @@ public static class InlineStepMigrationReportBuilderemissionStrategy,residualSurgery,states,- diagnostics.Distinct(StringComparer.Ordinal).ToArray());+ diagnostics.Distinct(StringComparer.Ordinal).ToArray())+ { Removals = new(document.Removals.Count(r => r.ImportedBodyName == solid.Name), 0, 0, 0) };}private static IEnumerable<string> BuildStates(int regionCount, int plannedCount, int verifiedCount, int emittedCount)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.csindex 72e2ec55..4a494623 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs@@ -230,7 +230,7 @@ public static class FirmamentSyntaxParser&& !LineBreak && !IsClause(Current.Text)) headerUnit = Identifier();var hasParameterList = Take("(");var parameters = hasParameterList ? Arguments(")", declarationParameters: true) : [];- if (type.Name.Text == "Replace" && Take("."))+ if ((type.Name.Text is "Replace" or "Remove") && Take(".")){var member = Identifier();name = new IdentifierSyntax(name!.Text + "." + member.Text, new(name.Span.Start, member.Span.Start + member.Span.Length - name.Span.Start));diff --git a/docs/development/architecture/imported-hole-revisions.md b/docs/development/architecture/imported-hole-revisions.mdindex 4e14a50d..ab15684e 100644--- a/docs/development/architecture/imported-hole-revisions.md+++ b/docs/development/architecture/imported-hole-revisions.md@@ -1,6 +1,6 @@# Bounded imported through-hole revisions-Implemented production contract for one isolated round Z-axis through-hole move.+Implemented production contract for one isolated round principal-axis (X/Y/Z) through-hole move or removal.The [authoring guide](../../public/firmament/imported-feature-recognition.md) and[golden fixture](../../../fixtures/Regression/InlineStep/production/ctc01-hole-move.firmament)are the executable surface; the [closeout](../../release/IMPORTED-HOLE-REVISION-PRODUCTION-2026-10-20.md)@@ -9,7 +9,7 @@ records qualification. Original experiments remain historical evidence.## OwnershipThe unified structural parser admits `InlineStep`, `Recognize`/`Region`, and-`Replace ... with Hole<Shaft>`. `FirmamentV2ImportedEditingBinding` consumes their+`Replace ... with Hole<Shaft>` and `Remove Source.Region`. `FirmamentV2ImportedEditingBinding` consumes theirfields through the existing `FirmamentSyntaxFields` owner. Unknown fields andstatements reject. There is no new whole-document parser or source rewrite.@@ -38,7 +38,7 @@ subsequent semantic projections. Source file bytes remain untouched.`BrepThroughHoleRevision` proves a single closed oriented manifold, qualifiedtrims, inward connected coaxial cylindrical walls, complete circular inner rims,-two distinct Z-normal planar supports and full same-depth coverage. The selected+two distinct axis-normal planar supports and full same-depth coverage. The selectedset must equal the entire proved wall group. Axis/frame limitations reject ratherthan project onto XY. Authored confidence never overrides geometric proof.@@ -143,3 +143,22 @@ boss. A single enclosing corridor rejects on the intervening boundaries. Residuageometry, topology identities and generated semantic PMI remain under the sameproduction revision owner. This is agent assistance for the admitted family,not a general feature recognizer or geometry repair system.++## FTC-09 extension++The importer no longer grafts faces owned by another OPEN_SHELL/CLOSED_SHELL+onto the selected solid through orphan-planar compatibility. Truly unowned+supported planar faces retain the existing compatibility rule. FTC-09's #6064+belongs to an auxiliary open surface model, not #6014's closed material shell.++Principal-axis editing projects only the local radial displacement. It does not+rotate the whole import or rebuild residual geometry. Source measurement AST+binding occurs in `ImportedHoleMeasurements` at the imported edit field owner,+against the complete pinned recognized group. It creates typed quantities/Point3+nodes with the expression span; it adds no source rewrite or global evaluator.++Remove shares recognition, stock-envelope proof, suppression and qualification+with Replace. Its face correspondence omits retired walls. It has separate+removal accounting, no generated hole PMI, and rejects explicit successor PMI+until annotation rebinding is qualified. No general Remove-body or arbitrary+surface surgery is implied. See the FTC-09 release report for current evidence.diff --git a/docs/public/firmament/imported-feature-recognition.md b/docs/public/firmament/imported-feature-recognition.mdindex b09970f3..41e5b4a9 100644--- a/docs/public/firmament/imported-feature-recognition.md+++ b/docs/public/firmament/imported-feature-recognition.md@@ -1,8 +1,8 @@# Imported through-hole revisions-Firmament can replace one isolated round through-hole in a pinned imported STEP-body, retaining the actual residual BRep. The first admitted operation moves the-hole without changing its diameter or depth. It does not reverse-engineer the+Firmament can move or remove one isolated round through-hole in a pinned imported STEP+body, retaining the actual residual BRep. A move retains the+hole diameter and depth; removal fills its proved material column. It does not reverse-engineer thewhole part or reconstruct stock from a guessed HostSize.The executable golden source is@@ -81,9 +81,11 @@ aetheris validate artifacts/local/imported-features/revision.firmament --jsonaetheris build artifacts/local/imported-features/revision.firmament --output artifacts/local/imported-features/revised.step --json```-`--offset dx dy` uses imported-body XY coordinates from the proved upper opening;+`--offset du dv` uses the radial coordinates of the proved upper opening:+YZ for X-axis holes, XZ for Y-axis holes, and XY for Z-axis holes;`--to x y z` supplies an absolute Point3 instead. All numbers are millimetres.-Exactly one placement mode is required. `--clearance` defaults to .1 mm and must+Use `--remove` instead of either placement mode to fill the selected hole.+Exactly one of `--offset`, `--to`, or `--remove` is required. `--clearance` defaults to .1 mm and mustexceed import uncertainty. The plan qualifies its generated source through normalbuild admission before committing outputs; a refused plan leaves no new source file.@@ -110,29 +112,33 @@ and review a changed STEP in a new revision/project; a lock update cannot rebindsurgery selections. The SDK source-only `PlanMove` result retains its explicit`textSha256` pin for compatibility and immutable resource planning.-Generated geometry dimensions and coordinates use a **0.1 mm authoring grid**:-nearest tenth for nominal lengths and positions, midpoint ties away from zero.-Safety bounds and radial padding round outward. For example, imported arithmetic-noise `24.9999999999998mm` becomes authored `25mm`, and `45.0000000000001mm`-becomes `45mm`. This changes the authored nominal geometry and replacement PMI,-not merely their display formatting. The JSON plan records-`authoringIncrementMillimetres: 0.1`.--The numerical `importTolerance` budget keeps its own precision (`0.01mm` in this-fixture); rounding it to zero or widening it would change import admission.-The emitted, rounded source must still build. Genuine resizing or moving off the-proved support plane remains subject to the current capability checks. The grid-does not invent a manufacturing tolerance annotation or modify retained STEP-geometry. Explicit `tol` requirements remain the source of manufacturing limits.--The destination is a named `Concept Struct` Point3; destination bounds reference+New in-plane positions use a **0.1 mm authoring grid**, midpoint ties away+from zero. Safety bounds round outward. Imported diameters and support stations+remain source-derived: a 6.35 mm hole stays 6.35 mm, and a plate thickness does+not move to a different plane merely to remove floating-point noise from source.+Generated source uses `Source.MountHole.diameter`, `.entry.Y`, `.exit.Y`, and+`.center.Y` for FTC-09, whose thickness runs along Y. The plan records+`authoringIncrementMillimetres: 0.1` for newly authored move coordinates.++Inside imported `Replace` and `Remove` field expressions, a proved named region+exposes `diameter`, `depth` (Length), `center`, `entry`, `exit` (Point3), and their+`.X`, `.Y`, `.Z` components (Length). Entry is the maximum principal-axis station;+exit is the minimum. These facts bind directly through the unified AST against+the pinned source. They are currently local to these imported edit fields;+arbitrary Static/Concept expressions cannot yet consume them. Unknown facts reject.++The numerical `importTolerance` keeps its own precision. It is distinct from+manufacturing tolerance; the authoring grid creates no `tol` requirement and does+not round retained STEP geometry. A requested resize or off-plane move rejects.++The CTC-01 generator retains its named `Concept Struct` Point3; destination bounds referenceits `.X` and `.Y` components. Editing that one point moves the requested hole andreruns clearance checks without duplicating coordinates. The executable[recovered fixture](../../../fixtures/Regression/InlineStep/production/ctc01-recovered-hole-move.firmament)moves the hole across the central boss to (130,45) mm without editing the boss.The .NET SDK exposes the same path through `FirmamentImportedFeatures.Inspect`-and `PlanMove`. Snapshot planning uses the immutable inspected resource text;+and `PlanMove`/`PlanRemove`. Snapshot planning uses the immutable inspected resource text;file-backed planning rechecks the pin through the ordinary loader. Explicitgeometry-only approval remains required in both paths.@@ -187,10 +193,10 @@ vendor's original dimensions, datums or GD&T.## Admission and reports-The current family is one isolated round Z-axis through-hole, unchanged diameter+The current family is one isolated round principal-axis (X, Y or Z) through-hole, unchanged diameterand depth, between two parallel planar supports in one qualified closed orientedbody. Blind, intersecting, breakout, threaded, blended-entry, counterbore,-countersink and non-Z-axis revisions reject. Unknown fields and placements reject.+countersink, slot and oblique-axis revisions reject. Unknown fields and placements reject.No arbitrary-body Boolean fallback or general healing is performed. An uneditedpinned body can be re-exported through the qualified import owner; a pin does notimply a replacement operation. Additional Modify operations still reject rather@@ -207,6 +213,43 @@ annotation exclusion, retired/new walls, preserved entity counts and corresponde`inlineStepMigration.residualSurgery` is true for this operation. Syntax diagnosticsand kernel admission failures retain source context.+## FTC-09 move and removal++FTC-09 is a qualified XZ plate at the default 0.001 mm numerical budget.+Inspection finds 25 admitted round through-holes among 59 cylindrical groups;+partial slot walls, countersinks, stepped holes and breakouts remain unsupported.+Separate surface-model faces are not material in the selected closed solid.++```shell+aetheris imported-features inspect ftc09.stp --json+aetheris imported-features plan ftc09.stp --candidate "through-hole:step-1255+1282" --as MountHole --offset 15.09 0.05 --geometry-only --source-out move/revision.firmament --json+aetheris imported-features plan ftc09.stp --candidate "through-hole:step-1255+1282" --as MountHole --remove --geometry-only --source-out remove/revision.firmament --json+```++The first moves the 6.35 mm hole to X=-70, Z=19.1 mm while preserving its Y+support station. The second independently fills that original hole:++```firmament+Remove Source.MountHole {+ within: {+ min: Point3(-88.4mm, Source.MountHole.exit.Y, 15.7mm)+ max: Point3(-81.8mm, Source.MountHole.entry.Y, 22.4mm)+ }+}+```++Use the tracked [move](../../../fixtures/Regression/InlineStep/production/ftc09-round-move.firmament)+and [removal](../../../fixtures/Regression/InlineStep/production/ftc09-round-remove.firmament)+fixtures for complete runnable sources. Each Model admits exactly one move **or**+removal; batching/chaining edits is not yet qualified. Removal suppresses the void+walls and the two support inner loops; no guessed caps or stock reconstruction+are involved. Surviving topology retains identity. Retired faces have no successor+mapping. Build JSON exposes `importedHoleRemoval` and `inlineStepMigration.removals`+with actual retired walls and preserved counts. Removal creates no hole PMI.+Explicit authored PMI on a removal Model currently rejects pending successor+annotation rebinding; original vendor PMI is excluded only by explicit+`geometryOnly: true`, just as for moves.+## Historical compatibilityThe older HostSize-based Box/shaft replacement prototype remains a compatibilitydiff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex b7debbc9..1e19b4d8 100644--- a/docs/public/firmament/syntax.md+++ b/docs/public/firmament/syntax.md@@ -393,7 +393,17 @@ workflow requires explicit `geometryOnly: true`; source annotation exclusion isreported, not silently assumed.`importTolerance` controls imported geometry qualification and is separate from amanufacturing `tol`. The older HostSize rebuild does not have this preservation-contract. See [imported through-hole revisions](imported-feature-recognition.md)+contract. The bounded imported editor also admits `Remove Source.RegionName {+within: { min: Point3(...); max: Point3(...) } }` for a proved isolated round+through-hole. One move or removal per Model is qualified, along principal X/Y/Z+axes. Source-derived `Source.RegionName.diameter`, `.depth`, `.center`, `.entry`,+`.exit` and Point3 `.X`/`.Y`/`.Z` components bind inside these imported edit fields.+They preserve the imported size and support planes while newly authored in-plane+positions can use ordinary engineering precision. Slots and countersinks remain+explicitly unsupported for editing; recognition never promotes a partial wall+into a complete hole.++See [imported through-hole revisions](imported-feature-recognition.md)for the executable CTC-01 source, numerical accuracy and rejection boundaries.Sheet Metal's named planar regions and FEA's `Region:` selectionfields are domain-owned uses of the word, with separate types and admissiondiff --git a/docs/release/FTC09-DIRECT-STEP-EDITING-2026-10-21.md b/docs/release/FTC09-DIRECT-STEP-EDITING-2026-10-21.mdnew file mode 100644index 00000000..3a280bc8--- /dev/null+++ b/docs/release/FTC09-DIRECT-STEP-EDITING-2026-10-21.md@@ -0,0 +1,196 @@+# FTC-09 direct STEP editing - 2026-10-21++## Result++The bounded round through-hole path now moves and removes a real FTC-09 hole+through ordinary Firmament validation, build, dependency locking and qualified+STEP export/reimport. This is retained-BRep editing, with no inferred stock box,+whole-model rotation, Boolean surgery or mesh fallback. Slots and countersinks+remain explicit capability refusals. They are not admitted as partial round holes.++Final qualification is recorded below.++## Source and initial blockers++Input: `testdata/step242/nist/FTC/nist_ftc_09_asme1_ap242-e1.stp`.+UTF-8/LF text pin:+`daad981598736d2ee6a104a7213b8d7813deaaabd7f683bc8cf8bbbf401a579a`.+The original source file is unchanged. Geometry-only revisions explicitly exclude+vendor annotation semantics; they do not claim PMI passthrough or preservation.++The plate lies in XZ, with material at Y=0..3.03784000001215 mm. Its nominal+world bounds are X=-95.25..95.25, Z=-139.7..139.7 mm. Source accuracy is 0.000001 mm;+qualification uses the default 0.001 mm numerical budget, not a manufacturing tol.++Initial discovery found 59 cylinder groups and admitted none. Two independent+blockers were reproduced:++1. `AppendSupportedOrphanPlanarFaces` grafted #6064 into the material solid even+ though it belongs to #6072 OPEN_SHELL / #6073 SHELL_BASED_SURFACE_MODEL. The+ actual MANIFOLD_SOLID_BREP #6015 selects CLOSED_SHELL #6014 with 158 faces.+ The extra face added four boundary edges and a detached component: 159 faces,+ 458 edges, 304 vertices, degraded qualification.+2. The existing editor admitted only Z-axis holes. FTC-09's round through-holes+ run along Y. Reorienting or reconstructing the residual part would have been+ the wrong repair.++The importer now respects shell ownership when applying orphan compatibility.+A genuinely unowned supported planar face retains the historical compatibility+behavior; a regression source variant proves that distinction. The corrected+solid has 158 faces / 454 edges / 300 vertices and qualifies at 0.001 mm.++## Production changes++- Principal X/Y/Z axes share the existing round-hole recognition certificate.+ Only the selected wall geometry receives radial displacement. Retained support+ surfaces, topology identities, vertices, edges, unrelated loops and pcurves+ remain identical. Oblique axes require a qualified frame and still reject.+- `Remove Source.Region { within: { min: Point3(...); max: Point3(...) } }`+ shares recognition, local stock exclusion, suppression and qualification with+ Replace. It removes complete void walls and their two support inner loops;+ no caps are guessed. Retired faces have no fictitious successor mapping.+- `Source.Region.diameter`, `.depth`, `.center`, `.entry`, `.exit`, and Point3+ components bind as typed source-derived AST values inside imported Replace and+ Remove fields. They are currently local edit facts, not global Static values.+- New in-plane positions round to the 0.1 mm authoring grid. Imported diameter+ and support coordinates remain source-derived. A 6.35 mm hole remains 6.35 mm;+ numerical float noise is not copied into source or fixed by resizing the hole.+- CLI `imported-features plan --remove` produces a normally compiled, locked+ revision. Radial `--offset du dv` means YZ/XZ/XY for X/Y/Z-axis holes.+- Build JSON distinguishes `importedHoleRemoval` from `importedHoleRevision`.+ Migration reports separately count planned/verified/emitted removals and retired+ faces; removal is not reported as an emitted replacement.++Exactly one move or removal per single-body Model is admitted. Source PMI must be+explicitly excluded with `geometryOnly: true`. Moves generate new diameter/depth+PMI attached to successor walls. Removal generates no hole PMI and currently+rejects explicit authored PMI until successor annotation rebinding is qualified.++No new parser route, source rewrite, geometry engine or diagnostic allowlist was+introduced. AST statement/field consumption remains closed. The code-quality pass+checked owner boundaries, source spans, immutable inputs and actual report counts.++## FTC-09 witnesses++The pinned candidate `through-hole:step-1255+1282` comprises wall faces 31/32.+It is nominally diameter 6.35 mm, depth 3.03784 mm, centered at+X=-85.09, Z=19.05 mm. The upper support is STEP #5088 (face 124); the opposite+support is face 121. The cylinder axis points -Y; entry facts use the maximum+principal-axis station.++| Independent revision | Result | Faces / edges / vertices |+|---|---|---|+| Move | New center X=-70, Z=19.1; exact source Y and diameter retained | 158 / 454 / 300 |+| Remove | Original opening filled, no new hole | 156 / 448 / 296 |++For both revisions, all 156 residual surfaces and 448 residual edges retain their+bindings and geometry. Surviving vertices and pcurves remain identical. The source+body is unmodified. World bounds are unchanged. Independent trimmed-domain+queries on **both** supports prove old stock restored and new opening present only+for the move. Strict pcurve checks, enforcing export and qualified reimport pass.+Whole-body ray containment returns Unknown on this mixed-spline body; it is not+used as affirmative occupancy evidence or weakened to make these tests pass.+No exact whole-part volume claim is made.++Two further independent CLI specimens also planned and built with normal locked+admission and qualified export/reimport:++| Candidate | Operation | Source size retained | New in-plane center |+|---|---|---|---|+| `through-hole:step-3157+3184` | LargeHole move | diameter 19.05 mm | X=-31.8, Z=66 mm |+| `through-hole:step-1107+1134` | SmallHole removal | diameter 3.96875 mm | no new hole |++Their sources, receipts, build JSON and STEP files are under the local+`large-move/` and `small-remove/` evidence directories. These are independent+revisions of the original plate, not a claim of qualified edit batching.++Discovery now reports 25 admitted round through-holes among 59 cylindrical groups.+That is recognition, not a promise that all 25 have clearance at an arbitrary new+position. The remaining 34 groups have explicit family/refusal explanations.+Representative rejected specimens include corner breakout #198, countersunk shaft+#811/#838 and a slot end wall #3558. Their partial cylindrical surfaces cannot be+removed independently. Countersinks need a complete coaxial cylinder/cone/support+certificate; slots need a complete line/arc wall-and-rim certificate. Both must+qualify suppression and reinsertion of the whole void family before admission.+These are the next bounded extensions, not a reason to implement general Booleans.++## Import compatibility correction++Seven NIST snapshots previously included auxiliary surface faces. Source-shell+ownership tests prove that each corrected material face set exactly equals its+selected CLOSED_SHELL. Only these baselines were updated; input files were not.+Counts below are faces / edges / vertices.++| Source | Previous mixed ownership | Correct material shell |+|---|---|---|+| nist_ctc_02_asme1_ap242-e2.stp | 637/1416/876 | 635/1410/870 |+| nist_ctc_04_asme1_ap242-e1.stp | 484/1110/664 | 483/1108/662 |+| nist_ftc_07_asme1_ap242-e2.stp | 306/871/588 | 304/865/582 |+| nist_ftc_09_asme1_ap242-e1.stp | 159/458/304 | 158/454/300 |+| nist_ftc_10_asme1_ap242-e2.stp | 268/813/572 | 264/799/560 |+| nist_stc_07_asme1_ap242-e3.stp | 306/871/588 | 304/865/582 |+| nist_stc_08_asme1_ap242-e3.stp | 271/709/446 | 270/705/442 |++Canonical hashes for all corrected bodies were measured on Windows and Linux+(WSL archlinux, .NET 10.0.13 runtime installed under ignored artifacts). The+Linux-specific FTC-09 hash was regenerated from the actual Linux exporter; the+other platform overrides remain unchanged. This is an explicit import ownership+correction, not a claim that previously appended open-surface geometry is part+of the engineering solid. The old CTC-02 planar-cap roundtrip assertion also required these grafted+faces. It now proves that #3148/#3149 belong to separate Fill.1/Split.1 OPEN_SHELL+surface models and that those caps stay out of the 635-face material solid, both+on import and roundtrip. Its source circular geometry is independently checked.+The tessellation-only FTC-08-tg import-failure policy+and its baseline remain unchanged.++## Reproduction++Tracked runnable sources:++- [Move](../../fixtures/Regression/InlineStep/production/ftc09-round-move.firmament).+- [Remove](../../fixtures/Regression/InlineStep/production/ftc09-round-remove.firmament).++```powershell+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll imported-features inspect testdata/step242/nist/FTC/nist_ftc_09_asme1_ap242-e1.stp --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll imported-features plan testdata/step242/nist/FTC/nist_ftc_09_asme1_ap242-e1.stp --candidate "through-hole:step-1255+1282" --as MountHole --offset 15.09 0.05 --geometry-only --source-out artifacts/local/ftc09-direct-edit/move/revision.firmament --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll imported-features plan testdata/step242/nist/FTC/nist_ftc_09_asme1_ap242-e1.stp --candidate "through-hole:step-1255+1282" --as MountHole --remove --geometry-only --source-out artifacts/local/ftc09-direct-edit/remove/revision.firmament --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll validate artifacts/local/ftc09-direct-edit/move/revision.firmament --locked --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll build artifacts/local/ftc09-direct-edit/move/revision.firmament --locked --output artifacts/local/ftc09-direct-edit/move/revision.step --json+```++Use the analogous validate/build commands for removal. The source-only fixtures+use portable LF text pins; CLI plans use byte-pinned dependency receipts.++Local evidence: `artifacts/local/ftc09-direct-edit/`, including inspection and+plan/build JSON, original/moved/removed front SVG/PNG previews, revised STEP files,+Windows/Linux canonical hashes, and regression logs. SVGs are diagnostic wireframe+projections, not manufacturing drawings.++## Qualification++**Success for the bounded round through-hole family.**++- Release solution build: passed (existing nullable/SQLite WASM warnings remain).+- Fast kernel lane: **1,088 passed**, no failures or skips.+- Full solution gate: **5,882 passed across 20 test assemblies**, no failures or+ skips, including Core 1,243, Firmament 3,116, CLI 635, and editable V8 7.+- Linux focused kernel/ownership/corpus/CTC-02 roundtrip lane: **31 passed**.+ Windows SDK VSTest was run under the local Linux runtime with ReadyToRun+ disabled so Windows-native precompiled SDK code was not loaded on Linux.+- Both tracked FTC-09 fixtures validate at Built; all four independent locked+ revision sources build to qualified STEP artifacts.+- Initial full gate found the historical CTC-02 cap assertion described above;+ it was corrected with source ownership evidence, passed individually, and the+ complete solution gate was rerun to green. The original failing log remains+ local as `full-tests-initial.log`.+- `git diff --check` passed. The final code-quality pass retained one parser and+ geometric admission owner, checked diagnostic spans and actual removal report+ counts, and introduced no regex, global rewrite or fallback machinery.++The remaining kernel prerequisite is an explicit complete void-family certificate+for slots and countersinks. This release does not claim their editing support,+multi-operation batching, arbitrary frames, resizing or vendor PMI migration.++Updated public documentation:+[syntax](../public/firmament/syntax.md) and+[imported editing guide](../public/firmament/imported-feature-recognition.md).diff --git a/fixtures/Regression/InlineStep/production/ftc09-round-move.firmament b/fixtures/Regression/InlineStep/production/ftc09-round-move.firmamentnew file mode 100644index 00000000..6c436006--- /dev/null+++ b/fixtures/Regression/InlineStep/production/ftc09-round-move.firmament@@ -0,0 +1,25 @@+// FTC-09's selected rigid solid only; vendor PMI is explicitly excluded.+Model Ftc09Revision {+ units: mm+ InlineStep Source {+ path: "../../../../testdata/step242/nist/FTC/nist_ftc_09_asme1_ap242-e1.stp"+ textSha256: "daad981598736d2ee6a104a7213b8d7813deaaabd7f683bc8cf8bbbf401a579a"+ geometryOnly: true+ }+ Recognize Source {+ Region MountHole {+ kind: HoleShaft+ candidate: "through-hole:step-1255+1282"+ }+ }+ Replace Source.MountHole with Hole<Shaft> MountHole {+ on: Source.Face("#5088")+ center: Point3(-70mm, Source.MountHole.center.Y, 19.1mm)+ diameter: Source.MountHole.diameter+ end: ThroughAll+ within: [+ { min: Point3(-88.4mm, Source.MountHole.exit.Y, 15.7mm); max: Point3(-81.8mm, Source.MountHole.entry.Y, 22.4mm) },+ { min: Point3(-73.3mm, Source.MountHole.exit.Y, 15.8mm); max: Point3(-66.7mm, Source.MountHole.entry.Y, 22.4mm) }+ ]+ }+}diff --git a/fixtures/Regression/InlineStep/production/ftc09-round-remove.firmament b/fixtures/Regression/InlineStep/production/ftc09-round-remove.firmamentnew file mode 100644index 00000000..7aa34e1c--- /dev/null+++ b/fixtures/Regression/InlineStep/production/ftc09-round-remove.firmament@@ -0,0 +1,18 @@+// FTC-09's selected rigid solid only; vendor PMI is explicitly excluded.+Model Ftc09Revision {+ units: mm+ InlineStep Source {+ path: "../../../../testdata/step242/nist/FTC/nist_ftc_09_asme1_ap242-e1.stp"+ textSha256: "daad981598736d2ee6a104a7213b8d7813deaaabd7f683bc8cf8bbbf401a579a"+ geometryOnly: true+ }+ Recognize Source {+ Region MountHole {+ kind: HoleShaft+ candidate: "through-hole:step-1255+1282"+ }+ }+ Remove Source.MountHole {+ within: { min: Point3(-88.4mm, Source.MountHole.exit.Y, 15.7mm); max: Point3(-81.8mm, Source.MountHole.entry.Y, 22.4mm) }+ }+}diff --git a/testdata/step242/manifests/nist.v0.canonical-linux.json b/testdata/step242/manifests/nist.v0.canonical-linux.jsonindex 87f8ee96..c37a615b 100644--- a/testdata/step242/manifests/nist.v0.canonical-linux.json+++ b/testdata/step242/manifests/nist.v0.canonical-linux.json@@ -1,5 +1,5 @@{"testdata/step242/nist/CTC/nist_ctc_03_asme1_ap242-e2.stp": "4020b5730a2b71e9d3678f171c46f4b5891ce3beff5c344eff7cd6dbda10e6cd",- "testdata/step242/nist/FTC/nist_ftc_09_asme1_ap242-e1.stp": "96dd2fa0c9e673f97c9905dbf0f7d597d3191abe5df87a160064dc9bf9d92646",+ "testdata/step242/nist/FTC/nist_ftc_09_asme1_ap242-e1.stp": "21b87111a1f61ba064f488b29c159536452aa461810cdbb3c3e3c9a7fcaef4e9","testdata/step242/nist/STC/nist_stc_09_asme1_ap242-e3.stp": "0a97849ebbb96a0c7761516b769faf7425ff99e1080e74a6e9a3ec0eb704e7c5"}diff --git a/testdata/step242/manifests/nist.v0.report.json b/testdata/step242/manifests/nist.v0.report.jsonindex a687d656..fb7e8447 100644--- a/testdata/step242/manifests/nist.v0.report.json+++ b/testdata/step242/manifests/nist.v0.report.json@@ -33,11 +33,11 @@"diagnosticCount": 0,"exceptionEscaped": false,"topologyCounts": {- "vertices": 876,- "edges": 1416,- "faces": 637+ "vertices": 870,+ "edges": 1410,+ "faces": 635},- "canonicalSha256": "e8998780c677c585769af01479455d77563f849d8a2159e63095a3a22e516f69"+ "canonicalSha256": "42cb87942c413bc8032d8f6e13bbbfbfd7c17d20b620dc12872338977cc3cf59"},{"fileId": "testdata_step242_nist_CTC_nist_ctc_03_asme1_ap242-e2",@@ -73,11 +73,11 @@"diagnosticCount": 0,"exceptionEscaped": false,"topologyCounts": {- "vertices": 664,- "edges": 1110,- "faces": 484+ "vertices": 662,+ "edges": 1108,+ "faces": 483},- "canonicalSha256": "b5c7b340162e8354e9fb8b33ae273d2c0cf39fcba7563fd5d02bd70f30a2c28d"+ "canonicalSha256": "7a3421904737f69b48e2a47c1f0e1c8de10d7bc7b913683b5808f172038d76d3"},{"fileId": "testdata_step242_nist_CTC_nist_ctc_05_asme1_ap242-e1",@@ -133,11 +133,11 @@"diagnosticCount": 0,"exceptionEscaped": false,"topologyCounts": {- "vertices": 588,- "edges": 871,- "faces": 306+ "vertices": 582,+ "edges": 865,+ "faces": 304},- "canonicalSha256": "2cc896fdc31ed01567e5f785cafd8c412fa83fc3e9eee3c9be5e8ecc0283cab4"+ "canonicalSha256": "a6f80792aaa5ed374467341670897e9a70d34dc421d82006c6689fa4750a8a8b"},{"fileId": "testdata_step242_nist_FTC_nist_ftc_08_asme1_ap242-e1-tg",@@ -193,11 +193,11 @@"diagnosticCount": 0,"exceptionEscaped": false,"topologyCounts": {- "vertices": 304,- "edges": 458,- "faces": 159+ "vertices": 300,+ "edges": 454,+ "faces": 158},- "canonicalSha256": "ebb4cbea28ee39bc30f51e7fb51e14c7920b92c3494e90a732cff7b443e51099"+ "canonicalSha256": "8c4ef481e1c337e5e730091ef098ce99b33b6dec9f1e1c9da8e705162a7d761e"},{"fileId": "testdata_step242_nist_FTC_nist_ftc_10_asme1_ap242-e2",@@ -213,11 +213,11 @@"diagnosticCount": 0,"exceptionEscaped": false,"topologyCounts": {- "vertices": 572,- "edges": 813,- "faces": 268+ "vertices": 560,+ "edges": 799,+ "faces": 264},- "canonicalSha256": "8eeb191ff5607820ed5f9a2116f3ade55732f984f265191da17e191a3e748236"+ "canonicalSha256": "961fe8d5bceb54ad061d9247217e2974385184fec000fa91a1b73591b3e327b8"},{"fileId": "testdata_step242_nist_FTC_nist_ftc_11_asme1_ap242-e2",@@ -273,11 +273,11 @@"diagnosticCount": 0,"exceptionEscaped": false,"topologyCounts": {- "vertices": 588,- "edges": 871,- "faces": 306+ "vertices": 582,+ "edges": 865,+ "faces": 304},- "canonicalSha256": "811d2ac7736a815715ee5aa4f7b955b56be156e3cb34999f203ce6eac325b94a"+ "canonicalSha256": "7961c738bac65581792fb5336ecaae633fa6366465e466fc0ac2fb177a7ce38c"},{"fileId": "testdata_step242_nist_STC_nist_stc_08_asme1_ap242-e3",@@ -293,11 +293,11 @@"diagnosticCount": 0,"exceptionEscaped": false,"topologyCounts": {- "vertices": 446,- "edges": 709,- "faces": 271+ "vertices": 442,+ "edges": 705,+ "faces": 270},- "canonicalSha256": "526d3c15f84f113cf132d8a0e0a7c8b23299e6da145a2389303ebb8dd2d431cb"+ "canonicalSha256": "35a86a0c796082d9a9b7b8655ffeaeeef73a935a075c19b40fdf7ebee21be372"},{"fileId": "testdata_step242_nist_STC_nist_stc_09_asme1_ap242-e3",