Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Support pinned imported hole revisions
Yuechen Li58c18af85df6
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 2601af71..92522e4a 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -582,8 +582,9 @@ 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),+ 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),inlineStepMigration = build.Value.Export.InlineStepMigration,+ importedHoleRevision = build.Value.Export.ImportedHoleRevision,inlineStepReplacementAssist = build.Value.Export.InlineStepReplacementAssist,diagnostics = build.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(d, sourcePath, diagnosticSource)),pmiExportEvidence = newdiff --git a/Aetheris.Kernel.Core.Tests/Brep/Features/BrepThroughHoleRevisionTests.cs b/Aetheris.Kernel.Core.Tests/Brep/Features/BrepThroughHoleRevisionTests.csnew file mode 100644index 00000000..780302f0--- /dev/null+++ b/Aetheris.Kernel.Core.Tests/Brep/Features/BrepThroughHoleRevisionTests.cs@@ -0,0 +1,108 @@+using System.Text.Json;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Import;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Core.Tests.Step242;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Core.Tests.Brep.Features;++public sealed class BrepThroughHoleRevisionTests+{+ const string Ctc = "testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp";+ // This policy-specific import cannot share the corpus's default strict policy.+ static readonly Lazy<BrepBody> Source = new(() => Step242Importer.ImportBody(Step242Corpus.Text(Ctc),+ new ImportPolicy(PcurveQualificationToleranceMillimetres: .01)).Value);+ static ThroughHoleRevisionRequest Request => new("MountHole", [new(1), new(2)], new(98), new(-130, 45, 0), 25,+ new(new(-175, 30, -50), new(-115, 60, 0)), .01);++ [Fact, Trait("Category", "SlowCorpus")]+ public void Ctc01_ExplicitSourceAccuracy_QualifiesAllTrimsWithoutChangingGeometry()+ {+ var strict = Step242Corpus.Body(Ctc);+ var source = Source.Value;+ Assert.Equal(ImportQualificationStatus.Qualified, source.ImportQualification!.GeometryStatus);+ Assert.Equal(636, source.Bindings.PcurveBindings.Count());+ Assert.True(BrepPcurveValidator.Validate(source, .01, requireEveryCoedge: true, samples: 1025).IsValid);+ Assert.True(strict.ImportQualification!.MissingPcurves > 0);+ Assert.Equal(JsonSerializer.Serialize(strict.Geometry.Curves), JsonSerializer.Serialize(source.Geometry.Curves));+ Assert.Equal(JsonSerializer.Serialize(strict.Geometry.Surfaces), JsonSerializer.Serialize(source.Geometry.Surfaces));+ var rejected = BrepThroughHoleRevision.Execute(source, Request with { ImportToleranceMillimetres = .001 });+ Assert.False(rejected.IsSuccess);+ }++ [Fact, Trait("Category", "SlowCorpus")]+ public void Ctc01_ReplacesOneHole_PreservesResidualIdentityAndRoundTrips()+ {+ var source = Source.Value;+ var before = JsonSerializer.Serialize(source.Topology);+ var result = BrepThroughHoleRevision.Execute(source, Request);+ Assert.True(result.IsSuccess, string.Join(" | ", result.Diagnostics.Select(d => d.Message)));+ var edit = result.Value; var body = edit.Body;+ Assert.Equal(117, body.Topology.Faces.Count()); Assert.Equal(318, body.Topology.Edges.Count());+ Assert.Equal(206, body.Topology.Vertices.Count());+ Assert.Equal(115, edit.PreservedFaces); Assert.Equal(312, edit.PreservedEdges);+ Assert.All(edit.WallFaces, id => Assert.True(id.Value > 117));+ Assert.All(edit.RetiredWallFaces, id => Assert.DoesNotContain(body.Topology.Faces, f => f.Id == id));+ foreach (var f in source.Topology.Faces.Where(f => f.Id.Value > 2))+ {+ Assert.Equal(f.Id, edit.FaceCorrespondence[f.Id]);+ Assert.Equal(source.Bindings.GetFaceBinding(f.Id), body.Bindings.GetFaceBinding(f.Id));+ Assert.Equal(source.GetFaceSurface(f.Id), body.GetFaceSurface(f.Id));+ if (f.Id.Value is not (3 or 98)) Assert.Equal(f.LoopIds, body.Topology.GetFace(f.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.Bindings.GetEdgeBinding(edge.Id), body.Bindings.GetEdgeBinding(edge.Id));+ Assert.Equal(source.GetEdgeCurve(edge.Id), body.GetEdgeCurve(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 survivingCoedges = body.Topology.Coedges.Select(c => c.Id).ToHashSet();+ Assert.All(source.Bindings.PcurveBindings.Where(b => survivingCoedges.Contains(b.CoedgeId)),+ binding => Assert.Contains(binding, body.Bindings.PcurveBindings));+ Assert.All(source.Bindings.VertexLoopParameterBindings, binding => Assert.Contains(binding, body.Bindings.VertexLoopParameterBindings));+ Assert.Equal(before, JsonSerializer.Serialize(source.Topology));+ Assert.True(BrepPcurveValidator.Validate(body, .01, requireEveryCoedge: true, samples: 1025).IsValid);+ var step = Step242Exporter.ExportBody(body, new Step242ExportOptions+ {+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,+ ImportedRecoveryToleranceMillimetres = .01+ });+ Assert.True(step.IsSuccess);+ var roundtrip = Step242Importer.ImportBody(step.Value, new ImportPolicy(PcurveQualificationToleranceMillimetres: .01));+ Assert.True(roundtrip.IsSuccess);+ Assert.Equal(ImportQualificationStatus.Qualified, roundtrip.Value.ImportQualification!.GeometryStatus);+ var cylindricalWalls = roundtrip.Value.Bindings.FaceBindings.Where(b => roundtrip.Value.GetFaceSurface(b.FaceId).Cylinder is { } c+ && System.Math.Abs(c.Radius - 12.5) < 1e-6).Select(b => roundtrip.Value.GetFaceSurface(b.FaceId).Cylinder!.Value).ToArray();+ Assert.Equal(2, cylindricalWalls.Count(c => System.Math.Abs(c.Origin.X + 130) < 1e-6 && System.Math.Abs(c.Origin.Y - 45) < 1e-6));+ Assert.DoesNotContain(cylindricalWalls, c => System.Math.Abs(c.Origin.X + 160) < 1e-6 && System.Math.Abs(c.Origin.Y - 45) < 1e-6);+ }++ [Theory, Trait("Category", "SlowCorpus")]+ [InlineData("partial")]+ [InlineData("diameter")]+ [InlineData("plane")]+ [InlineData("collision")]+ [InlineData("off-plane")]+ public void UnprovedRevision_IsRejectedWithoutChangingInput(string kind)+ {+ var source = Source.Value; var before = JsonSerializer.Serialize(source.Topology);+ var request = kind switch+ {+ "partial" => Request with { WallFaces = [new FaceId(1)] },+ "diameter" => Request with { Diameter = 30 },+ "plane" => Request with { EntryFace = new(4) },+ "collision" => Request with { Center = new(160, 45, 0), Within = new(new(-175, 30, -50), new(180, 60, 0)) },+ _ => Request with { Center = new(-130, 45, 1) }+ };+ Assert.False(BrepThroughHoleRevision.Execute(source, request).IsSuccess);+ Assert.Equal(before, JsonSerializer.Serialize(source.Topology));+ }+}diff --git a/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.cs b/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.csindex 75df4275..b8f272be 100644--- a/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.cs+++ b/Aetheris.Kernel.Core/Brep/BrepPcurveRecovery.cs@@ -124,7 +124,26 @@ public static class BrepPcurveRecoveryif (surface.Cylinder is { } cylinder)return BuildPeriodicAnalytic(surface, curve, interval, tolerance, point => CylinderUv(cylinder, point));if (surface.Cone is { } cone)+ {+ // A cone apex has no unique U coordinate. For a straight generator,+ // borrow its one-sided interior angle instead of fitting atan2(0,0).+ // The independent lift check still proves the complete admitted edge.+ if (curve.Line3 is { } generator)+ {+ var a = generator.Evaluate(interval.Start);+ var b = generator.Evaluate(interval.End);+ if ((a - cone.Apex).Length <= tolerance || (b - cone.Apex).Length <= tolerance)+ {+ var interior = ConeUv(cone, generator.Evaluate((interval.Start + interval.End) / 2));+ var start = ConeUv(cone, a) with { U = interior.U };+ var end = ConeUv(cone, b) with { U = interior.U };+ var candidate = PcurveGeometry.Line(interval, start, end);+ var residual = MaximumResidual(surface, curve, candidate, interval, 1025);+ if (residual <= tolerance) return (candidate, residual, null);+ }+ }return BuildPeriodicAnalytic(surface, curve, interval, tolerance, point => ConeUv(cone, point));+ }if (surface.Sphere is { } sphere)return BuildPeriodicAnalytic(surface, curve, interval, tolerance, point => SphereUv(sphere, point));if (surface.Torus is { } torus)diff --git a/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs b/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.csindex cd8f9fa4..81d08d0b 100644--- a/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs+++ b/Aetheris.Kernel.Core/Brep/BrepPcurveValidator.cs@@ -184,6 +184,10 @@ public static class BrepPcurveValidatorprivate static double UvDistance(SurfaceGeometry surface, SurfaceParameterPoint a, SurfaceParameterPoint b){+ // Distinct generator angles meet at one exact cone apex. Comparing U+ // there rejects a closed boundary solely because its chart is singular.+ if (surface.Cone is not null && double.Abs(a.V) <= 1e-10 && double.Abs(b.V) <= 1e-10)+ return double.Abs(a.V - b.V);var periodicity = SurfacePeriodicity.Of(surface);var du = PeriodicDelta(a.U - b.U, periodicity.UPeriod);var dv = PeriodicDelta(a.V - b.V, periodicity.VPeriod);diff --git a/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleRevision.cs b/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleRevision.csnew file mode 100644index 00000000..c837cb63--- /dev/null+++ b/Aetheris.Kernel.Core/Brep/Features/BrepThroughHoleRevision.cs@@ -0,0 +1,335 @@+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Kernel.Core.Brep.Features;++public sealed record ThroughHoleEditBounds(Point3D Min, Point3D Max);+public sealed record ThroughHoleRevisionRequest(string FeatureId, IReadOnlyList<FaceId> WallFaces,+ FaceId EntryFace, Point3D Center, double Diameter, ThroughHoleEditBounds Within,+ double ImportToleranceMillimetres = 1e-6);+public sealed record ThroughHoleRevisionResult(BrepBody Body, string FeatureId,+ IReadOnlyList<FaceId> RetiredWallFaces, IReadOnlyList<FaceId> WallFaces,+ FaceId EntryFace, FaceId ExitFace, Point3D Center, double Diameter, double Depth,+ ThroughHoleEditBounds Within, IReadOnlyDictionary<FaceId, FaceId> FaceCorrespondence,+ int PreservedFaces, int PreservedEdges, double ImportToleranceMillimetres);++/// <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>+public static 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);+ 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+ && Min.Y <= other.Max.Y + uncertainty && Max.Y >= other.Min.Y - uncertainty+ && Min.Z <= other.Max.Z + uncertainty && Max.Z >= other.Min.Z - uncertainty;+ }++ public static KernelResult<ThroughHoleRevisionResult> Execute(BrepBody source, ThroughHoleRevisionRequest request)+ {+ ArgumentNullException.ThrowIfNull(source);+ ArgumentNullException.ThrowIfNull(request);+ try+ {+ if (string.IsNullOrWhiteSpace(request.FeatureId)) throw new ArgumentException("A stable replacement 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.");+ if (region.Openings.SingleOrDefault(o => o.Face.Id == request.EntryFace).Face is not { } entry)+ throw 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)+ throw new ArgumentException("The world-space center must lie on the selected entry plane.");+ var box = new Box(request.Within.Min, request.Within.Max);+ 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("The edit envelope must be finite and span exactly the two support planes.");+ var r = request.Diameter / 2;+ foreach (var center in new[] { region.Cylinder.Origin, request.Center })+ 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 edit envelope must contain both complete holes 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) && 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.");+ var patch = MaterializeHolePatch(source, region, request.Center, r);+ var suppressed = Suppress(source, region);+ RequireQualified(suppressed, request.ImportToleranceMillimetres);+ var body = SuppressThenInsert(source, suppressed, patch, region);+ RequireQualified(body, request.ImportToleranceMillimetres);+ var maximum = source.Topology.Faces.Max(f => f.Id.Value);+ var map = source.Topology.Faces.ToDictionary(f => f.Id, f => region.Walls.Contains(f.Id) ? new FaceId(maximum + f.Id.Value) : f.Id);+ var walls = region.Walls.OrderBy(id => id.Value).Select(id => map[id]).ToArray();+ var 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,+ source.Topology.Edges.Count() - region.Edges.Count, request.ImportToleranceMillimetres));+ }+ catch (Exception error) when (error is ArgumentException or InvalidOperationException or KeyNotFoundException or NotSupportedException)+ {+ return KernelResult<ThroughHoleRevisionResult>.Failure([new(KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Error, "firmament-imported-hole-revision-rejected: " + error.Message,+ "Brep.ThroughHoleRevision")]);+ }+ }++ static bool Finite(Point3D p) => double.IsFinite(p.X) && double.IsFinite(p.Y) && double.IsFinite(p.Z);+ static void RequireQualified(BrepBody body, double tolerance)+ {+ if (!double.IsFinite(tolerance) || tolerance <= 0 || tolerance > .1)+ throw new ArgumentException("Import tolerance must be positive, finite and at most 0.1 mm.");+ if (!TopologyGraphValidator.Validate(body.Topology).IsSuccess || body.Topology.Bodies.Count() != 1 || body.Topology.Shells.Count() != 1+ || body.Topology.Coedges.GroupBy(c => c.EdgeId).Any(g => g.Count() != 2 || g.First().IsReversed == g.Last().IsReversed))+ throw new ArgumentException("A single closed oriented manifold body is required.");+ var pcurves = BrepPcurveValidator.Validate(body, tolerance, requireEveryCoedge: true, samples: 257);+ if (!pcurves.IsValid || pcurves.MaximumReconstructionDeviation > tolerance || !BrepExportPreflight.Validate(body, tolerance).IsValid)+ throw new ArgumentException("The imported or revised body is not qualified at the requested tolerance; required trim or boundary checks failed.");+ }+ static 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 incidence = body.Topology.Faces.SelectMany(f => Edges(body, f).Select(e => (Edge: e, Face: f.Id)))+ .GroupBy(x => x.Edge).ToDictionary(g => g.Key, g => g.Select(x => x.Face).Distinct().ToArray());+ var walls = new HashSet<FaceId> { seed };+ var queue = new Queue<FaceId>(); queue.Enqueue(seed);+ while (queue.TryDequeue(out var id))+ {+ foreach (var adjacent in Edges(body, body.Topology.GetFace(id)).SelectMany(e => incidence[e]).Distinct())+ {+ if (walls.Contains(adjacent) || Surface(body, adjacent).Cylinder is not { } other) continue;+ var d = other.Origin - cylinder.Origin;+ if (System.Math.Abs(other.Radius - cylinder.Radius) > Tol || other.Axis.ToVector().Cross(cylinder.Axis.ToVector()).Length > Tol+ || (d - cylinder.Axis.ToVector() * d.Dot(cylinder.Axis.ToVector())).Length > Tol) continue;+ walls.Add(adjacent); queue.Enqueue(adjacent);+ }+ }+ if (walls.Any(id => body.Bindings.GetFaceBinding(id).Orientation.IsAlignedWithSurface)) throw new ArgumentException("Not an inward cylindrical void wall.");+ var wallEdges = walls.SelectMany(id => Edges(body, body.Topology.GetFace(id))).ToHashSet();+ var openings = new List<(Face Face, Loop Loop)>();+ foreach (var face in body.Topology.Faces.Where(f => !walls.Contains(f.Id)))+ foreach (var loop in face.LoopIds.Select(body.Topology.GetLoop))+ {+ var 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+ || body.Bindings.GetFaceBoundaryRoleBinding(loop.Id).Role != FaceBoundaryRole.Inner)+ throw new ArgumentException("Void boundary is not two isolated circular inner loops on Z-normal planes.");+ 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.");+ var trim = body.Bindings.GetEdgeBinding(edge).TrimInterval ?? throw new ArgumentException("Missing arc trim.");+ angularCoverage += System.Math.Abs(trim.End - trim.Start);+ }+ if (System.Math.Abs(angularCoverage - 2 * double.Pi) > Tol) throw new ArgumentException("Opening does not cover a complete circle.");+ openings.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.");+ 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))+ 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).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]);+ }++ static BrepBody MaterializeHolePatch(BrepBody source, Region region, Point3D center, double radius)+ {+ var changedCurves = region.Edges.Select(e => source.Bindings.GetEdgeBinding(e).CurveGeometryId).ToHashSet();+ var changedSurfaces = region.Walls.Select(f => source.Bindings.GetFaceBinding(f).SurfaceGeometryId).ToHashSet();+ if (source.Bindings.EdgeBindings.Any(b => changedCurves.Contains(b.CurveGeometryId) && !region.Edges.Contains(b.EdgeId))+ || 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, 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);+ }+ var bindings = new BrepBindingModel();+ foreach (var b in source.Bindings.EdgeBindings) bindings.AddEdgeBinding(b);+ foreach (var b in source.Bindings.FaceBindings) bindings.AddFaceBinding(b);+ foreach (var b in source.Bindings.FaceBoundaryRoleBindings) bindings.AddFaceBoundaryRoleBinding(b);+ foreach (var b in source.Bindings.VertexLoopParameterBindings) bindings.AddVertexLoopParameterBinding(b);+ foreach (var b in source.Bindings.PcurveBindings)+ {+ var edge = source.Topology.GetCoedge(b.CoedgeId).EdgeId;+ if (!region.Edges.Contains(edge)) { bindings.AddPcurveBinding(b); continue; }+ var pcurve = b.Pcurve;+ if (!region.Walls.Contains(b.FaceId))+ {+ var plane = Surface(source, b.FaceId).Plane!.Value;+ var circle = geometry.GetCurve(source.Bindings.GetEdgeBinding(edge).CurveGeometryId).Circle3!.Value;+ var d = circle.Center - plane.Origin;+ pcurve = PcurveGeometry.Ellipse(b.Pcurve.Domain, new(d.Dot(plane.UAxis.ToVector()), d.Dot(plane.VAxis.ToVector())),+ new(circle.Radius * circle.XAxis.ToVector().Dot(plane.UAxis.ToVector()), circle.Radius * circle.XAxis.ToVector().Dot(plane.VAxis.ToVector())),+ new(circle.Radius * circle.YAxis.ToVector().Dot(plane.UAxis.ToVector()), circle.Radius * circle.YAxis.ToVector().Dot(plane.VAxis.ToVector())));+ }+ bindings.AddPcurveBinding(b with+ {+ Pcurve = pcurve,+ SourceStepPcurveEntityId = null,+ SourceStepCurveEntityId = null,+ SourceStepSurfaceEntityId = null,+ Qualification = null+ });+ }+ var points = Points(source);+ foreach (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);+ }+ return new(source.Topology.Clone(), geometry, bindings, points, null, source.ShellRepresentation);+ }++ static BrepBody Suppress(BrepBody source, Region region)+ {+ var removedLoops = region.Walls.SelectMany(id => source.Topology.GetFace(id).LoopIds).Concat(region.Openings.Select(o => o.Loop.Id)).ToHashSet();+ var topology = new TopologyModel();+ foreach (var v in source.Topology.Vertices.Where(v => !region.Vertices.Contains(v.Id))) topology.AddVertex(v);+ foreach (var e in source.Topology.Edges.Where(e => !region.Edges.Contains(e.Id))) topology.AddEdge(e);+ foreach (var c in source.Topology.Coedges.Where(c => !removedLoops.Contains(c.LoopId))) topology.AddCoedge(c);+ foreach (var l in source.Topology.Loops.Where(l => !removedLoops.Contains(l.Id))) topology.AddLoop(l);+ foreach (var f in source.Topology.Faces.Where(f => !region.Walls.Contains(f.Id))) topology.AddFace(f with { LoopIds = f.LoopIds.Where(id => !removedLoops.Contains(id)).ToArray() });+ foreach (var s in source.Topology.Shells) topology.AddShell(s with { FaceIds = s.FaceIds.Where(id => !region.Walls.Contains(id)).ToArray() });+ foreach (var b in source.Topology.Bodies) topology.AddBody(b);+ return Assemble(source, topology, Points(source).Where(p => !region.Vertices.Contains(p.Key)).ToDictionary(), [], [], [], []);+ }++ static BrepBody SuppressThenInsert(BrepBody original, BrepBody suppressed, BrepBody moved, Region region)+ {+ var wallLoops = region.Walls.SelectMany(id => original.Topology.GetFace(id).LoopIds).ToHashSet();+ var changedLoops = wallLoops.Concat(region.Openings.Select(o => o.Loop.Id)).ToHashSet();+ var vMap = region.Vertices.ToDictionary(id => id, id => new VertexId(original.Topology.Vertices.Max(v => v.Id.Value) + id.Value));+ var eMap = region.Edges.ToDictionary(id => id, id => new EdgeId(original.Topology.Edges.Max(v => v.Id.Value) + id.Value));+ var lMap = changedLoops.ToDictionary(id => id, id => new LoopId(original.Topology.Loops.Max(v => v.Id.Value) + id.Value));+ var cMap = original.Topology.Coedges.Where(c => changedLoops.Contains(c.LoopId)).ToDictionary(c => c.Id, c => new CoedgeId(original.Topology.Coedges.Max(v => v.Id.Value) + c.Id.Value));+ var fMap = region.Walls.ToDictionary(id => id, id => new FaceId(original.Topology.Faces.Max(v => v.Id.Value) + id.Value));+ var topology = new TopologyModel();+ foreach (var v in moved.Topology.Vertices) topology.AddVertex(v with { Id = vMap.GetValueOrDefault(v.Id, v.Id) });+ foreach (var e in moved.Topology.Edges) topology.AddEdge(e with { Id = eMap.GetValueOrDefault(e.Id, e.Id), StartVertexId = vMap.GetValueOrDefault(e.StartVertexId, e.StartVertexId), EndVertexId = vMap.GetValueOrDefault(e.EndVertexId, e.EndVertexId) });+ foreach (var c in moved.Topology.Coedges) topology.AddCoedge(c with { Id = cMap.GetValueOrDefault(c.Id, c.Id), EdgeId = eMap.GetValueOrDefault(c.EdgeId, c.EdgeId), LoopId = lMap.GetValueOrDefault(c.LoopId, c.LoopId), NextCoedgeId = cMap.GetValueOrDefault(c.NextCoedgeId, c.NextCoedgeId), PrevCoedgeId = cMap.GetValueOrDefault(c.PrevCoedgeId, c.PrevCoedgeId) });+ foreach (var l in moved.Topology.Loops) topology.AddLoop(l with { Id = lMap.GetValueOrDefault(l.Id, l.Id), CoedgeIds = l.CoedgeIds.Select(id => cMap.GetValueOrDefault(id, id)).ToArray() });+ foreach (var f in suppressed.Topology.Faces)+ {+ var opening = region.Openings.SingleOrDefault(o => o.Face.Id == f.Id);+ topology.AddFace(opening.Face is null ? f : f with { LoopIds = f.LoopIds.Append(lMap[opening.Loop.Id]).ToArray() });+ }+ foreach (var f in moved.Topology.Faces.Where(f => region.Walls.Contains(f.Id))) topology.AddFace(f with { Id = fMap[f.Id], LoopIds = f.LoopIds.Select(id => lMap[id]).ToArray() });+ foreach (var s in original.Topology.Shells) topology.AddShell(s with { FaceIds = s.FaceIds.Select(id => fMap.GetValueOrDefault(id, id)).ToArray() });+ foreach (var b in original.Topology.Bodies) topology.AddBody(b);+ var points = Points(moved).ToDictionary(p => vMap.GetValueOrDefault(p.Key, p.Key), p => p.Value);+ return Assemble(moved, topology, points, eMap, cMap, lMap, fMap);+ }++ static BrepBody Assemble(BrepBody geometrySource, TopologyModel topology, Dictionary<VertexId, Point3D> points,+ Dictionary<EdgeId, EdgeId> eMap, Dictionary<CoedgeId, CoedgeId> cMap, Dictionary<LoopId, LoopId> lMap, Dictionary<FaceId, FaceId> fMap)+ {+ var edges = topology.Edges.Select(e => e.Id).ToHashSet(); var faces = topology.Faces.Select(f => f.Id).ToHashSet();+ var loops = topology.Loops.Select(l => l.Id).ToHashSet(); var coedges = topology.Coedges.Select(c => c.Id).ToHashSet();+ var bindings = new BrepBindingModel();+ foreach (var b in geometrySource.Bindings.EdgeBindings) { var id = eMap.GetValueOrDefault(b.EdgeId, b.EdgeId); if (edges.Contains(id)) bindings.AddEdgeBinding(b with { EdgeId = id }); }+ foreach (var b in geometrySource.Bindings.FaceBindings) { var id = fMap.GetValueOrDefault(b.FaceId, b.FaceId); if (faces.Contains(id)) bindings.AddFaceBinding(b with { FaceId = id, SourceStepEntityId = fMap.ContainsKey(b.FaceId) ? null : b.SourceStepEntityId }); }+ foreach (var b in geometrySource.Bindings.FaceBoundaryRoleBindings) { var id = lMap.GetValueOrDefault(b.LoopId, b.LoopId); if (loops.Contains(id)) bindings.AddFaceBoundaryRoleBinding(b with { LoopId = id, FaceId = fMap.GetValueOrDefault(b.FaceId, b.FaceId), SourceStepEntityId = lMap.ContainsKey(b.LoopId) ? null : b.SourceStepEntityId }); }+ foreach (var b in geometrySource.Bindings.PcurveBindings) { var id = cMap.GetValueOrDefault(b.CoedgeId, b.CoedgeId); if (coedges.Contains(id)) bindings.AddPcurveBinding(b with { CoedgeId = id, FaceId = fMap.GetValueOrDefault(b.FaceId, b.FaceId) }); }+ foreach (var b in geometrySource.Bindings.VertexLoopParameterBindings)+ if (loops.Contains(b.LoopId) && faces.Contains(b.FaceId) && points.ContainsKey(b.VertexId)) bindings.AddVertexLoopParameterBinding(b);+ var geometry = new BrepGeometryStore();+ foreach (var id in bindings.EdgeBindings.Select(b => b.CurveGeometryId).Distinct()) geometry.AddCurve(id, geometrySource.Geometry.GetCurve(id));+ foreach (var id in bindings.FaceBindings.Select(b => b.SurfaceGeometryId).Distinct()) geometry.AddSurface(id, geometrySource.Geometry.GetSurface(id));+ return new(topology, geometry, bindings, points, null, geometrySource.ShellRepresentation);+ }++ static Box FaceBounds(BrepBody body, Face face)+ {+ var points = Edges(body, face).SelectMany(e => CurveHull(body, e)).ToArray();+ if (points.Length == 0) throw new ArgumentException("Unbounded face.");+ if (Surface(body, face.Id).Plane is not null) return Bounds(points);+ if (Surface(body, face.Id).Cylinder is { } c)+ {+ var values = points.Select(p => (p - c.Origin).Dot(c.Axis.ToVector())).ToArray();+ return AxialBounds(c.Origin, c.Axis.ToVector(), values.Min(), values.Max(), c.Radius);+ }+ if (Surface(body, face.Id).Cone is { } cone)+ {+ var values = points.Select(p => (p - cone.Apex).Dot(cone.Axis.ToVector())).ToArray();+ return AxialBounds(cone.Apex, cone.Axis.ToVector(), values.Min(), values.Max(), System.Math.Max(System.Math.Abs(values.Min()), System.Math.Abs(values.Max())) * System.Math.Tan(cone.SemiAngleRadians));+ }+ throw new ArgumentException($"No conservative support bound for {Surface(body, face.Id).Kind}.");+ }++ static Box AxialBounds(Point3D origin, Vector3D axis, double low, double high, double radius)+ {+ var a = origin + axis * low; var b = origin + axis * high;+ var x = radius * System.Math.Sqrt(System.Math.Max(0, 1 - axis.X * axis.X));+ var y = radius * System.Math.Sqrt(System.Math.Max(0, 1 - axis.Y * axis.Y));+ var z = radius * System.Math.Sqrt(System.Math.Max(0, 1 - axis.Z * axis.Z));+ return new(new(System.Math.Min(a.X, b.X) - x, System.Math.Min(a.Y, b.Y) - y, System.Math.Min(a.Z, b.Z) - z), new(System.Math.Max(a.X, b.X) + x, System.Math.Max(a.Y, b.Y) + y, System.Math.Max(a.Z, b.Z) + z));+ }++ static IEnumerable<Point3D> CurveHull(BrepBody body, EdgeId id)+ {+ var c = Curve(body, id);+ var interval = body.Bindings.GetEdgeBinding(id).TrimInterval ?? throw new ArgumentException("Missing finite trim.");+ if (c.Line3 is { } line) return [line.Evaluate(interval.Start), line.Evaluate(interval.End)];+ if (c.Circle3 is { } circle)+ {+ var n = circle.Normal;+ var x = circle.Radius * System.Math.Sqrt(System.Math.Max(0, 1 - n.X * n.X));+ var y = circle.Radius * System.Math.Sqrt(System.Math.Max(0, 1 - n.Y * n.Y));+ var z = circle.Radius * System.Math.Sqrt(System.Math.Max(0, 1 - n.Z * n.Z));+ // All eight corners are necessary for conservative projection onto+ // oblique cylinder/cone axes; two opposite corners can cancel terms.+ return new[] { -x, x }.SelectMany(dx => new[] { -y, y }.SelectMany(dy => new[] { -z, z }.Select(dz => circle.Center + new Vector3D(dx, dy, dz))));+ }+ if (c.BSpline3 is { } spline) return spline.ControlPoints;+ throw new ArgumentException($"Unsupported conservative curve hull {c.Kind}.");+ }++ 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)+ {+ if (c.Circle3 is { } circle) return CurveGeometry.FromCircle(new(new(center.X, center.Y, circle.Center.Z), 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));+ }+ throw new NotSupportedException("Only circular rims and axial seams are admitted.");+ }+ static IEnumerable<EdgeId> Edges(BrepBody b, Face f) => f.LoopIds.SelectMany(id => b.Topology.GetLoop(id).CoedgeIds).Select(id => b.Topology.GetCoedge(id).EdgeId).Distinct();+ static SurfaceGeometry Surface(BrepBody b, FaceId id) { b.TryGetFaceSurfaceGeometry(id, out var s); return s ?? throw new ArgumentException("Missing surface."); }+ static CurveGeometry Curve(BrepBody b, EdgeId id) { b.TryGetEdgeCurveGeometry(id, out var c); return c ?? throw new ArgumentException("Missing curve."); }+ static Dictionary<VertexId, Point3D> Points(BrepBody b) => b.Topology.Vertices.ToDictionary(v => v.Id, v => b.TryGetVertexPoint(v.Id, out var p) ? p : throw new ArgumentException("Missing vertex."));+}diff --git a/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs b/Aetheris.Kernel.Core/Step242/Step242ExportOptions.csindex b4706f5d..9cdf8684 100644--- a/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs+++ b/Aetheris.Kernel.Core/Step242/Step242ExportOptions.cs@@ -19,6 +19,9 @@ public enum BrepExportPreflightPolicypublic sealed class Step242ExportOptions{+ /// <summary>Declared distance accuracy of retained imported geometry, in mm.+ /// Null preserves the historical export. This is not a machining tolerance.</summary>+ public double? DistanceAccuracyMillimetres { get; init; }public string ProductName { get; init; } = "AetherisBody";public string ProductId { get; init; } = "AETHERIS";diff --git a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs b/Aetheris.Kernel.Core/Step242/Step242Exporter.csindex 15ca18f6..db55a095 100644--- a/Aetheris.Kernel.Core/Step242/Step242Exporter.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Exporter.cs@@ -161,7 +161,17 @@ public static class Step242Exportervar lengthUnitId = writer.AddRawEntity("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))");var planeAngleUnitId = writer.AddRawEntity("(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))");var solidAngleUnitId = writer.AddRawEntity("(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT())");- var repContextId = writer.AddRawEntity($"(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNIT_ASSIGNED_CONTEXT(({lengthUnitId},{planeAngleUnitId},{solidAngleUnitId}))REPRESENTATION_CONTEXT('3','3D'))");+ var uncertaintyContext = string.Empty;+ if (options.DistanceAccuracyMillimetres is { } accuracy)+ {+ if (!double.IsFinite(accuracy) || accuracy <= 0)+ return Failure("DistanceAccuracyMillimetres must be positive and finite.", "Exporter.DistanceAccuracy");+ var uncertainty = writer.AddEntity("UNCERTAINTY_MEASURE_WITH_UNIT",+ "LENGTH_MEASURE(" + accuracy.ToString("R", System.Globalization.CultureInfo.InvariantCulture) + ")",+ lengthUnitId, "'distance_accuracy_value'", "'Declared accuracy of retained source geometry'");+ uncertaintyContext = $"GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT(({uncertainty}))";+ }+ var repContextId = writer.AddRawEntity($"(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNIT_ASSIGNED_CONTEXT(({lengthUnitId},{planeAngleUnitId},{solidAngleUnitId})){uncertaintyContext}REPRESENTATION_CONTEXT('3','3D'))");var shapeRepresentationId = writer.AddEntity("SHAPE_REPRESENTATION", Step242TextWriter.String(options.ProductName), Step242TextWriter.List(brepId), Step242TextWriter.Ref(repContextId));writer.AddEntity("SHAPE_DEFINITION_REPRESENTATION", Step242TextWriter.Ref(shapeId), Step242TextWriter.Ref(shapeRepresentationId));EmitSemanticPmi(writer, shapeId, shapeRepresentationId, repContextId, lengthUnitId, advancedFaceIds, semanticPmi);diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentImportedHoleRevisionTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentImportedHoleRevisionTests.csnew file mode 100644index 00000000..2b9bf557--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentImportedHoleRevisionTests.cs@@ -0,0 +1,159 @@+using Aetheris.Kernel.Core.Import;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentImportedHoleRevisionTests+{+ 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 => File.ReadAllText(Path.Combine(DirectoryPath, "ctc01-hole-move.firmament"));+ static FirmamentV2ValidationReport Validate(string source) => FirmamentBuildAdmissionValidation.Admit(+ FirmamentV2ValidationReportBuilder.Build(FirmamentV2Parser.Parse(source, DirectoryPath), "ctc01-hole-move.firmament", sourceText: source), source, DirectoryPath);++ [Fact]+ public void GoldenPath_AdmitsBuildsAndExportsQualifiedMovedHoleWithSemanticPmi()+ {+ var source = Source;+ 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)));+ var export = build.Value; var report = Assert.IsType<FirmamentImportedHoleRevisionReport>(export.ImportedHoleRevision);+ Assert.True(report.SourceSemanticsExcluded); Assert.Equal(.01, report.ImportToleranceMillimetres);+ Assert.Equal(115, report.PreservedFaces); Assert.Equal(312, report.PreservedEdges);+ Assert.Equal(25, report.Diameter); Assert.Equal(50, report.Depth);+ Assert.Equal("Ctc01Revision", export.DocumentName);+ Assert.Equal(25, Assert.Single(export.DimensionInspection!).Value);+ Assert.True(export.InlineStepMigration!.ResidualSurgery);+ Assert.Contains(build.Diagnostics, d => d.Severity == Core.Diagnostics.KernelDiagnosticSeverity.Warning && d.Message.StartsWith("firmament-inline-step-source-semantics-excluded"));+ var imported = Step242Importer.ImportBody(export.StepText);+ Assert.True(imported.IsSuccess, string.Join(" | ", imported.Diagnostics.Select(d => d.Message)));+ Assert.Equal(ImportQualificationStatus.Qualified, imported.Value.ImportQualification!.GeometryStatus);+ Assert.Equal(636, imported.Value.Bindings.PcurveBindings.Count());+ Assert.Equal(.01, imported.Value.ImportQualification.SourceDistanceAccuracyMillimetres);+ var pmi = Step242SemanticPmiInspector.Inspect(export.StepText);+ var hole = Assert.Single(pmi.Items, i => i.Kind == "Diameter");+ Assert.Equal(25, hole.Value); Assert.Equal(50, hole.Depth); Assert.Equal(2, hole.GeometricFaceEntityIds.Count);+ Assert.All(hole.GeometricFaceEntityIds, id =>+ {+ var binding = Assert.Single(imported.Value.Bindings.FaceBindings, b => b.SourceStepEntityId == id);+ imported.Value.TryGetFaceSurfaceGeometry(binding.FaceId, out var support);+ Assert.Equal(-130, support!.Cylinder!.Value.Origin.X, 6);+ });+ Assert.True(export.RuntimeAdmissionDocument!.Solid.InlineStep!.TopologyMap.TryResolveFaceEntity("#764", out var mapped));+ Assert.Equal("face-118", mapped);+ }++ [Fact]+ public void AuthoredPmi_ResolvesOriginalRegionToReplacementWalls()+ {+ var source = Source[..Source.LastIndexOf('}')] + """+ Pmi { HoleDiameter MovedSize { target: Source.region("MountHole") value: 25mm } }+ }+ """;+ var build = FirmamentBuildAndExport.CompileSource(source, DirectoryPath);+ Assert.True(build.IsSuccess, string.Join(" | ", build.Diagnostics.Select(d => d.Message)));+ var inspection = Step242SemanticPmiInspector.Inspect(build.Value.StepText);+ var size = Assert.Single(inspection.Items, item => item.Kind == "Diameter" && item.Name.Contains("MovedSize"));+ Assert.Equal(25, size.Value);+ Assert.Equal(2, size.GeometricFaceEntityIds.Count);+ var body = Step242Importer.ImportBody(build.Value.StepText).Value;+ Assert.All(size.GeometricFaceEntityIds, id => {+ var binding = Assert.Single(body.Bindings.FaceBindings, b => b.SourceStepEntityId == id);+ Assert.True(body.TryGetFaceSurfaceGeometry(binding.FaceId, out var support));+ Assert.Equal(-130, support!.Cylinder!.Value.Origin.X, 6);+ });+ }++ static string StepPath => Path.GetFullPath(Path.Combine(DirectoryPath, "../../../../testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp"));++ [Fact]+ public void BytePin_RemainsExactAndExplicit()+ {+ var digest = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(StepPath))).ToLowerInvariant();+ var source = Source.Replace("textSha256:", "sha256:").Replace("341cea888fb316673ed683e59391c11b4f96cff2542d9387e135f06682dbd745", digest);+ var build = FirmamentBuildAndExport.CompileSource(source, DirectoryPath);+ Assert.True(build.IsSuccess, string.Join(" | ", build.Diagnostics.Select(d => d.Message)));+ Assert.Equal("sha256-bytes", build.Value.ImportedHoleRevision!.SourceHashKind);+ Assert.Equal(digest, build.Value.ImportedHoleRevision.SourceHash);+ Assert.Equal(digest, build.Value.ImportedHoleRevision.SourceByteHash);+ }++ [Fact]+ public void BytePin_DoesNotSilentlyNormalizeLineEndings()+ {+ var text = File.ReadAllText(StepPath).Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n').Replace("\n", "\r\n", StringComparison.Ordinal);+ var resources = new Dictionary<string, string> { ["testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp"] = text };+ var build = FirmamentBuildAndExport.CompileSource(Source.Replace("textSha256:", "sha256:"), "fixtures/Regression/InlineStep/production", resources);+ Assert.False(build.IsSuccess);+ Assert.Contains(build.Diagnostics, d => d.Message.Contains("firmament-inline-step-source-pin-mismatch", StringComparison.Ordinal));+ }++ [Theory]+ [InlineData(false)] [InlineData(true)]+ public void TextPin_IsPortableAcrossExplicitLfAndCrlfResourceSnapshots(bool crlf)+ {+ var text = File.ReadAllText(StepPath).Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n');+ if (crlf) text = text.Replace("\n", "\r\n", StringComparison.Ordinal);+ var resources = new Dictionary<string, string> { ["testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp"] = text };+ var build = FirmamentBuildAndExport.CompileSource(Source, "fixtures/Regression/InlineStep/production", resources);+ Assert.True(build.IsSuccess, string.Join(" | ", build.Diagnostics.Select(d => d.Message)));+ Assert.Equal("sha256-utf8-lf", build.Value.ImportedHoleRevision!.SourceHashKind);+ Assert.Equal("341cea888fb316673ed683e59391c11b4f96cff2542d9387e135f06682dbd745", build.Value.ImportedHoleRevision.SourceHash);+ Assert.Equal(25, build.Value.ImportedHoleRevision.Diameter);+ }++ [Theory]+ [InlineData("pin")]+ [InlineData("tolerance")]+ [InlineData("annotations")]+ [InlineData("diameter")]+ [InlineData("partial")]+ [InlineData("outside")]+ [InlineData("evidence")]+ [InlineData("on")]+ [InlineData("field")]+ [InlineData("bounds-field")]+ [InlineData("import-field")]+ [InlineData("pin-conflict")][InlineData("named-face")][InlineData("object-type")][InlineData("no-replacement")]+ [InlineData("no-pin")]+ [InlineData("notes")]+ public void InvalidIntent_ValidateAndBuildRejectWithLocatedDiagnostics(string change)+ {+ var source = change switch+ {+ "pin" => Source.Replace("341cea88", "041cea88"),+ "tolerance" => Source.Replace("importTolerance: 0.01mm", "importTolerance: 0.001mm"),+ "annotations" => Source.Replace("geometryOnly: true", "geometryOnly: false"),+ "diameter" => Source.Replace("diameter: 25mm", "diameter: 30mm"),+ "partial" => Source.Replace("[\"#764\", \"#765\"]", "[\"#764\"]"),+ "outside" => Source.Replace("Point3(-130mm, 45mm, 0mm)", "Point3(200mm, 45mm, 0mm)"),+ "evidence" => Source.Replace("radius: 12.5mm", "radius: 13mm"),+ "on" => Source.Replace("Source.Face(98)", "Source.Face(4)"),+ "field" => Source.Replace("diameter: 25mm", "diammeter: 25mm"),+ "pin-conflict" => Source.Replace("textSha256:", "sha256: \"0000000000000000000000000000000000000000000000000000000000000000\"\n textSha256:"),+ "named-face" => Source.Replace("Source.Face(98)", "Source.Face(ignored: 98)"),+ "object-type" => Source.Replace("within: {", "within: Nonsense {"),+ "no-replacement" => Source[..Source.IndexOf(" Replace Source.MountHole", StringComparison.Ordinal)] + "}\n",+ "no-pin" => Source.Replace("textSha256:", "// textSha256:"),+ "notes" => Source.Replace("radius: 12.5mm", "notes: [12]\n radius: 12.5mm"),+ "bounds-field" => Source.Replace("min: Point3", "minimum: Point3"),+ _ => Source.Replace("geometryOnly: true", "geometryOnyl: true")+ };+ var build = FirmamentBuildAndExport.CompileSource(source, DirectoryPath);+ var validation = Validate(source);+ Assert.False(build.IsSuccess);+ Assert.Equal("invalid", validation.Status);+ Assert.Contains(validation.Diagnostics, d => d.Severity is "error" or "fatal");+ Assert.Contains(validation.Diagnostics, d => d.SourceSpan is not null);+ Assert.DoesNotContain(validation.Diagnostics, d => d.Code.Contains("toon", StringComparison.OrdinalIgnoreCase));+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 7384204e..4803216a 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -178,7 +178,10 @@ public static partial class FirmamentBuildAndExport{var parsed = FirmamentV2Parser.Parse(source, sourceDirectory, null, null, resources);if (!parsed.IsSuccess || parsed.Document is null) return export;- export = export with { DocumentName = parsed.Document.ModelName, RuntimeAdmissionDocument = parsed.Document,+ export = export with+ {+ DocumentName = parsed.Document.ModelName,+ RuntimeAdmissionDocument = export.RuntimeAdmissionDocument ?? parsed.Document,ConceptDisplayValues = parsed.Document.ConceptIr?.Structs?? ConceptIrResolver.RetainSpatialStructs(parsed.DiagnosticSource ?? parsed.BoundSource ?? source) };@@ -226,14 +229,15 @@ public static partial class FirmamentBuildAndExportIReadOnlyDictionary<string, string>? resources = null){var parsed = FirmamentV2Parser.Parse(source, sourceDirectory, null, null, resources);- if (!parsed.IsSuccess || parsed.Document is null || parsed.Document.Pmi is not { Count: > 0 } pmi)- return KernelResult<bool>.Success(true);+ if (!parsed.IsSuccess || parsed.Document is null) return KernelResult<bool>.Success(true);+ var pmi = parsed.Document.Pmi ?? [];+ if (pmi.Count == 0 && export.GeneratedSemanticPmi.Count == 0) return KernelResult<bool>.Success(true);var support = ValidateV2PmiExportSupport(parsed.Document);if (!support.IsSuccess) return support;- var expectedDatums = pmi.Count(record => record.Kind == FirmamentV2PmiKind.DatumPlane);- var expectedDiameters = pmi.Count(record => record.Kind == FirmamentV2PmiKind.HoleDiameter);+ var expectedDatums = pmi.Count(record => record.Kind == FirmamentV2PmiKind.DatumPlane) + export.GeneratedSemanticPmi.OfType<Step242SemanticPmiDatum>().Count();+ var expectedDiameters = pmi.Count(record => record.Kind == FirmamentV2PmiKind.HoleDiameter) + export.GeneratedSemanticPmi.OfType<Step242SemanticPmiHole>().Count();var inspection = Step242SemanticPmiInspector.Inspect(export.StepText);if (inspection.Success && inspection.DatumCount == expectedDatums && inspection.DimensionCount == expectedDiameters)return KernelResult<bool>.Success(true);@@ -514,6 +518,9 @@ public static partial class FirmamentBuildAndExportreturn KernelResult<FirmamentStepExportResult>.Failure(dfm.Diagnostics);}+ if (v2Parse.Document.Solids.Any(s => s.InlineStep?.SourceHashPin is not null))+ return ExportPinnedImportedRevision(v2Parse.Document);+if (TryExportV2StandaloneCubicLattice(v2Parse.Document) is { } latticeExport){return latticeExport;@@ -2193,6 +2200,9 @@ public static partial class FirmamentBuildAndExportprivate static KernelResult<FirmamentStepExportResult>? TryExportV2InlineStepReplacementBody(FirmamentV2Document document){+ if (document.Replacements is { Count: > 1 })+ return KernelResult<FirmamentStepExportResult>.Failure([new(KernelDiagnosticCode.ValidationFailed,KernelDiagnosticSeverity.Error,+ "firmament-imported-hole-count-unsupported: One imported hole revision per Model is admitted.","FirmamentV2.ImportedHoleRevision")]);if (document.Replacements is not { Count: 1 } replacements || document.Solids.Count != 1){return null;@@ -2206,6 +2216,7 @@ public static partial class FirmamentBuildAndExport}var stepText = solid.InlineStep.SourceText ?? File.ReadAllText(solid.InlineStep.NormalizedPath, Encoding.UTF8);+ if (replacement.Within is not null) return ExportImportedHoleRevision(document, solid, replacement);var import = Step242Importer.ImportBody(stepText);if (!import.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(import.Diagnostics);@@ -2282,14 +2293,8 @@ public static partial class FirmamentBuildAndExport}var semanticPmi = BuildV2SemanticPmi(document, [], solid.Name, body: import.Value);- foreach (var item in semanticPmi)- {- var required = item is Step242SemanticPmiDatum ? SurfaceGeometryKind.Plane : SurfaceGeometryKind.Cylinder;- if (item.GeometricFaceIds.Count == 0 || item.GeometricFaceIds.Any(id =>- !import.Value.TryGetFaceSurface(new Core.Topology.FaceId(id), out var surface) || surface?.Kind != required))- return KernelResult<FirmamentStepExportResult>.Failure([new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed,- KernelDiagnosticSeverity.Error, $"firmament-v2-imported-pmi-target-kind: '{item.FeatureId}' requires a resolved {required} face. The imported geometry is immutable; choose a compatible face.", "FirmamentV2.Pmi")]);- }+ var targetValidation = ValidateImportedPmiTargets(semanticPmi, import.Value);+ if (!targetValidation.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(targetValidation.Diagnostics);var export = Step242Exporter.ExportBody(import.Value, semanticPmi, new Step242ExportOptions{ProductName = solid.Name,@@ -2787,9 +2792,13 @@ public static partial class FirmamentBuildAndExport{var references = ImportedPmiFaceReferences(document, targetBinding, pmi.Target);if (references.Count > 0)- importedFaces[pmi.Name] = body.Bindings.FaceBindings- .Where(binding => binding.SourceStepEntityId is { } entity && references.Contains("#" + entity))- .Select(binding => binding.FaceId.Value).Distinct().Order().ToArray();+ // The admitted map includes source-to-successor correspondence. Fresh+ // replacement walls deliberately have no original STEP entity identity.+ importedFaces[pmi.Name] = references.Select(entity =>+ targetBinding.InlineStep.TopologyMap.TryResolveFaceEntity(entity, out var mapped)+ && mapped.StartsWith("face-", StringComparison.Ordinal)+ && int.TryParse(mapped.AsSpan(5), out var id) ? id : 0)+ .Where(id => body.Topology.Faces.Any(face => face.Id.Value == id)).Distinct().Order().ToArray();}if (pmi.Kind == FirmamentV2PmiKind.HoleDiameter && pmi.Value.HasValue){@@ -2840,6 +2849,19 @@ public static partial class FirmamentBuildAndExport}).ToArray();}+ private static KernelResult<bool> ValidateImportedPmiTargets(IReadOnlyList<Step242SemanticPmi> items, BrepBody body)+ {+ foreach (var item in items)+ {+ var required = item is Step242SemanticPmiDatum ? SurfaceGeometryKind.Plane : SurfaceGeometryKind.Cylinder;+ if (item.GeometricFaceIds.Count == 0 || item.GeometricFaceIds.Any(id =>+ !body.TryGetFaceSurface(new FaceId(id), out var surface) || surface?.Kind != required))+ return KernelResult<bool>.Failure([new(KernelDiagnosticCode.ValidationFailed,+ KernelDiagnosticSeverity.Error, $"firmament-v2-imported-pmi-target-kind: '{item.FeatureId}' requires a resolved {required} face. Choose a compatible admitted face.", "FirmamentV2.Pmi")]);+ }+ return KernelResult<bool>.Success(true);+ }+private static IReadOnlyList<string> ImportedPmiFaceReferences(FirmamentV2Document document, FirmamentV2SolidBinding solid, string target){var prefix = solid.Name + ".face(\"";diff --git a/Aetheris.Kernel.Firmament/FirmamentImportedHoleRevision.cs b/Aetheris.Kernel.Firmament/FirmamentImportedHoleRevision.csnew file mode 100644index 00000000..38cae2f9--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentImportedHoleRevision.cs@@ -0,0 +1,122 @@+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 FirmamentImportedHoleRevisionReport(string Feature, string SourceHash,+ string SourceHashKind, string? SourceByteHash,+ string Strategy, bool SourceSemanticsExcluded, double ImportToleranceMillimetres,+ IReadOnlyList<int> RetiredWallFaces, IReadOnlyList<int> WallFaces, int EntryFace, int ExitFace,+ double Diameter, double Depth, ThroughHoleEditBounds Within, int PreservedFaces, int PreservedEdges,+ IReadOnlyDictionary<int, int> FaceCorrespondence);++public static partial class FirmamentBuildAndExport+{+ private static KernelResult<FirmamentStepExportResult> ExportPinnedImportedRevision(FirmamentV2Document document)+ {+ var solid = document.Solids.First(s => s.InlineStep?.SourceHashPin is not null);+ if (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)+ 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")+ { SourceSpan = solid.SourceSpan is { } span ? new(span.Start, span.Length) : null }]);+ return ExportImportedHoleRevision(document, solid, document.Replacements[0]);+ }++ private static KernelResult<FirmamentStepExportResult> ExportImportedHoleRevision(FirmamentV2Document document,+ FirmamentV2SolidBinding solid, FirmamentV2ReplacementDecl replacement)+ {+ KernelResult<FirmamentStepExportResult> Failure(string message) => KernelResult<FirmamentStepExportResult>.Failure([+ new(KernelDiagnosticCode.ValidationFailed,KernelDiagnosticSeverity.Error,message,"FirmamentV2.ImportedHoleRevision")+ { SourceSpan=replacement.SourceSpan is {} span ? new(span.Start,span.Length) : null }]);+ var imported = solid.InlineStep!;+ if (imported.SourceHashPin is null || replacement.WorldCenter is null || replacement.Within is null)+ return Failure("firmament-imported-hole-binding-incomplete: A pinned source, Point3 center and within envelope are required.");+ // Source annotation migration is outside this first release. Requiring explicit+ // exclusion also covers vendor graphs unknown to the bounded PMI inspector.+ if (!imported.GeometryOnly)+ return Failure("firmament-imported-hole-source-semantics-unsupported: Imported annotations cannot yet be safely migrated. Use an explicitly authored geometryOnly: true import to exclude them, or retain the original model without this edit.");+ var tolerance = imported.ImportToleranceMillimetres ?? 1e-3;+ var body = imported.RuntimeBody;+ if (body is null) return Failure("firmament-imported-hole-import-unavailable: The admitted immutable imported body is missing.");+ if (body.ImportQualification?.GeometryStatus != ImportQualificationStatus.Qualified)+ return Failure("firmament-imported-hole-import-unqualified: Required imported trims are not qualified at importTolerance. Inspect the import diagnostics; the tolerance is not widened automatically.");+ var region = document.RecognizedRegions!.Single(r => r.BodyName == solid.Name && r.RegionName == replacement.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();+ var marker = replacement.PlacementTarget.IndexOf("\"", StringComparison.Ordinal);+ var end = replacement.PlacementTarget.LastIndexOf('"');+ var entry = marker >= 0 && end > marker ? Resolve(replacement.PlacementTarget[(marker + 1)..end]) : null;+ if (selected.Any(id => id is null) || entry is null) return Failure("firmament-imported-hole-selection-unresolved: Resolve every wall and the entry support in the pinned source.");+ var edit = BrepThroughHoleRevision.Execute(body, new(replacement.ReplacementFeatureName, selected.Select(id => id!.Value).ToArray(), entry.Value,+ replacement.WorldCenter.Value, replacement.Radius * 2, replacement.Within, tolerance));+ if (!edit.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(edit.Diagnostics.Select(d => d with+ {+ SourceSpan = 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)))+ 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);+ var mapped = imported.TopologyMap.FaceEntityToFaceId.ToDictionary(p => p.Key, p =>+ {+ var old = Resolve(p.Key)!.Value; return "face-" + revised.FaceCorrespondence[old].Value;+ });+ var updatedSolid = solid with { Primitive = imported with { TopologyMap = new(mapped, mapped.ToDictionary(p => p.Value, p => p.Key)), RuntimeBody = revised.Body } };+ var bound = document with { Solids = document.Solids.Select(s => s.Name == solid.Name ? updatedSolid : s).ToArray() };+ var pmi = BuildV2SemanticPmi(bound, [], solid.Name, body: revised.Body).ToList();+ var generatedHolePmi = new Step242SemanticPmiHole(solid.Name + "." + replacement.ReplacementFeatureName, revised.Diameter, revised.Depth, "Shaft", null, null)+ {+ Name = replacement.ReplacementFeatureName,+ GeometricFaceIds = revised.WallFaces.Select(id => id.Value).ToArray()+ };+ pmi.Add(generatedHolePmi);+ var targetAdmission = ValidateImportedPmiTargets(pmi, revised.Body);+ if (!targetAdmission.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(targetAdmission.Diagnostics);+ var exported = Step242Exporter.ExportBody(revised.Body, pmi, new Step242ExportOptions+ {+ ProductName = document.ModelName,+ ApplicationName = "Aetheris.Firmament.ImportedHoleRevision",+ DistanceAccuracyMillimetres = System.Math.Max(body.ImportQualification?.SourceDistanceAccuracyMillimetres ?? 0, tolerance),+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,+ ImportedRecoveryToleranceMillimetres = tolerance+ });+ if (!exported.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(exported.Diagnostics);+ var reimport = Step242Importer.ImportBody(exported.Value, new ImportPolicy(PcurveQualificationToleranceMillimetres: tolerance));+ if (!reimport.IsSuccess || reimport.Value.ImportQualification?.GeometryStatus != ImportQualificationStatus.Qualified)+ return Failure("firmament-imported-hole-roundtrip-unqualified: The successor failed qualified STEP roundtrip.");+ IReadOnlyList<KernelDiagnostic> warnings = imported.GeometryOnly ? [new(KernelDiagnosticCode.ValidationFailed,KernelDiagnosticSeverity.Warning,+ "firmament-inline-step-source-semantics-excluded: geometryOnly explicitly excludes the imported annotation layer. The original source file remains unchanged; replacement-hole PMI is generated from the authored feature.","FirmamentV2.InlineStep")+ {SourceSpan=solid.SourceSpan is {} span?new(span.Start,span.Length):null}] : [];+ return KernelResult<FirmamentStepExportResult>.Success(new(exported.Value, solid.Name, 0, "inline-step-revision", "through-hole-suppression-reinsertion",+ DatumInspection: pmi.OfType<Step242SemanticPmiDatum>().Select(d => new FirmamentPmiInspectionDatum(d.Label, "planar", d.Target)).ToArray(),+ DimensionInspection: pmi.OfType<Step242SemanticPmiHole>().Select(h => new FirmamentPmiInspectionDimension(+ "Diameter", h.FeatureId, null, h.Diameter, "imported-hole-revision-pmi", h.Name)).ToArray(),+ InlineStepMigration: InlineStepMigrationReportBuilder.Build(document, solid, true, true, "through-hole-suppression-reinsertion", true))+ {+ GeneratedSemanticPmi = [generatedHolePmi],+ DocumentName = document.ModelName,+ RuntimeBody = revised.Body,+ RuntimeBodySourceName = solid.Name,+ RuntimeAdmissionDocument = bound,+ ImportedHoleRevision = new(replacement.ReplacementFeatureName, imported.SourceHashPin, imported.TextHashPin ? "sha256-utf8-lf" : "sha256-bytes", imported.SourceByteHash, "ThroughHoleSuppressionReinsertion", imported.GeometryOnly, tolerance,+ revised.RetiredWallFaces.Select(id => id.Value).ToArray(), revised.WallFaces.Select(id => id.Value).ToArray(), revised.EntryFace.Value, revised.ExitFace.Value,+ revised.Diameter, revised.Depth, revised.Within, revised.PreservedFaces, revised.PreservedEdges, revised.FaceCorrespondence.ToDictionary(p => p.Key.Value, p => p.Value.Value))+ }, warnings);+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.csindex 541aab8f..830b117a 100644--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs@@ -38,6 +38,9 @@ public sealed record FirmamentStepExportResult(FirmamentThreadReport? Thread = null){public string? DocumentName { get; init; }+ public FirmamentImportedHoleRevisionReport? ImportedHoleRevision { 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; } = [];// In-process display can use the exact body that was exported to STEP.// It is intentionally absent from CLI/JSON artifact serialization.diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.csindex b63af9c7..3f1c9307 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs@@ -100,6 +100,13 @@ public sealed record FirmamentV2InlineStepRecord(string SourcePath, string Norma/// <summary>The admitted immutable input. Lowering must not reopen a changed file.</summary>[System.Text.Json.Serialization.JsonIgnore]public string? SourceText { get; init; }+ public string? SourceHashPin { get; init; }+ public bool TextHashPin { get; init; }+ public string? SourceByteHash { get; init; }+ public double? ImportToleranceMillimetres { get; init; }+ public bool GeometryOnly { get; init; }+ [System.Text.Json.Serialization.JsonIgnore]+ public Aetheris.Kernel.Core.Brep.BrepBody? RuntimeBody { get; init; }}public sealed record ImportedStepTopologyMap(IReadOnlyDictionary<string, string> FaceEntityToFaceId, IReadOnlyDictionary<string, string> FaceIdToFaceEntity){@@ -184,6 +191,9 @@ public sealed record FirmamentV2SemanticProposal(string ProposalKind, string Feapublic sealed record FirmamentV2ReplacementDecl(string ImportedBodyName, string RecognizedRegionName, string ReplacementKind, string ReplacementFeatureName, string PlacementTarget, FirmamentV2FaceLocalPoint2D Center, double Radius, string EndCondition, IReadOnlyList<double> HostSize, string Source){public string TargetSource => $"{ImportedBodyName}.region(\"{RecognizedRegionName}\")";+ public Aetheris.Kernel.Core.Math.Point3D? WorldCenter { get; init; }+ public Aetheris.Kernel.Core.Brep.Features.ThroughHoleEditBounds? Within { get; init; }+ public FirmamentV2SourceSpan? SourceSpan { get; init; }}public sealed record FirmamentV2ImportedStepFaceTarget(string BodySymbol, string EntityRef)diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ImportedEditingBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ImportedEditingBinding.csnew file mode 100644index 00000000..cd1bef18--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ImportedEditingBinding.cs@@ -0,0 +1,187 @@+using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++public static partial class FirmamentV2Parser+{+ private static FirmamentV2SolidBinding? BindImportedStep(DeclarationSyntax declaration, List<string> diagnostics,+ string? directory, IReadOnlyDictionary<string, string>? resources)+ {+ var fields = new FirmamentSyntaxFields(declaration, diagnostics);+ var geometryValue = fields.Take("GeometryOnly");+ var geometryOnly = false;+ if (geometryValue is not null && !bool.TryParse(FirmamentSyntaxWriter.Expression(geometryValue), out geometryOnly)) fields.Invalid("GeometryOnly");+ var path = StringValue(fields.Take("Path"));+ var bytePinExpression = fields.Take("Sha256");+ var textPinExpression = fields.Take("TextSha256");+ if (bytePinExpression is not null && textPinExpression is not null)+ diagnostics.Add("firmament-inline-step-source-pin-conflict: Choose sha256 for exact bytes or textSha256 for UTF-8 text with LF line endings, not both.");+ var pinExpression = bytePinExpression ?? textPinExpression;+ var textPin = bytePinExpression is null && textPinExpression is not null;+ var pin = StringValue(pinExpression);+ if (pinExpression is not null && (pin is null || pin.Length != 64 || pin.Any(c => !char.IsAsciiHexDigit(c)))) fields.Invalid(textPin ? "TextSha256" : "Sha256");+ var toleranceExpression = fields.Take("ImportTolerance");+ double? tolerance = null;+ if (toleranceExpression is not null)+ {+ if (FirmamentSyntaxValues.TryMeasure(toleranceExpression, "mm", out var value) && value > 0 && value <= .1) tolerance = value;+ else fields.Invalid("ImportTolerance");+ if (pin is null) diagnostics.Add("firmament-inline-step-source-pin-required: Explicit import tolerance requires a pinned source.");+ }+ if (geometryOnly && pin is null) diagnostics.Add("firmament-inline-step-source-pin-required: geometryOnly requires a pinned source.");+ fields.Complete();+ if (path is null || declaration.Name is null) { diagnostics.Add(InlineStepPathMissing); return null; }+ return LoadInlineStep(declaration.Name.Text, path, diagnostics, directory, resources, pin, tolerance, textPin) is { } binding+ ? binding with { Primitive = ((FirmamentV2InlineStepRecord)binding.Primitive) with { GeometryOnly = geometryOnly }, SourceSpan = declaration.Span, AuthoredFields = fields.AuthoredFields } : null;+ }++ private static IReadOnlyList<FirmamentV2RecognizedRegion> BindImportedRegions(IEnumerable<DeclarationSyntax> declarations,+ Dictionary<string, FirmamentV2SolidBinding> solids, List<string> diagnostics, Action<DeclarationSyntax, int> capture)+ {+ var result = new List<FirmamentV2RecognizedRegion>();+ foreach (var declaration in declarations.Where(d => d.Type.Name.Text == "Recognize"))+ {+ var diagnosticStart = diagnostics.Count;+ if (declaration.Name is null || !solids.TryGetValue(declaration.Name.Text, out var solid) || solid.InlineStep is null)+ { diagnostics.Add(UnknownRecognitionBody); capture(declaration, diagnosticStart); continue; }+ var regions = declaration.Body?.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Region").ToArray() ?? [];+ new FirmamentSyntaxFields(declaration, diagnostics).Complete(regions.ToHashSet<StatementSyntax>());+ capture(declaration, diagnosticStart);+ foreach (var region in regions)+ {+ diagnosticStart = diagnostics.Count;+ var fields = new FirmamentSyntaxFields(region, diagnostics);+ var kind = NormalizeRecognitionKind(fields.Reference("Kind") ?? "");+ var confidence = fields.Reference("Confidence", "medium")!.ToLowerInvariant();+ if (kind is not ("holeShaft" or "datumPlane")) diagnostics.Add(InvalidRecognitionKind);+ if (confidence is not ("low" or "medium" or "high" or "certain")) diagnostics.Add(InvalidRecognitionConfidence);+ var raw = fields.Take("StepFaceEntities");+ var friendly = fields.Take("Faces");+ var refs = new List<string>();+ if (raw is not null && friendly is not null) diagnostics.Add(UnknownRecognitionFace);+ else if ((raw ?? friendly) is SequenceSyntax { Kind: SequenceKind.List } list)+ {+ foreach (var argument in list.Items)+ {+ string? entity = null;+ if (raw is not null && StringValue(argument.Value) is { } id && solid.InlineStep.TopologyMap.TryResolveFaceEntity(id, out _)) entity = id;+ else if (friendly is not null && FirmamentSyntaxValues.TryMeasure(argument.Value, "", out var number)+ && number == (int)number && solid.InlineStep.TopologyMap.TryResolveSequentialFaceId((int)number, out var ordinal)) entity = ordinal;+ if (entity is null || argument.Name is not null) diagnostics.Add(UnknownRecognitionFace); else refs.Add(entity);+ }+ }+ if (refs.Count == 0 || refs.Distinct().Count() != refs.Count) diagnostics.Add(UnknownRecognitionFace);+ FirmamentV2RecognitionEvidence? evidence = null;+ if (fields.Take("Evidence") is { } value)+ {+ if (value is not ObjectSyntax obj) fields.Invalid("Evidence");+ else+ {+ var e = ImportedObject(obj, "Evidence", diagnostics);+ var family = e.Reference("SurfaceFamily");+ if (family is not null && family.ToLowerInvariant() is not ("cylindrical" or "planar")) diagnostics.Add(RecognitionEvidenceSurfaceFamilyUnknown);+ var radiusValue = e.Take("Radius"); double? radius = null;+ if (radiusValue is not null)+ { if (FirmamentSyntaxValues.TryMeasure(radiusValue, "mm", out var r) && r > 0) radius = r; else diagnostics.Add(RecognitionEvidenceRadiusInvalid); }+ var throughValue = e.Take("Through"); bool? through = null;+ if (throughValue is not null)+ { if (bool.TryParse(FirmamentSyntaxWriter.Expression(throughValue), out var b)) through = b; else e.Invalid("Through"); }+ var axis = e.Reference("Axis");+ var centerValue = e.Take("Center"); FirmamentV2FaceLocalPoint2D? center = null;+ if (centerValue is not null)+ { if (FirmamentSyntaxValues.Vector(centerValue, "mm", out var xy) && xy.Length == 2) center = new(xy[0], xy[1], "world-xy"); else e.Invalid("Center"); }+ var notes = e.Take("Notes");+ if (notes is not null && (notes is not SequenceSyntax { Kind: SequenceKind.List } notesList+ || notesList.Items.Any(item => item.Name is not null || StringValue(item.Value) is null))) e.Invalid("Notes");+ e.Complete();+ evidence = new(family is null ? [] : [family.ToLowerInvariant()], radius, axis, center, through);+ }+ }+ fields.Complete();+ if (region.Name is null) diagnostics.Add(CanonicalDeclarationUnrecognized);+ else if (result.Any(r => r.BodyName == solid.Name && r.RegionName == region.Name.Text)) diagnostics.Add(DuplicateRegion);+ else result.Add(new(solid.Name, region.Name.Text, kind, refs, confidence, evidence));+ capture(region, diagnosticStart);+ }+ }+ return result;+ }++ private static IReadOnlyList<FirmamentV2ReplacementDecl> BindImportedReplacements(IEnumerable<DeclarationSyntax> declarations,+ Dictionary<string, FirmamentV2SolidBinding> solids, IReadOnlyList<FirmamentV2RecognizedRegion> regions,+ List<string> diagnostics, string source, Action<DeclarationSyntax, int> capture)+ {+ var result = new List<FirmamentV2ReplacementDecl>();+ foreach (var declaration in declarations.Where(d => d.Type.Name.Text == "Replace"))+ {+ var diagnosticStart = 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; }+ var kind = declaration.ResultType is null ? "" : NormalizeRecognitionKind(FirmamentSyntaxWriter.Expression(declaration.ResultType));+ if (kind != "holeShaft") diagnostics.Add(ReplacementUnsupportedKind);+ if (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 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+ && call.Arguments[0].Name is null && call.Arguments[0].Default is null)+ {+ var argument = call.Arguments[0].Value;+ if (FirmamentSyntaxValues.TryMeasure(argument, "", out var id) && id == (int)id && solid.InlineStep.TopologyMap.TryResolveSequentialFaceId((int)id, out var entity)) faceEntity = entity;+ else if (StringValue(argument) is { } raw && solid.InlineStep.TopologyMap.TryResolveFaceEntity(raw, out _)) faceEntity = raw;+ }+ if (faceEntity is null) diagnostics.Add(ReplacementFaceUnresolved);+ var centerValue = fields.Take("Center");+ Point3D? world = null; FirmamentV2FaceLocalPoint2D center = new(0, 0, "");+ if (Point(centerValue) is { } p) { world = p; center = new(p.X, p.Y, "world-xy"); }+ else if (FirmamentSyntaxValues.Vector(centerValue, "mm", out var xy) && xy.Length == 2) center = new(xy[0], xy[1], "");+ else diagnostics.Add(HoleCenterMissing);+ var diameter = fields.Number("Diameter", "mm");+ if (!double.IsFinite(diameter) || diameter <= 0) diagnostics.Add(ReplacementRadiusInvalid);+ if (fields.Reference("End") is not ("ThroughAll" or "throughAll")) diagnostics.Add(ReplacementEndUnsupported);+ var hostValue = fields.Take("HostSize");+ var host = FirmamentSyntaxValues.Vector(hostValue, "mm", out var size) && size.Length == 3 && size.All(v => v > 0) ? size : [];+ ThroughHoleEditBounds? within = null;+ if (fields.Take("Within") is { } envelope)+ {+ if (envelope 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) within = new(min.Value, max.Value); else fields.Invalid("Within");+ }+ else fields.Invalid("Within");+ if (world is null) fields.Invalid("Center");+ if (solid.InlineStep.SourceHashPin is null) diagnostics.Add("firmament-inline-step-source-pin-required: A local revision requires sha256 or textSha256 on InlineStep.");+ if (hostValue is not null) diagnostics.Add("firmament-imported-hole-host-size-conflict: within edits the retained BRep; HostSize is not admitted in this operation.");+ }+ else if (host.Length != 3) diagnostics.Add(ReplacementVerificationFailed);+ fields.Complete();+ result.Add(new(solid.Name, target[1], kind, name, $"{solid.Name}.face(\"{faceEntity}\")", center, diameter / 2, "throughAll", host,+ source.Substring(declaration.Span.Start, declaration.Span.Length))+ { WorldCenter = world, Within = within, SourceSpan = declaration.Span });+ }+ finally { capture(declaration, diagnosticStart); }+ }+ 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)+ diagnostics.Add($"{CanonicalDeclarationUnknown}:{type}:header");+ return FirmamentSyntaxFields.Object(obj.Type is null ? obj with { Type = new ReferenceSyntax(new(type, obj.Span), obj.Span) } : obj, null, diagnostics);+ }+ private static string? StringValue(ExpressionSyntax? value) => value is LiteralSyntax { Kind: LiteralKind.String } literal+ ? System.Text.Json.JsonSerializer.Deserialize<string>(literal.Raw) : null;+ private static Point3D? Point(ExpressionSyntax? value) => value is CallSyntax { Target: ReferenceSyntax { Name.Text: "Point3" } }+ && FirmamentSyntaxValues.Vector(value, "mm", out var xyz) && xyz.Length == 3 ? new(xyz[0], xyz[1], xyz[2]) : null;+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.csindex d68c9011..db40fca9 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs@@ -152,7 +152,9 @@ public static partial class FirmamentV2Parser{var body = declaration.Body;if (body is null || declaration.Name is null) { diagnostics.Add(CanonicalPrimitiveMalformed); continue; }- var imported = ParseInlineStep(declaration.Name.Text, source.Substring(body.Span.Start + 1, body.Span.Length - 2), diagnostics, sourceDirectory, resources);+ var diagnosticStart = diagnostics.Count;+ var imported = BindImportedStep(declaration, diagnostics, sourceDirectory, resources);+ CaptureFieldDiagnostics(declaration, diagnosticStart);if (imported is not null && !solids.TryAdd(imported.Name, imported)) diagnostics.Add(DuplicateName);}if (solids.Count == 0) diagnostics.Add(MissingSolid);@@ -202,8 +204,8 @@ public static partial class FirmamentV2Parser{ SyntaxDiagnostics = [new(UniformStockFilletAdmission.Code, "fatal", stockError) { SourceSpan = operation.SourceSpan, Stage = "Capability" }] };}var bodyText = source.Substring(model.Body.Span.Start + 1, model.Body.Span.Length - 2);- var recognized = ParseCanonicalRecognizedRegions(bodyText, solids, diagnostics);- var replacements = ParseCanonicalReplacements(bodyText, solids, recognized, diagnostics);+ var recognized = BindImportedRegions(declarations, solids, diagnostics, CaptureFieldDiagnostics);+ var replacements = BindImportedReplacements(declarations, solids, recognized, diagnostics, source, 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);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csindex 09ec6437..be2e7116 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -274,9 +274,6 @@ public static partial class FirmamentV2Parser// binder so a misspelled family can never disappear from a Modify block.private static readonly Regex CanonicalPerforationHeaderRegex = new(@"\bPerforation\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);private static readonly Regex CanonicalThreadHeaderRegex = new(@"\bThread\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);- private static readonly Regex CanonicalRecognizeHeaderRegex = new(@"\bRecognize\s+(?<body>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);- private static readonly Regex CanonicalRegionHeaderRegex = new(@"\bRegion\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);- private static readonly Regex CanonicalReplaceHeaderRegex = new(@"\bReplace\s+(?<body>[A-Za-z_][A-Za-z0-9_]*)\.(?<region>[A-Za-z_][A-Za-z0-9_]*)\s+With\s+(?<kind>[A-Za-z_][A-Za-z0-9_]*(?:\s*<\s*[A-Za-z_][A-Za-z0-9_]*\s*>)?)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);public static FirmamentV2ParseResult Parse(string sourceText) => Parse(sourceText, null, null);@@ -710,18 +707,21 @@ public static partial class FirmamentV2Parser};// The geometry/source-map owner must receive authored call spans, never// offsets into the expanded text. Generated fields are not source edits.- document = document with { ModifyBlocks = document.ModifyBlocks?.Select(block => block with+ document = document with{- SemanticHoles = block.SemanticHoles.Select(hole =>+ ModifyBlocks = document.ModifyBlocks?.Select(block => block with{- var application = FirmamentV2FeatureExpansion.ApplicationFor(document, hole.Name);- return application is null ? hole : hole with+ SemanticHoles = block.SemanticHoles.Select(hole =>{- SourceSpan = application.InvocationOrigin is { LocationNote: null } origin ? origin.SourceSpan : null,- AuthoredFields = null- };+ var application = FirmamentV2FeatureExpansion.ApplicationFor(document, hole.Name);+ return application is null ? hole : hole with+ {+ SourceSpan = application.InvocationOrigin is { LocationNote: null } origin ? origin.SourceSpan : null,+ AuthoredFields = null+ };+ }).ToArray()}).ToArray()- }).ToArray() };+ };return result with { Document = document };}@@ -1084,7 +1084,12 @@ public static partial class FirmamentV2Parservar match = Regex.Match(body, "\\b(?:path|Path)\\s*:\\s*\\\"(?<path>[^\\\"]+)\\\"", RegexOptions.CultureInvariant);if (!match.Success) { diagnostics.Add(InlineStepPathMissing); return null; }- var sourcePath = match.Groups["path"].Value;+ return LoadInlineStep(name, match.Groups["path"].Value, diagnostics, sourceDirectory, resources);+ }++ private static FirmamentV2SolidBinding? LoadInlineStep(string name, string sourcePath, List<string> diagnostics,+ string? sourceDirectory, IReadOnlyDictionary<string, string>? resources, string? sourceHashPin = null, double? importTolerance = null, bool textHashPin = false)+ {if (Path.IsPathRooted(sourcePath)){diagnostics.Add(InlineStepPathInvalid);@@ -1093,6 +1098,7 @@ public static partial class FirmamentV2Parserstring normalizedPath;string stepText;+ byte[]? sourceBytes = null;if (resources is not null){// Explicit browser/project snapshots never fall through to the host filesystem.@@ -1105,16 +1111,37 @@ public static partial class FirmamentV2Parservar baseDirectory = string.IsNullOrWhiteSpace(sourceDirectory) ? Directory.GetCurrentDirectory() : sourceDirectory;normalizedPath = Path.GetFullPath(Path.Combine(baseDirectory!, sourcePath));if (!File.Exists(normalizedPath)) { diagnostics.Add(InlineStepFileMissing); return null; }- stepText = File.ReadAllText(normalizedPath, Encoding.UTF8);+ sourceBytes = File.ReadAllBytes(normalizedPath);+ using var reader = new StreamReader(new MemoryStream(sourceBytes), Encoding.UTF8, detectEncodingFromByteOrderMarks: true);+ stepText = reader.ReadToEnd();}- if (!IsAetherisCanonicalStep(stepText, out var evidence))+ var canonical = IsAetherisCanonicalStep(stepText, out var evidence);+ if (!canonical && sourceHashPin is null){diagnostics.Add(InlineStepRequiresCanonical);return null;}var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(stepText))).ToLowerInvariant();- return new FirmamentV2SolidBinding(name, "InlineStep", new FirmamentV2InlineStepRecord(sourcePath, normalizedPath, hash, true, evidence, BuildImportedStepTopologyMap(stepText)) { SourceText = stepText });+ var byteHash = sourceBytes is not null ? Convert.ToHexString(SHA256.HashData(sourceBytes)).ToLowerInvariant() : hash;+ var pinnedHash = textHashPin+ ? Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(stepText.Replace("\r\n", "\n", StringComparison.Ordinal).Replace('\r', '\n')))).ToLowerInvariant()+ : byteHash;+ if (sourceHashPin is not null && !string.Equals(sourceHashPin, pinnedHash, StringComparison.OrdinalIgnoreCase))+ { diagnostics.Add("firmament-inline-step-source-pin-mismatch: The STEP differs from the explicitly selected source pin; re-inspect the imported entities before updating the pin."); return null; }+ Aetheris.Kernel.Core.Brep.BrepBody? runtimeBody = null;+ if (sourceHashPin is not null)+ {+ var imported = Aetheris.Kernel.Core.Step242.Step242Importer.ImportBody(stepText,+ new Aetheris.Kernel.Core.Import.ImportPolicy(PcurveQualificationToleranceMillimetres: importTolerance ?? 1e-3));+ if (!imported.IsSuccess) { diagnostics.AddRange(imported.Diagnostics.Select(d => "firmament-inline-step-import-failed: " + d.Message)); return null; }+ runtimeBody = imported.Value;+ }+ var map = runtimeBody is null ? BuildImportedStepTopologyMap(stepText) : new ImportedStepTopologyMap(+ runtimeBody.Bindings.FaceBindings.Where(b => b.SourceStepEntityId is not null).ToDictionary(b => "#" + b.SourceStepEntityId, b => "face-" + b.FaceId.Value),+ runtimeBody.Bindings.FaceBindings.Where(b => b.SourceStepEntityId is not null).ToDictionary(b => "face-" + b.FaceId.Value, b => "#" + b.SourceStepEntityId));+ return new FirmamentV2SolidBinding(name, "InlineStep", new FirmamentV2InlineStepRecord(sourcePath, normalizedPath, hash, canonical, evidence, map)+ { SourceText = stepText, SourceHashPin = sourceHashPin, TextHashPin = textHashPin, SourceByteHash = byteHash, ImportToleranceMillimetres = importTolerance, RuntimeBody = runtimeBody });}private static ImportedStepTopologyMap BuildImportedStepTopologyMap(string stepText)@@ -1674,133 +1701,6 @@ public static partial class FirmamentV2Parserprivate static bool CanonicalBodyHasUnknownField(string body, IReadOnlyCollection<string> knownFields) =>ReadAuthoredFields(body, 0).Any(field => !knownFields.Contains(field.Name, StringComparer.Ordinal));- // Canonical semantic STEP declarations bind directly to the normalized V2 nodes- // used by the compatibility parser. FaceRefs deliberately remain STEP entities- // downstream; the public canonical surface accepts analysis-facing ordinals.- private static IReadOnlyList<FirmamentV2RecognizedRegion> ParseCanonicalRecognizedRegions(string source, Dictionary<string, FirmamentV2SolidBinding> solids, List<string> diagnostics)- {- var regions = new List<FirmamentV2RecognizedRegion>();- var seen = new HashSet<string>(StringComparer.Ordinal);- foreach (Match recognize in CanonicalRecognizeHeaderRegex.Matches(source))- {- var bodyName = recognize.Groups["body"].Value;- if (!solids.TryGetValue(bodyName, out var solid) || solid.InlineStep is null) { diagnostics.Add(UnknownRecognitionBody); continue; }- var open = source.IndexOf('{', recognize.Index); var close = FindMatchingBrace(source, open);- if (close < 0) { diagnostics.Add(CanonicalDeclarationUnrecognized); continue; }- var recognizeBody = source[(open + 1)..close];- foreach (Match region in CanonicalRegionHeaderRegex.Matches(recognizeBody))- {- var name = region.Groups["name"].Value;- if (!seen.Add($"{bodyName}.{name}")) { diagnostics.Add(DuplicateRegion); continue; }- var regionOpen = recognizeBody.IndexOf('{', region.Index); var regionClose = FindMatchingBrace(recognizeBody, regionOpen);- if (regionClose < 0) { diagnostics.Add(CanonicalDeclarationUnrecognized); continue; }- var regionBody = recognizeBody[(regionOpen + 1)..regionClose];- var kindMatch = Regex.Match(regionBody, @"\bKind\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*(?:\s*<\s*[A-Za-z_][A-Za-z0-9_]*\s*>)?)", RegexOptions.CultureInvariant);- var kind = kindMatch.Success ? NormalizeRecognitionKind(kindMatch.Groups["value"].Value) : string.Empty;- if (kind is not ("datumPlane" or "holeShaft")) { diagnostics.Add(InvalidRecognitionKind); continue; }- var confidenceMatch = Regex.Match(regionBody, @"\bConfidence\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);- var confidence = confidenceMatch.Success ? confidenceMatch.Groups["value"].Value.ToLowerInvariant() : "medium";- if (confidence is not ("low" or "medium" or "high" or "certain")) { diagnostics.Add(InvalidRecognitionConfidence); continue; }- var faces = ParseCanonicalFaceReferences(regionBody, solid.InlineStep.TopologyMap, diagnostics);- if (faces.Count == 0) continue;- var evidence = ParseCanonicalRecognitionEvidence(regionBody, diagnostics);- regions.Add(new FirmamentV2RecognizedRegion(bodyName, name, kind, faces, confidence, evidence));- }- }- return regions;- }-- private static IReadOnlyList<string> ParseCanonicalFaceReferences(string regionBody, ImportedStepTopologyMap topologyMap, List<string> diagnostics)- {- var faces = new List<string>();- var friendly = Regex.Match(regionBody, @"\bFaces\s*:\s*\[(?<faces>[^\]]*)\]", RegexOptions.CultureInvariant | RegexOptions.Singleline);- var raw = Regex.Match(regionBody, @"\bStepFaceEntities\s*:\s*\[(?<faces>[^\]]*)\]", RegexOptions.CultureInvariant | RegexOptions.Singleline);- if (friendly.Success && raw.Success) { diagnostics.Add(UnknownRecognitionFace); return []; }- if (friendly.Success)- {- foreach (var token in friendly.Groups["faces"].Value.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))- {- if (!int.TryParse(token, NumberStyles.None, CultureInfo.InvariantCulture, out var faceId) || faceId <= 0 || !topologyMap.TryResolveSequentialFaceId(faceId, out var entity)) { diagnostics.Add(UnknownRecognitionFace); return []; }- faces.Add(entity);- }- }- else if (raw.Success)- {- foreach (Match entity in Regex.Matches(raw.Groups["faces"].Value, "\\\"(?<entity>#[0-9]+)\\\"", RegexOptions.CultureInvariant))- {- var value = entity.Groups["entity"].Value;- if (!topologyMap.TryResolveFaceEntity(value, out _)) { diagnostics.Add(UnknownRecognitionFace); return []; }- faces.Add(value);- }- }- if (faces.Count == 0 || faces.Distinct(StringComparer.Ordinal).Count() != faces.Count) { diagnostics.Add(UnknownRecognitionFace); return []; }- return faces;- }-- private static FirmamentV2RecognitionEvidence? ParseCanonicalRecognitionEvidence(string regionBody, List<string> diagnostics)- {- var header = Regex.Match(regionBody, @"\bEvidence\s*:\?\s*\{", RegexOptions.CultureInvariant);- if (!header.Success) return null;- var open = regionBody.IndexOf('{', header.Index); var close = FindMatchingBrace(regionBody, open);- if (close < 0) { diagnostics.Add(CanonicalDeclarationUnrecognized); return null; }- var body = regionBody[(open + 1)..close];- var surface = Regex.Match(body, @"\bSurfaceFamily\s*:\s*(?<value>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);- var families = new List<string>();- if (surface.Success)- {- var family = surface.Groups["value"].Value.ToLowerInvariant();- if (family is not ("cylindrical" or "planar")) diagnostics.Add(RecognitionEvidenceSurfaceFamilyUnknown); else families.Add(family);- }- double? radius = null;- if (Regex.IsMatch(body, @"\bRadius\s*:", RegexOptions.CultureInvariant))- {- var match = Regex.Match(body, @"\bRadius\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);- if (!match.Success || !double.TryParse(match.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) || value <= 0d || !double.IsFinite(value)) diagnostics.Add(RecognitionEvidenceRadiusInvalid); else radius = value;- }- bool? through = null;- var throughMatch = Regex.Match(body, @"\bThrough\s*:\s*(?<value>true|false)\b", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);- if (throughMatch.Success) through = bool.Parse(throughMatch.Groups["value"].Value);- return new FirmamentV2RecognitionEvidence(families, radius, Through: through, Notes: []);- }-- private static IReadOnlyList<FirmamentV2ReplacementDecl> ParseCanonicalReplacements(string source, Dictionary<string, FirmamentV2SolidBinding> solids, IReadOnlyList<FirmamentV2RecognizedRegion> recognizedRegions, List<string> diagnostics)- {- var replacements = new List<FirmamentV2ReplacementDecl>();- foreach (Match replace in CanonicalReplaceHeaderRegex.Matches(source))- {- var bodyName = replace.Groups["body"].Value; var regionName = replace.Groups["region"].Value;- if (!solids.TryGetValue(bodyName, out var solid) || solid.InlineStep is null) { diagnostics.Add(UnknownReplacementBody); continue; }- var region = recognizedRegions.SingleOrDefault(candidate => candidate.BodyName == bodyName && candidate.RegionName == regionName);- if (region is null) { diagnostics.Add(UnknownReplacementRegion); continue; }- var kind = NormalizeRecognitionKind(replace.Groups["kind"].Value);- if (kind != "holeShaft") { diagnostics.Add(ReplacementUnsupportedKind); continue; }- if (region.Kind != kind) { diagnostics.Add(ReplacementKindMismatch); continue; }- var open = source.IndexOf('{', replace.Index); var close = FindMatchingBrace(source, open);- if (close < 0) { diagnostics.Add(CanonicalDeclarationUnrecognized); continue; }- var body = source[(open + 1)..close];- var face = Regex.Match(body, @"\bOn\s*:\s*(?<body>[A-Za-z_][A-Za-z0-9_]*)\.Face\(\s*(?<face>[0-9]+)\s*\)", RegexOptions.CultureInvariant);- if (!face.Success || face.Groups["body"].Value != bodyName || !int.TryParse(face.Groups["face"].Value, out var faceId) || !solid.InlineStep.TopologyMap.TryResolveSequentialFaceId(faceId, out var entity)) { diagnostics.Add(ReplacementFaceUnresolved); continue; }- var center = Regex.Match(body, @"\bCenter\s*:\s*Point2\(\s*(?<u>[-+0-9.eE]+)mm\s*,\s*(?<v>[-+0-9.eE]+)mm\s*\)", RegexOptions.CultureInvariant);- if (!center.Success || !double.TryParse(center.Groups["u"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var u) || !double.TryParse(center.Groups["v"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var v)) { diagnostics.Add(HoleCenterMissing); continue; }- var diameter = Regex.Match(body, @"\bDiameter\s*:\s*(?<value>[-+0-9.eE]+)mm\b", RegexOptions.CultureInvariant);- if (!diameter.Success || !double.TryParse(diameter.Groups["value"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var d) || d <= 0d || !double.IsFinite(d)) { diagnostics.Add(ReplacementRadiusInvalid); continue; }- if (!Regex.IsMatch(body, @"\bEnd\s*:\s*ThroughAll\b", RegexOptions.CultureInvariant)) { diagnostics.Add(ReplacementEndUnsupported); continue; }- var host = Regex.Match(body, @"\bHostSize\s*:\s*\[(?<values>[^\]]*)\]", RegexOptions.CultureInvariant);- var hostSize = host.Success ? ParseCanonicalLengthTriple(host.Groups["values"].Value) : null;- if (hostSize is null) { diagnostics.Add(ReplacementVerificationFailed); continue; }- replacements.Add(new FirmamentV2ReplacementDecl(bodyName, regionName, kind, replace.Groups["name"].Value, $"{bodyName}.face(\"{entity}\")", new FirmamentV2FaceLocalPoint2D(u, v, string.Empty), d / 2d, "throughAll", hostSize, replace.Value));- }- return replacements;- }-- private static IReadOnlyList<double>? ParseCanonicalLengthTriple(string raw)- {- var values = raw.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)- .Select(ParsePhase3Length)- .ToArray();- return values.Length == 3 && values.All(value => double.IsFinite(value) && value > 0d) ? values : null;- }-private static FirmamentV2ParseResult CanonicalFailure(List<string> diagnostics, string diagnostic){// A precise producer error already explains rejection. Do not append adiff --git a/Aetheris.Kernel.Firmament/FirmamentV2/InlineStepMigrationReport.cs b/Aetheris.Kernel.Firmament/FirmamentV2/InlineStepMigrationReport.csindex 0ba94782..2579fbf3 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/InlineStepMigrationReport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/InlineStepMigrationReport.cs@@ -86,7 +86,7 @@ public static class InlineStepMigrationReportBuildersolid.Name,inlineStep.SourcePath,inlineStep.ContentHash,- new InlineStepOriginalTopologyAccounting(originalFaceCount, 0, 0),+ new InlineStepOriginalTopologyAccounting(originalFaceCount, inlineStep.RuntimeBody?.Topology.Edges.Count() ?? 0, inlineStep.RuntimeBody?.Topology.Vertices.Count() ?? 0),new InlineStepRecognizedAccounting(regions.Length, uniqueRecognized.Count, duplicateCount, unresolvedCount, regions.Count(r => r.Evidence is not null), regions.Count(r => r.Proposal is not null), 0, regions.Count(r => r.Proposal is not null), assist.ReadyCount, assist.BlockedCount),new InlineStepReplacementAccounting(plannedCount, verifiedCount, emittedCount, failedCount, replacedFaces.Count),new InlineStepResidualAccounting(residualFaceCount, residualFaceCount),diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.csindex 0dfeea12..419ce6a8 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxParser.cs@@ -239,7 +239,7 @@ public static class FirmamentSyntaxParser}if (Pair("=", ">")) { at += 2; initializer = Expression(stopGreater: occurrence); }else if (Take("=")) initializer = Expression(stopGreater: occurrence);- if (type.Name.Text == "Replace" && Take("With"))+ if (type.Name.Text == "Replace" && (Take("With") || Take("with"))){result = Expression(allowObject: false);if (Current.Kind == SyntaxTokenKind.Identifier) initializer = new ReferenceSyntax(Identifier(), Previous.Span);diff --git a/docs/development/architecture/imported-hole-revisions.md b/docs/development/architecture/imported-hole-revisions.mdnew file mode 100644index 00000000..ca1105be--- /dev/null+++ b/docs/development/architecture/imported-hole-revisions.md@@ -0,0 +1,112 @@+# Bounded imported through-hole revisions++Implemented production contract for one isolated round Z-axis through-hole move.+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)+records qualification. Original experiments remain historical evidence.++## Ownership++The unified structural parser admits `InlineStep`, `Recognize`/`Region`, and+`Replace ... with Hole<Shaft>`. `FirmamentV2ImportedEditingBinding` consumes their+fields through the existing `FirmamentSyntaxFields` owner. Unknown fields and+statements reject. There is no new whole-document parser or source rewrite.++The loader reads one immutable byte snapshot and imports at the authored numerical+budget. Exactly one pin is required: `sha256` checks those same bytes; explicit+`textSha256` checks decoded UTF-8/LF text, changing line endings only. Browser+snapshots use their UTF-8 resource text as the byte representation. There is no+automatic fallback between modes; the report records the pin kind and input byte+hash. The LF text mode makes Git-normalized corpus files portable without rewriting+the original STEP. Raw `stepFaceEntities` and sequential `faces`+retain distinct meanings through the imported topology map.++Pinned imports select the bounded revision owner exclusively. They cannot fall+into the historical HostSize/Box reconstruction route or ignore additional Modify+operations. The current release admits one revision in a single-body Model.+Historical unpinned inputs retain their existing compatibility boundary; the old+rebuild route explicitly reports that residual surgery was not performed.++`FirmamentImportedHoleRevision` binds the selected walls and entry support, checks+recognized evidence, invokes Core, generates semantic diameter/depth PMI and+performs qualified STEP export/reimport. Validate executes the same build admission.+It retains the revised admission document and source-to-successor face map for+subsequent semantic projections. Source file bytes remain untouched.++## Geometric certificate and transaction++`BrepThroughHoleRevision` proves a single closed oriented manifold, qualified+trims, inward connected coaxial cylindrical walls, complete circular inner rims,+two distinct Z-normal planar supports and full same-depth coverage. The selected+set must equal the entire proved wall group. Axis/frame limitations reject rather+than project onto XY. Authored confidence never overrides geometric proof.++The destination is a world Point3 on the selected support. Diameter is unchanged;+ThroughAll resolves against that support pair, not global body bounds. The typed+`within` prism spans both supports and contains both complete old/new holes with+positive clearance. Every unrelated boundary face must be excluded using+conservative plane/cylinder/cone support bounds, finite line/circle/B-spline curve+hulls and the import uncertainty budget. Unsupported bounds reject. This can+refuse physically possible edits; it cannot choose a permissive fallback.++One atomic operation:++1. Prove source topology, recognition and stock exclusion.+2. Suppress the old walls and their two opening loops in a successor BRep.+3. Qualify the filled successor.+4. Materialize circles, seam lines, cylinders and vertices from the authored+ center/diameter, reusing the proved split-wall connectivity template.+5. Insert fresh topology identities into the retained residual body.+6. Qualify the result, export with enforced preflight and reimport as qualified.++Surviving face/edge/vertex identities, geometry objects, bindings and unrelated+loops/pcurves remain unchanged. Only the two support trim lists and shell wall+membership change among surviving topology. New walls clear original STEP entity+identity; retired-to-new correspondence records history separately. Shared geometry+outside the edit region rejects rather than overwriting another binding. Cached+Boolean/construction decomposition is cleared. Rejection never mutates the input.++There is one deterministic qualified strategy. No strategy framework or+JudgmentEngine dispatch is needed; future competing strategies would require+explicit admissibility and scoring in the existing JudgmentEngine.++## Accuracy and annotation boundaries++`importTolerance` is numerical admission accuracy, not manufacturing tolerance.+It defaults to .001 mm and must be explicitly pinned if overridden (positive,+finite, at most .1 mm). CTC-01's original curves differ from support surfaces by+about .0034 mm and its file declares .01 mm. The golden source explicitly uses+.01 mm; strict .001 mm still rejects. The cone-apex generator repair treats the+singular chart without modifying curves or surfaces. All 636 trims now qualify+at the explicit source budget. Export carries at least the original declared+accuracy and requested budget; it does not assert native precision.++This first release requires `geometryOnly: true` for pinned revisions, with a+source-located warning. It excludes the entire original annotation layer,+including vendor semantics unknown to the bounded inspector. The user expressly+approved this for CTC-01. Generic PMI passthrough/remapping needs a separate design.+New Hole PMI and additional supported authored Firmament PMI bind to revised+geometry; they do not represent inherited vendor requirements.++## Diagnostics and qualification++Syntax/binding errors retain AST spans. Kernel refusal uses+`firmament-imported-hole-revision-rejected` with the failing geometric explanation;+frontend source-pin, annotation, import qualification, evidence and roundtrip+failures have separate stable prefixes. Build JSON exposes `importedHoleRevision`,+including strategy, source pin, accuracy, annotation exclusion, retired/new face+IDs, preserved counts, envelope and face correspondence. The existing migration+report records residual surgery and actual imported topology counts.++Regression tests exercise real CTC-01 source, strict/explicit accuracy, unchanged+residual geometry and identities, semantic PMI associations, STEP roundtrip,+validate/build agreement and located refusals. The local tool delegates to Core+and checks three accepted moves and five refusals. Full solution qualification+remains mandatory because trim/export fixes affect interchange beyond this part.++Deferred: arbitrary frames, hole resizing, counterbores/countersinks, blind,+intersecting, threaded or blended holes, broader stock bounds, multiple edits per+Model, generic source PMI migration, and UI recognition/editing affordances.+Independent STEP producers beyond the admitted geometric family need their own+qualification; CTC-01 is a golden witness, not universal import certification.diff --git a/docs/public/firmament/imported-feature-recognition.md b/docs/public/firmament/imported-feature-recognition.mdindex 559b754b..a03cb794 100644--- a/docs/public/firmament/imported-feature-recognition.md+++ b/docs/public/firmament/imported-feature-recognition.md@@ -1,27 +1,130 @@-# Imported feature recognition: current limits--`Recognize` currently binds explicit face references to a named region. Authored-kind, confidence and optional evidence/proposals are not equivalent to automatic-feature recognition or a complete geometric verification. Resolving a face ID-proves which face was named; it does not prove that face is a hole wall.--A bounded `Replace ... With Hole<Shaft>` path exists for one canonical imported-body and one through-hole replacement. It rebuilds a Box plus a semantic shaft-hole using the existing materializer, then exports STEP. Its report explicitly-states `emissionStrategy: holeShaft-bounded-rebuild` and `residualSurgery: false`.-Residual face counts are migration accounting, not proof of preserved residual-geometry. This is not general hole resizing in an arbitrary imported part.--The current implementation checks for one matching-radius cylindrical support,-but does not establish complete correspondence between the recognized region,-the imported host and its declared HostSize. A planar region labeled as a hole-can currently pass this replacement path. An inconsistent HostSize can change the-rebuilt host. These are known admission gaps; do not use this prototype as evidence-that arbitrary imported geometry is preserved or that a replacement was verified.--The canonical positive witness is-`fixtures/Canonical/Integration/inline-step-recognize-replace.firmament`.-It is a constrained integration fixture, not a general modeling recipe. See the-[current audit](../../release/HOLE-RECOGNIZE-REPLACE-AUDIT-2026-10-20.md) for live-reproduction and the proposed bounded next step. No broader capability is implied-by proposal text or a replacement-ready metadata report.+# 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+whole part or reconstruct stock from a guessed HostSize.++The executable golden source is+[`ctc01-hole-move.firmament`](../../../fixtures/Regression/InlineStep/production/ctc01-hole-move.firmament).+It moves a Ø25 mm hole on NIST CTC-01 from (-160,45) to (-130,45) mm, through the+same Z=-50..0 mm material column.++```firmament+Model Revision {+ units: mm+ InlineStep Source {+ path: "ctc01.stp"+ textSha256: "341cea888fb316673ed683e59391c11b4f96cff2542d9387e135f06682dbd745"+ importTolerance: 0.01mm+ geometryOnly: true+ }+ Recognize Source {+ Region MountHole {+ kind: HoleShaft+ stepFaceEntities: ["#764", "#765"]+ evidence: { radius: 12.5mm; through: true }+ }+ }+ Replace Source.MountHole with Hole<Shaft> MountHole {+ on: Source.Face(98)+ center: Point3(-130mm, 45mm, 0mm)+ diameter: 25mm+ end: ThroughAll+ within: {+ min: Point3(-175mm, 30mm, -50mm)+ max: Point3(-115mm, 60mm, 0mm)+ }+ }+}+```++Put the unmodified CTC-01 STEP beside this example as `ctc01.stp`, or use the+repository fixture's relative path. Choose exactly one pin:++- `sha256` checks exact file bytes. Obtain it with PowerShell+ `Get-FileHash file.stp -Algorithm SHA256`.+- `textSha256` checks decoded source text encoded as UTF-8 with CRLF/CR converted+ to LF. No other whitespace or characters are changed. The fixture uses this+ explicit mode because Git stores the corpus as LF while older Windows worktrees+ can contain CRLF. Import still consumes the original text; no file is rewritten.++There is no fallback between these modes. Build JSON records the chosen hash kind+and actual input byte hash (UTF-8 resource hash for browser snapshots). Re-inspect+entity selectors before intentionally updating a pin after an upstream revision.++## What the fields mean++`stepFaceEntities` selects original STEP entity IDs. `faces` is the historical+sequential face-number alternative; the two number spaces are not interchangeable.+Select the complete cylindrical wall group, including legitimate split half-walls.+Recognition proves that the group has complete circular openings on two parallel+planar supports and is an inward through-void. An authored kind, confidence or+evidence label cannot override failed geometry checks.++`on` selects one of those proved supports. In the pinned CTC-01 source, sequential+face 98 is the plane at Z=0. `center` is a Point3 in imported-body coordinates,+which coincide with Model world coordinates in this single-body workflow. It+must lie on the selected plane. Imported UV origins are not inferred from a Point2.++`within` authorizes the local edit volume. Its Point3 min/max must contain both+holes with positive clearance and span the support planes. The compiler proves+that no other boundary can interfere. A conservative refusal means the current+planner cannot prove that envelope safe; it is not necessarily a physically+impossible edit. Support faces can extend outside the box: their support surfaces,+outer loops and all unrelated inner loops remain intact.++`importTolerance` is a numeric import/trim qualification budget in mm, **not a+manufacturing tolerance or a `tol` requirement**. It defaults to 0.001 mm. CTC-01's+original polynomial intersection curves deviate about 0.0034 mm from their analytic+supports and the file declares 0.01 mm source accuracy. The example explicitly+admits that accuracy; strict 0.001 mm admission rejects. Source geometry is not+fitted or moved to hide that discrepancy. Export carries declared distance+accuracy rather than claiming native precision for retained imported geometry.++## Imported annotations++`geometryOnly: true` explicitly excludes the source annotation layer. It does not+modify the original STEP. The compiler emits a warning and reports the choice.+This first bounded revision workflow requires explicit geometry-only import for+every pinned source. Generic source PMI migration is not admitted, including+annotation graphs that the bounded inspector does not recognize. Without explicit+exclusion the edit rejects; it never silently discards imported requirements.++The new named Hole produces semantic diameter/depth PMI associated with its new+wall faces. Additional supported Firmament PMI can be authored against the revised+bindings. Importing geometry only does not certify, translate or preserve the+vendor's original dimensions, datums or GD&T.++## Admission and reports++The current family is one isolated round Z-axis through-hole, unchanged diameter+and depth, between two parallel planar supports in one qualified closed oriented+body. Blind, intersecting, breakout, threaded, blended-entry, counterbore,+countersink and non-Z-axis revisions reject. Unknown fields and placements reject.+No arbitrary-body Boolean fallback or general healing is performed. Pinned imports+currently require this one bounded replacement; standalone pinned re-export and+additional Modify operations reject rather than bypassing revision admission.++The operation suppresses the old wall/openings, materializes fresh analytic hole+geometry and reinserts it with fresh topology IDs. Unchanged topology keeps its+identity; a face correspondence map records the revision. Cached construction+geometry is invalidated. Required trim, boundary and STEP roundtrip checks must+pass before success. `validate` and `build` use the same admission path.++CLI build JSON exposes `importedHoleRevision`, including strategy, import accuracy,+annotation exclusion, retired/new walls, preserved entity counts and correspondence.+`inlineStepMigration.residualSurgery` is true for this operation. Syntax diagnostics+and kernel admission failures retain source context.++## Historical compatibility++The older HostSize-based Box/shaft replacement prototype remains a compatibility+route, reporting `holeShaft-bounded-rebuild` and `residualSurgery: false`. It does+not provide this imported-body preservation contract. Its historical admission+limitations are recorded in the [audit](../../release/HOLE-RECOGNIZE-REPLACE-AUDIT-2026-10-20.md).+Use the pinned `within` form for the qualified production operation.++See the [production closeout](../../release/IMPORTED-HOLE-REVISION-PRODUCTION-2026-10-20.md)+for test evidence and the [design contract](../../development/architecture/imported-hole-revisions.md)+for ownership and limits.diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex 5c7f4abd..4934533d 100644--- a/docs/public/firmament/syntax.md+++ b/docs/public/firmament/syntax.md@@ -373,11 +373,18 @@ volume.mechanical compatibility syntax has the bounded lowercase`region sideHole on face(+X) { cut Cylinder { ... } }` operation inside`modify`; it is not a general native `Region` declaration. Prefer `Hole<Shaft>`-for new hole construction. `Recognize` names an explicitly referenced region of-imported geometry; its current binding checks are not automatic feature recognition-or a complete geometric proof of the authored kind. The existing hole `Replace`-lane is a bounded canonical box/through-hole rebuild, not general imported-body-editing. See [imported feature recognition](imported-feature-recognition.md).+for new hole construction. `Recognize` names a region of imported geometry. The+qualified imported-hole revision form pins the STEP with `sha256` (exact bytes)+or `textSha256` (explicit UTF-8/LF text normalization), proves a+complete through-hole and uses `Replace ... with Hole<Shaft>` plus explicit+`within` bounds to move it while retaining the residual BRep. The first family is+same-size, Z-axis and between parallel planar supports. This first pinned revision+workflow requires explicit `geometryOnly: true`; source annotation exclusion is+reported, not silently assumed.+`importTolerance` controls imported geometry qualification and is separate from a+manufacturing `tol`. The older HostSize rebuild does not have this preservation+contract. 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 admissionrules. See [Sheet Metal](sheet-metal.md) and [FEA](fea.md).diff --git a/docs/release/CTC01-HOLE-MOVE-EXPERIMENT-2026-10-20.md b/docs/release/CTC01-HOLE-MOVE-EXPERIMENT-2026-10-20.mdnew file mode 100644index 00000000..084ea05a--- /dev/null+++ b/docs/release/CTC01-HOLE-MOVE-EXPERIMENT-2026-10-20.md@@ -0,0 +1,159 @@+# CTC-01 local hole-move experiment++> Historical experiment evidence. The production implementation now lives in+> `BrepThroughHoleRevision` and the unified Firmament binder; the experiment tool+> delegates to that kernel owner. Commands/results below describe the original+> investigation, not the current release contract. See the+> [production closeout](IMPORTED-HOLE-REVISION-PRODUCTION-2026-10-20.md).++Result: **Success for the experimental study**. One real NIST CTC-01 through-hole+moves without reconstructing the whole part or invoking general Boolean surgery.+Production Recognize/Replace is unchanged and is not claimed qualified.++## Input and motivating edit++- Checkout investigated: `3aad55aa`.+- Source: `testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp`.+- Source SHA256: `85a5752da05f53c456ca3a9e038c90358e1d5a3141d1f0d6e5f0970f2356e821`.+- Imported BRep: one shell/body, 117 faces, 318 edges, 206 vertices; enclosed+ manifold topology, 56 planes, 57 cylinders and four cones.+- Selected void: sequential faces 1/2, original STEP #764/#765. Two connected+ cylindrical half-walls form a Ø25 mm hole at (-160,45), Z=-50..0 mm.+- Edit: move +30 mm in X to (-130,45), keeping diameter, depth and supports.+- Local stock envelope: min (-175,30,-50), max (-115,60,0) mm. Conservative+ bounds exclude all 113 unrelated boundary faces. The two planar supports and+ two hole walls are the only permitted intersecting faces.++Unlike the earlier canonical-box suppression witness, this is the original+complex NIST part. No full-part reverse engineering, mesh replacement or guessed+HostSize is used.++## Compared approaches++| Approach | Executed result | Conclusion |+| --- | --- | --- |+| Literal subtract-a-box, then union replacement stock | Actual `BrepBoolean.Subtract` rejects the first cut: bounded family only supports recognized axis-aligned Box hosts. Union was not attempted. | Not a viable existing route for this import; do not broaden generic Boolean scope for this task. |+| Direct proved-boundary relocation | Moves the two wall supports, six edge curves, four vertices and planar opening pcurves; topology IDs retained; STEP roundtrip succeeds. | Small, effective optimization for unchanged hole shape within a proved stock prism. |+| Suppress then insert fresh topology | Intermediate has 115 faces / 312 edges / 202 vertices. Inserts a translated proved hole patch with fresh topology IDs, returning to 117 / 318 / 206; STEP roundtrip succeeds. | Preferred semantic production contract: retire the old void and insert a named replacement while preserving residual identities. |++The two successful strategies have matching boundary geometry signatures. This+is not a performance benchmark. The second strategy currently copies a proved+hole patch; it does not yet call a new semantic Hole materializer or carry PMI.++## Evidence and checks++The retained experimental tool is `tools/Aetheris.ImportedHoleExperiment`.+Its CTC-specific `qualify` command checks eight cases:++| Case | Outcome |+| --- | --- |+| +30 mm X, disjoint old/new holes | Both strategies accepted experimentally; old axis becomes material, new axis becomes void in the certified local analytic stock model |+| +5 mm X, overlapping old/new holes | Both accepted; avoids assuming old/new voids must be disjoint |+| Zero displacement control | Both accepted, unchanged boundary geometry |+| +320 mm X crossing other features | Rejected before editing: conservative boundary conflicts |+| -250 mm X breakout | Rejected before editing: outer boundary conflict |+| Exterior cylindrical face 4 | Rejected: outward material orientation |+| Blind candidate face 13 | Rejected: not two complete planar inner openings |+| Ø35 mm lobe hole, seed 72, +5 mm X | Conservatively rejected against faces 3/26/28; not evidence that the physical edit is impossible |++For accepted cases, the tool verifies:++- Complete connected cylindrical wall groups, full circular rim coverage and+ matching axial extents; exterior rounds are not mistaken for holes.+- No source-body mutation on acceptance or refusal.+- Closed, oriented two-use edge incidence and valid topology references.+- Exact equality of unchanged supports/bindings, edge geometry/topology, vertex+ coordinates and retained pcurves in memory. Other opening loops on both support+ faces remain unchanged. 115 faces and 312 edges are retained by identity.+- Recognition of the relocated hole again after STEP reimport.+- Matching parameterization-independent analytic support and trimmed-boundary+ signatures through roundtrip, including an unmodified whole-body control.+ Numeric signature values are rounded to 1e-8; this is **not** a Hausdorff bound+ or a general exact-equivalence proof.+- Analytic local fill volume and cut volume both 24543.69260616987 mm³; net local+ volume change zero. This uses the proved local stock prism, not a mesh-volume+ assertion. Equal volume is not used alone as edit correctness evidence.++## Qualification limits found, not hidden++1. **Inherited trim gaps.** The original import is globally degraded: 32 coedges+ lack qualified pcurves. These same diagnostics persist through both edits and+ their roundtrips; no new pcurve diagnostic is introduced. Worst measured lift+ among existing bindings remains about 9.55e-9 mm. Missing bindings do not count+ as zero error or as a successful whole-body qualification.+2. **Native versus imported tolerance.** Native 1e-6 mm preflight reports 22+ pre-existing off-surface trim errors outside the selected region. The initial+ enforced export failed on these. The experiment explicitly uses a 0.001 mm+ imported-geometry budget, stricter than this source's declared 0.01 mm accuracy.+ That preflight passes without disabling checks. Both results are recorded;+ this does not repair pcurves or silently change production tolerances.+3. **Generic occupancy queries.** The existing global point-containment API+ returns Unknown at both axes for source, successor and roundtrip. The positive+ material witness instead follows from inward wall orientation, complete local+ rims, boundary exclusion over the stock prism and the actual circular opening+ after reimport. That local analytic reasoning is explicitly distinct from an+ independent whole-body point query.+4. **Semantics.** Experimental exports preserve the BRep geometry under the above+ checks, but do not migrate semantic PMI, product metadata or external bindings.+ They are not manufacturing-release artifacts. Fresh wall bindings retire their+ original STEP entity IDs; semantic feature correspondence still needs integration.+5. **Scope.** Only unchanged-radius/depth, Z-axis through-holes between parallel+ planar supports are implemented. No arbitrary healing, diameter changes,+ counterbore/countersink moves, blind/intersecting/threaded/blended hole edits,+ or general kernel Boolean extension is claimed.++## Reproduction and artifacts++See the [tool README](../../tools/Aetheris.ImportedHoleExperiment/README.md) for+commands. Generated output defaults to ignored `artifacts/local/`.++```powershell+dotnet build tools/Aetheris.ImportedHoleExperiment -c Release -m:1 -nr:false -p:UseSharedCompilation=false+dotnet tools/Aetheris.ImportedHoleExperiment/bin/Release/net10.0/Aetheris.ImportedHoleExperiment.dll testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp qualify artifacts/local/ctc01-hole-move/qualification+```++Local evidence includes `qualification/cases.json`, `control.json`,+`literal-box-cut.json`, each case's recognition/report JSON and successful+`direct.step` / `replace.step` artifacts. `comparison.png` compares compiler+wireframes of the original and moved BRep with the same world-space detail crop.++## Production decision++Use **local stock-region proof plus an atomic semantic replacement**. Keep the+existing Recognize/Region/Replace vocabulary, remove HostSize reconstruction from+this path, and make the allowed envelope explicit. Direct relocation can be a+qualified optimization; it cannot bypass the same proof or semantic contract.++The [production syntax proposal](../development/architecture/imported-hole-revisions.md)+defines typed fields, source pinning, world-space placement, same-size admission,+identity/provenance, diagnostics and validate/build agreement. It is explicitly+not parser-backed yet. InlineStep's current canonical-header restriction also+needs real import-capability admission, rather than a header workaround.++The concrete production prerequisites are now isolated: qualified residual import+handling (notably CTC's 32 missing trims), semantic Hole insertion, and association+migration. These belong to their existing owners; no new document parser or+general Boolean surgery is needed to continue this bounded operation.++## Repository qualification++The tool builds with zero warnings/errors and its eight-case qualification passes.+The solution Release build passes with 34 warnings and zero errors. Required lanes:++```powershell+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build --filter 'Category!=SlowCorpus' -m:1 -nr:false -- RunConfiguration.MaxCpuCount=1+dotnet test Aetheris.slnx -c Release --no-build -m:1 -nr:false -- RunConfiguration.MaxCpuCount=1+```++- Fast lane: 1087 passed, zero failed/skipped.+- Full solution: 5808 passed across 20 projects, zero failed/skipped, including+ SlowCorpus and the EditableV8 tests.+- A dedicated source-quality pass removed duplicate validation and an unused+ parameter, checked conservative oblique-axis bounds, enforced comparison results+ rather than merely reporting them, and checked untouched support-face loops.+- `git diff --check` passes. Tool-only whitespace formatting was applied.+- No dotnet/testhost/MSBuild/VBCSCompiler hosts remained after qualification.++Logs are retained under ignored `artifacts/local/ctc01-hole-move/`. Only the+isolated experimental tool and documentation change; production frontend/kernel+implementations remain unchanged. No baseline fixtures or snapshots were edited.diff --git a/docs/release/IMPORTED-HOLE-REVISION-PRODUCTION-2026-10-20.md b/docs/release/IMPORTED-HOLE-REVISION-PRODUCTION-2026-10-20.mdnew file mode 100644index 00000000..a18b9104--- /dev/null+++ b/docs/release/IMPORTED-HOLE-REVISION-PRODUCTION-2026-10-20.md@@ -0,0 +1,198 @@+# Imported through-hole revision: bounded production closeout++Outcome: **Success for the bounded geometry-only through-hole move contract**.+The original NIST CTC-01 source now builds through unified Firmament admission,+retains its residual BRep, and exports a moved semantic Hole with qualified STEP+roundtrip. This is feature qualification, not approval of CTC-01 for manufacture.+Original vendor PMI is expressly excluded with the user's approval; its safe+migration requires a separate design.++## Motivating witness++Source: `testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp`.+Working-source byte SHA256: `85a5752da05f53c456ca3a9e038c90358e1d5a3141d1f0d6e5f0970f2356e821`.+Repository LF / explicit textSha256: `341cea888fb316673ed683e59391c11b4f96cff2542d9387e135f06682dbd745`.++The [golden source](../../fixtures/Regression/InlineStep/production/ctc01-hole-move.firmament)+selects original STEP walls #764/#765 (sequential faces 1/2), proves their isolated+round through-hole, and moves its center from (-160,45,0) to (-130,45,0) mm.+Diameter remains 25 mm and depth 50 mm between Z=-50 and Z=0. Entry is sequential+face 98; exit is face 3. The authored envelope is min(-175,30,-50), max(-115,60,0) mm.++| Evidence | Result |+| --- | --- |+| `validate` | valid, validationLevel Built, parserRoute UnifiedMechanical |+| Normal `build` | Ctc01Revision; ThroughHoleSuppressionReinsertion |+| Source/successor topology | 117 faces, 318 edges, 206 vertices |+| Surviving identities/geometry | 115 faces, 312 edges; surviving vertices, trims and bindings unchanged |+| Retired/new wall IDs | 1/2 retired; 118/119 created |+| Unrelated boundary exclusion | 113 faces excluded from the stock envelope |+| STEP reimport | Qualified; 636 pcurves, zero missing |+| Measured maximum lift discrepancy | about 0.00335475 mm, under explicit 0.01 mm source budget |+| New semantic PMI | diameter 25 mm, depth 50 mm, associated to both replacement walls |+| Original STEP | bytes unchanged; source PMI excluded explicitly |++The comparison uses actual CLI wireframe projections of the original source and+compiled successor. Its outline is preserved; only the selected local hole moves.+The image and detailed diagnostics remain in ignored+`artifacts/local/imported-hole-production/` and are reproducible below.++## Root causes and repairs++The previous HostSize replacement reconstructed a Box instead of preserving the+imported residual body. That compatibility route remains clearly identified as+`residualSurgery: false`. Pinned revisions now have an exclusive bounded owner;+they cannot select that rebuild or silently ignore additional Modify operations.+The new Core operation proves constant stock, validates intermediate suppression,+materializes analytic hole geometry from authored dimensions, and reinserts it+with fresh topology identities. Input data is immutable throughout refusal/success.++Modern InlineStep/Recognize/Region/Replace fields now bind through the existing+unified AST and `FirmamentSyntaxFields`. Obsolete modern recognition/replacement+regex readers were removed. PascalCase compatibility fields and historical `With`+remain admitted; new examples use camelCase and lowercase `with`. Unknown fields,+malformed evidence and wrong object/header types reject with source locations.++The loader hashes the same immutable input it decodes/imports. A stale pin rejects+before using entity selectors. Raw `sha256` remains byte-exact. The portability+audit found that the current worktree is CRLF while Git stores this corpus as LF.+The golden fixture therefore uses explicit `textSha256`: decoded text encoded as+UTF-8, with CRLF/CR changed to LF and no other normalization. Both the pin kind and+actual input byte hash are reported; there is no implicit hash fallback and the+original STEP is not rewritten. Tests cover LF and CRLF resource snapshots, raw+byte pinning and conflicting modes. Browser resources use their UTF-8 snapshot+text, with no host-filesystem fallback.++CTC's 32 original missing pcurves had two causes. Four straight cone generators+encountered a singular U coordinate at their exact apex; recovery now uses the+one-sided interior angle and validates its surface lift. UV closure ignores the+undefined angle only at the exact apex, while keeping 3D endpoint checks.+The other 28 original polynomial curves actually depart from their supports by+about .0034 mm. They cannot satisfy .001 mm without changing source geometry.+The fixture therefore authors `importTolerance: 0.01mm`, matching the source's+own declared accuracy. Strict .001 mm still rejects. No curve/surface is refitted,+no preflight is disabled, and default import/recovery tolerances remain unchanged.+STEP export carries declared distance accuracy instead of claiming native precision.++Source annotations require `geometryOnly: true` in this first pinned revision+family, with a structured, source-located warning. This intentionally covers+vendor graphs unknown to the bounded PMI inspector. Normal unpinned compatibility+imports keep their existing boundary. No imported annotation passthrough is claimed.++The new Hole projects diameter/depth PMI on its fresh walls. Additional authored+PMI resolves through the admitted source-to-successor topology map rather than+stale STEP provenance on retired walls. Shared imported-PMI target validation+rejects missing/wrong-kind targets. Explicit lowerer-owned generated-PMI receipts+let the existing final parity check verify authored and generated records together,+including builds with no authored Pmi block. The regression caught and closed both+the count mismatch and the otherwise unassociated explicit dimension.++## Public contract and diagnostics++See [authoring](../public/firmament/imported-feature-recognition.md),+[syntax](../public/firmament/syntax.md), and+[ownership](../development/architecture/imported-hole-revisions.md).+`importTolerance` is numerical qualification accuracy, not a manufacturing `tol`.++Admission requires one qualified closed oriented body, a complete inward coaxial+wall group, two circular inner rims, two parallel planar supports, unchanged+size/depth, a Point3 on the selected support and a clear typed `within` prism.+Conservative bounds include the numerical uncertainty budget. Unknown bounding+families or possible intersections fail; they do not invoke arbitrary Booleans.++The shared validate/build path retains code, severity, message and AST location.+Important code prefixes include `firmament-inline-step-source-pin-mismatch`,+`firmament-inline-step-revision-required`,+`firmament-imported-hole-source-semantics-unsupported`,+`firmament-imported-hole-import-unqualified`,+`firmament-imported-hole-evidence-mismatch`,+`firmament-imported-hole-revision-rejected`, and+`firmament-imported-hole-roundtrip-unqualified`.+`firmament-inline-step-source-semantics-excluded` is a warning, not a waiver.++Build JSON exposes `importedHoleRevision`: strategy, source pin and hash kind, actual byte hash, exclusion choice,+accuracy, envelope, retired/new walls, support faces, dimensions, retained counts+and face correspondence. The existing migration report now includes actual+imported topology counts when the admitted runtime body is available. The summary+names the enclosing Model and counts the imported revision as one feature.++## Qualification++| Closing gate | Evidence |+| --- | --- |+| Release solution build | Passed, zero errors |+| Core fast lane | 1,087 passed |+| Complete solution lane | 5,838 passed across 20 test assemblies; zero failed/skipped tests |+| Focused imported frontend/compatibility | 77 passed (23 new, 54 existing) |+| Focused Core revision cases | 7 passed |+| Production kernel harness | 8/8 expected outcomes |+| Real CLI golden validate/build/analyze | Passed; one feature, qualified successor, semantic size/depth PMI |+| Real CLI strict .001 mm validate/build | Both rejected; no STEP emitted |+| Source integrity | Working byte hash remains unchanged; LF/CRLF text-pin and strict byte-pin tests pass |+| Whitespace/content checks | git diff --check and public documentation link qualification passed |++Existing nullable-analysis and WASM SQLite-varargs build warnings remain; this+feature does not claim to repair those unrelated warnings. FrictionLab's test+project currently discovers no tests; the 20 assemblies above are those with+executed tests. Existing V8 and other solution regression projects passed.++Raw evidence is under `artifacts/local/imported-hole-production/`:+`closing-solution-build.log`, `closing-fast-tests.log`, `closing-full-tests.log`,+`pin-focused-tests.log`, `closing-tool-tests.log`, `kernel-cases/cases.json`,+`validate-final.json`, `build.json`, `analyze.json`, `strict-validate.json`,+`strict-build.json`, `qualification-summary.json`, `ctc01-moved.step`,+`before.svg`, `after.svg`, and `comparison.png`. The source file is unchanged.+The intermediate doc-link failure was corrected by completing the linked closeout+before the closing full run; it is not waived.++Focused tests cover real source geometry, strict/explicit accuracy, 1025-sample+trim checks, unchanged source and residual identities/geometry/pcurves, fresh wall+IDs, semantic PMI associations, explicit PMI remapping, qualified STEP roundtrip,+validate/build agreement and source-located failures. All 54 pre-existing InlineStep+cases remain part of the focused compatibility lane.++The fixture harness now consumes the production Core owner rather than retaining+another edit engine. Its eight cases are: three accepted (30 mm move, overlapping+5 mm move and no-op), five rejected (collision, breakout, non-hole, blind and lobe).+Every accepted case must roundtrip as qualified; every case checks immutable input.+Original strategy-comparison reports remain historical investigation evidence.++No new parser route, global source rewrite, diagnostic fatality allowlist or+Boolean framework was introduced. There is one deterministic qualified surgery+strategy. The source pin, annotation policy and import tolerance cannot be bypassed+by standalone pinned re-export. The code-quality pass also checked original-source+provenance, map inverses, shared geometry, stale construction caches and generated+PMI accounting. Full interchange qualification is required because the apex and+export accuracy fixes are shared Core behavior.++### Reproduce++From the repository root in PowerShell:++```powershell+dotnet build Aetheris.slnx -c Release -m:1 -nr:false -p:UseSharedCompilation=false+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build --filter "Category!=SlowCorpus" -m:1 -nr:false -- RunConfiguration.MaxCpuCount=1+dotnet test Aetheris.slnx -c Release --no-build -m:1 -nr:false -- RunConfiguration.MaxCpuCount=1++dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll validate fixtures/Regression/InlineStep/production/ctc01-hole-move.firmament --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll build fixtures/Regression/InlineStep/production/ctc01-hole-move.firmament --output artifacts/local/imported-hole-production/ctc01-moved.step --json+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll analyze artifacts/local/imported-hole-production/ctc01-moved.step --json++dotnet build tools/Aetheris.ImportedHoleExperiment -c Release -m:1 -nr:false -p:UseSharedCompilation=false+dotnet tools/Aetheris.ImportedHoleExperiment/bin/Release/net10.0/Aetheris.ImportedHoleExperiment.dll testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp qualify artifacts/local/imported-hole-production/kernel-cases+```++The harness README documents inventory, single moves and explicit import budgets.+The CLI `wireframe` command produces the before/after SVGs for visual inspection.++## Remaining limits++This release does not admit non-Z frames, resizing, blind holes, breakouts,+intersections, threads, blended entries, counterbores/countersinks or multiple+revisions in one Model. Source PMI migration and a recognition/editing UI need+separate designs. Conservative whole-support bounds may reject safe moves in+other shapes. CTC is a real complex golden witness, not a claim that every STEP+producer or arbitrary local surgery is supported.++The legacy HostSize prototype is not upgraded into this preservation contract.+Use the pinned `within` form for the qualified imported-body operation.diff --git a/docs/release/IMPORTED-HOLE-SUPPRESSION-EXPERIMENT-2026-10-20.md b/docs/release/IMPORTED-HOLE-SUPPRESSION-EXPERIMENT-2026-10-20.mdnew file mode 100644index 00000000..4a1c4d6b--- /dev/null+++ b/docs/release/IMPORTED-HOLE-SUPPRESSION-EXPERIMENT-2026-10-20.md@@ -0,0 +1,136 @@+# Imported through-hole suppression: feasibility experiment++> Historical experiment evidence. The production implementation now lives in+> `BrepThroughHoleRevision` and the unified Firmament binder; the experiment tool+> delegates to that kernel owner. Commands/results below describe the original+> investigation, not the current release contract. See the+> [production closeout](IMPORTED-HOLE-REVISION-PRODUCTION-2026-10-20.md).++Status: **Meaningful progression**. The basic topology suppression operation+works on two valid imported witnesses. This is an isolated experiment, not a+production Recognize/Replace implementation or a qualified hole-move feature.++Investigated against checkout `3aad55aa`. The local probe references the existing+Release Kernel.Core assembly. No production kernel, parser or UI code changed.++## What was executed++The probe imports STEP, takes an explicitly selected cylindrical wall face, finds+its two adjoining complete inner loops on planar support faces, and constructs a+successor topology that omits the wall and those openings. It retains surviving+entity IDs, surface/curve objects, bindings, pcurves and vertex points. It clears+cached construction decomposition rather than retaining stale Boolean authority.++This does not recreate the imported body from HostSize or reconstruct a Box.+The input is unmodified. Only two support-face loop lists and shell membership+change among surviving topology; unrelated face loops are checked unchanged.++The checks cover graph validation, export preflight, required pcurves, closed and+oriented boundary incidence, STEP export/reimport, surviving geometry bindings,+and unchanged input topology. These are necessary checks, not a complete+self-intersection, material-occupancy or feature-recognition proof.++| Imported witness | Result | Preservation evidence |+| --- | --- | --- |+| Fresh CLI build of FrontendX4 reference `c03-face-reference-spellings.firmament` | 10 faces to 9; four cylindrical holes to three | Other holes, surviving supports/edges and unrelated loops retained; valid source and successor preflight/pcurves; closed oriented STEP roundtrip |+| Fresh CLI build of Composite `combined-hole-edgefinish-x1.firmament` | 12 faces to 11; two cylindrical holes to one | Outer chamfer and remaining hole retained with the same bindings; valid source and successor preflight/pcurves; closed oriented STEP roundtrip |+| Original canonical-through-hole.step | Suppression produces a valid six-face body, but **excluded as a valid-input success** | Input fails preflight and pcurves, with disconnected coedges and an unclosed loop; input boundary is not closed/orientation-consistent |+| Fresh CLI build of FrontendX4 chimera.baseline.firmament, selected face 15 | Rejected before editing | Selected wall alone is not bounded by two complete planar opening loops; complete connected wall-region tracing is missing |+| Planar face selected in the four-hole witness | Rejected before editing | Cylindrical wall required |++The numerical trimmed-face volume estimate is not used as preservation evidence.+For the four-hole input and three-hole successor it even decreases on suppression+(7818.2004 to 7813.6503 mm³), with reported bounds about 1772 and 1725 mm³.+Those display-derived estimates cannot qualify the expected positive fill-volume+delta. A production gate needs independent analytic section/material evidence.++## Reproduction and retained local evidence++Probe project/source and JSON/STEP results are retained under ignored+`artifacts/local/hole-suppression-experiment/`. In PowerShell from the repo root:++```powershell+dotnet build artifacts/local/hole-suppression-experiment/Probe.csproj -c Release -m:1 -nr:false -p:UseSharedCompilation=false+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll build fixtures/Regression/FrontendX4/cases/reference/c03-face-reference-spellings.firmament --output artifacts/local/hole-suppression-experiment/four-holes.step --json+dotnet artifacts/local/hole-suppression-experiment/bin/Release/net10.0/Probe.dll artifacts/local/hole-suppression-experiment/four-holes.step 7 artifacts/local/hole-suppression-experiment/three-holes.step+dotnet Aetheris.CLI/bin/Release/net10.0/aetheris.dll build fixtures/Regression/Composite/combined-hole-edgefinish-x1.firmament --output artifacts/local/hole-suppression-experiment/chamfered-two-holes.step --json+dotnet artifacts/local/hole-suppression-experiment/bin/Release/net10.0/Probe.dll artifacts/local/hole-suppression-experiment/chamfered-two-holes.step 11 artifacts/local/hole-suppression-experiment/chamfered-one-hole.step+```++This local experimental source is not a distributed tool. Its failed admissions+throw exceptions; it has no public diagnostic contract. Production work must move+the admitted algorithm into the owning topology-edit seam with structured errors+and permanent regression tests. The probe built with zero warnings/errors. No+full-solution regression qualification is claimed for this experiment. No .NET,+testhost, MSBuild or VBCSCompiler process remained after the run.++## Proposed production boundary++Start with isolated round through-holes connecting two parallel planar supports+in one valid closed, oriented manifold body. The surrounding body need not be a+Box. Require actual circular rim evidence, coaxial cylindrical wall coverage,+inward material orientation, and a fully traced connected void region. A cylinder+is not by itself a hole: it could be an outside boss or a partial cut.++Initially reject intersecting holes, breakouts, threads, blended entries, blind+holes, ambiguous imports, and unsupported surfaces. Handle split cylindrical+walls only after grouping connected, geometrically equivalent wall patches and+proving their complete external rims. The Chimera refusal is a concrete grouping+gap, not evidence that the part is inherently uneditable.++Use the existing Recognize/Replace authoring direction, with an internal atomic+transaction:++1. Recognize and prove the void against a particular imported body revision.+2. Plan a local face/loop rewrite and its explicit correspondence/deletions.+3. Suppress the old hole while retaining the actual residual BRep.+4. Prove the entire destination cylinder lies in the admitted material column,+ clears other features and stays within the authorized edit envelope.+5. Insert new semantic hole topology into that retained body.+6. Validate and export/reimport the successor, or discard the whole transaction.++The next unimplemented editing seam is **inserting a new hole into the retained+imported topology**, including destination clearance, circular trims, wall seams,+orientation and pcurves. The existing Box-based replacement materializer does not+provide that preservation contract. First qualify suppression plus reinsertion+at the same location as a control, then a real move. Verify old-axis material,+new-axis void, analytic volume change and unaffected topology independently.+Equal volume alone cannot prove a correct move.++## Region's role++Region is the right ownership abstraction, but declaring one does not itself+prove locality. Bind a proved region to its wall faces, opening loops, support+faces, body revision and permitted geometric envelope. Compare the actual edit+against that write contract. Global reads for collision checks remain necessary.++Support faces may span the whole part. Removing one inner loop changes that+face's trim list while retaining its support surface, outer loop and every other+hole. Locality therefore applies to the edited boundary and material envelope,+not a rule that every touched face must fit inside a small box.++Keep unchanged identities and PMI associations. Mark deleted topology as retired,+create fresh semantic identity for the new hole, and retain replacement history.+Report affected associations explicitly; do not silently map them to a nearby face.++## Counterbore and countersink follow-ons++Both are plausible extensions of the same void-region operation. A counterbore+adds a larger coaxial cylindrical wall and annular shoulder; a countersink adds+a coaxial conical mouth. Suppression removes the complete proved void boundary+and its two external opening loops. Recognition must prove connectivity,+material side, radii, depth ordering and cone/shoulder relations.++The existing Boolean hole-family recognizer uses authored Box-root construction+history; it is not imported STEP recognition. Its family definitions may be+reused, but cannot replace topology evidence. Neither compound family, automatic+discovery, destination insertion, PMI remapping nor vendor STEP qualification was+implemented or demonstrated in this experiment.++## Recommendation++Proceed with bounded imported-hole defeaturing and semantic reinsertion. The+suppression primitive is experimentally viable without general surface healing.+The substantial work is trustworthy recognition, destination material proof and+transactional topology insertion. Keep those gates explicit instead of growing+the old HostSize-based reconstruction path into an apparent general editor.diff --git a/fixtures/Regression/InlineStep/production/ctc01-hole-move.firmament b/fixtures/Regression/InlineStep/production/ctc01-hole-move.firmamentnew file mode 100644index 00000000..d45c6c8d--- /dev/null+++ b/fixtures/Regression/InlineStep/production/ctc01-hole-move.firmament@@ -0,0 +1,28 @@+// Explicit geometry-only revision: preserve the source BRep, exclude vendor PMI.+// Revisions of imported annotations are not admitted by this bounded operation.+Model Ctc01Revision {+ units: mm+ InlineStep Source {+ path: "../../../../testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp"+ textSha256: "341cea888fb316673ed683e59391c11b4f96cff2542d9387e135f06682dbd745"+ importTolerance: 0.01mm+ geometryOnly: true+ }+ Recognize Source {+ Region MountHole {+ kind: HoleShaft+ stepFaceEntities: ["#764", "#765"]+ evidence: { radius: 12.5mm; through: true }+ }+ }+ Replace Source.MountHole with Hole<Shaft> MountHole {+ on: Source.Face(98)+ center: Point3(-130mm, 45mm, 0mm)+ diameter: 25mm+ end: ThroughAll+ within: {+ min: Point3(-175mm, 30mm, -50mm)+ max: Point3(-115mm, 60mm, 0mm)+ }+ }+}diff --git a/tools/Aetheris.ImportedHoleExperiment/Aetheris.ImportedHoleExperiment.csproj b/tools/Aetheris.ImportedHoleExperiment/Aetheris.ImportedHoleExperiment.csprojnew file mode 100644index 00000000..24b4349d--- /dev/null+++ b/tools/Aetheris.ImportedHoleExperiment/Aetheris.ImportedHoleExperiment.csproj@@ -0,0 +1,9 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <OutputType>Exe</OutputType>+ <TargetFramework>net10.0</TargetFramework>+ </PropertyGroup>+ <ItemGroup>+ <ProjectReference Include="../../Aetheris.Kernel.Core/Aetheris.Kernel.Core.csproj" />+ </ItemGroup>+</Project>diff --git a/tools/Aetheris.ImportedHoleExperiment/MoveExperiment.cs b/tools/Aetheris.ImportedHoleExperiment/MoveExperiment.csnew file mode 100644index 00000000..0bdffc22--- /dev/null+++ b/tools/Aetheris.ImportedHoleExperiment/MoveExperiment.cs@@ -0,0 +1,96 @@+using System.Text.Json;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Import;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Core.Topology;++// The experiment now consumes the production kernel. No parallel surgery engine.+static class MoveExperiment+{+ static readonly JsonSerializerOptions Json = new() { WriteIndented = true };+ sealed class RevisionRefusal(string reason) : Exception(reason);+ public static void Run(BrepBody source, int seed, Vector3D delta, string directory)+ {+ var face = new FaceId(seed);+ if (!source.TryGetFaceSurfaceGeometry(face, out var surface) || surface?.Cylinder is not { } cylinder)+ throw new RevisionRefusal("Select a cylindrical seed face.");+ var axis = cylinder.Axis.ToVector();+ var walls = source.Topology.Faces.Where(f => source.TryGetFaceSurfaceGeometry(f.Id, out var s) && s?.Cylinder is { } c+ && System.Math.Abs(c.Radius - cylinder.Radius) < 1e-6 && c.Axis.ToVector().Cross(axis).Length < 1e-6+ && (c.Origin - cylinder.Origin).Cross(axis).Length < 1e-6).Select(f => f.Id).ToArray();+ var edgeIds = walls.SelectMany(id => source.Topology.GetFace(id).LoopIds)+ .SelectMany(id => source.Topology.GetLoop(id).CoedgeIds).Select(id => source.Topology.GetCoedge(id).EdgeId).ToHashSet();+ var vertices = edgeIds.SelectMany(id => { var e = source.Topology.GetEdge(id); return new[] { e.StartVertexId, e.EndVertexId }; }).Distinct()+ .Select(id => source.TryGetVertexPoint(id, out var point) ? point : throw new InvalidOperationException("Missing vertex.")).ToArray();+ var low = vertices.Min(p => p.Z); var high = vertices.Max(p => p.Z);+ var entry = source.Topology.Faces.FirstOrDefault(f => source.TryGetFaceSurfaceGeometry(f.Id, out var s) && s?.Plane is { } plane+ && System.Math.Abs(plane.Origin.Z - high) < 1e-6+ && f.LoopIds.SelectMany(id => source.Topology.GetLoop(id).CoedgeIds).Any(id => edgeIds.Contains(source.Topology.GetCoedge(id).EdgeId)));+ if (entry is null) throw new RevisionRefusal("No upper planar entry support.");+ var center = cylinder.Origin + delta; center = center with { Z = high };+ var pad = cylinder.Radius + 2.5;+ var within = new ThroughHoleEditBounds(new(System.Math.Min(center.X, cylinder.Origin.X) - pad, System.Math.Min(center.Y, cylinder.Origin.Y) - pad, low),+ new(System.Math.Max(center.X, cylinder.Origin.X) + pad, System.Math.Max(center.Y, cylinder.Origin.Y) + pad, high));+ var tolerance = source.ImportQualification?.PcurveToleranceMillimetres ?? 1e-3;+ var edited = BrepThroughHoleRevision.Execute(source, new("MovedHole", walls, entry.Id, center, 2 * cylinder.Radius, within, tolerance));+ if (!edited.IsSuccess) throw new RevisionRefusal(string.Join(" | ", edited.Diagnostics.Select(d => d.Message)));+ var result = edited.Value;+ var step = Step242Exporter.ExportBody(result.Body, new Step242ExportOptions+ {+ BrepExportPreflightMode = BrepExportPreflightMode.Enforce,+ ImportedRecoveryToleranceMillimetres = tolerance,+ DistanceAccuracyMillimetres = System.Math.Max(tolerance, source.ImportQualification?.SourceDistanceAccuracyMillimetres ?? 0)+ });+ if (!step.IsSuccess) throw new InvalidOperationException(string.Join(" | ", step.Diagnostics));+ var roundtrip = Step242Importer.ImportBody(step.Value, new ImportPolicy(PcurveQualificationToleranceMillimetres: tolerance));+ if (!roundtrip.IsSuccess || roundtrip.Value.ImportQualification?.GeometryStatus != ImportQualificationStatus.Qualified)+ throw new InvalidOperationException("Production kernel result did not roundtrip as qualified.");+ Directory.CreateDirectory(directory);+ File.WriteAllText(Path.Combine(directory, "replace.step"), step.Value);+ File.WriteAllText(Path.Combine(directory, "report.json"), JsonSerializer.Serialize(new+ {+ strategy = "ThroughHoleSuppressionReinsertion",+ kernel = "BrepThroughHoleRevision",+ geometryOnly = true,+ source.ImportQualification,+ tolerance,+ result.Center,+ result.Diameter,+ result.Depth,+ result.Within,+ result.PreservedFaces,+ result.PreservedEdges,+ retired = result.RetiredWallFaces.Select(id => id.Value),+ walls = result.WallFaces.Select(id => id.Value),+ roundtripQualification = roundtrip.Value.ImportQualification,+ note = "BRep geometry harness; use the Firmament fixture for source pinning, diagnostics and semantic replacement PMI."+ }, Json));+ Console.WriteLine($"Moved hole {seed}: diameter {result.Diameter:R}, center {center}; retained {result.PreservedFaces} faces/{result.PreservedEdges} edges.");+ }++ public static void Qualify(BrepBody source, string directory)+ {+ var cases = new[]{("web-hole",1,30d,true),("overlap",1,5d,true),("noop",1,0d,true),+ ("collision",1,320d,false),("breakout",1,-250d,false),("nonhole",4,30d,false),("blind",13,30d,false),("lobe",72,5d,false)};+ var before = JsonSerializer.Serialize(new { source.Topology, curves = source.Geometry.Curves, surfaces = source.Geometry.Surfaces });+ var results = new List<object>();+ foreach (var (name, seed, dx, accept) in cases)+ {+ try+ {+ Run(source, seed, new(dx, 0, 0), Path.Combine(directory, name));+ if (!accept) throw new InvalidOperationException($"Unexpected acceptance: {name}.");+ results.Add(new { name, passed = true, accepted = true });+ }+ catch (RevisionRefusal refusal) when (!accept) { results.Add(new { name, passed = true, accepted = false, reason = refusal.Message }); }+ if (before != JsonSerializer.Serialize(new { source.Topology, curves = source.Geometry.Curves, surfaces = source.Geometry.Surfaces }))+ throw new InvalidOperationException("Kernel edited the original input.");+ }+ Directory.CreateDirectory(directory);+ File.WriteAllText(Path.Combine(directory, "cases.json"), JsonSerializer.Serialize(results, Json));+ Console.WriteLine($"Production kernel qualification passed: {cases.Length} cases.");+ }+}diff --git a/tools/Aetheris.ImportedHoleExperiment/Program.cs b/tools/Aetheris.ImportedHoleExperiment/Program.csnew file mode 100644index 00000000..8ce09ee0--- /dev/null+++ b/tools/Aetheris.ImportedHoleExperiment/Program.cs@@ -0,0 +1,78 @@+using System.Text.Json;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Core.Topology;++// Outside the solution: a fixture harness for the production kernel owner,+// not a second Firmament admission path.+try+{+ if (args.Length == 0 || args[0] is "--help" or "-h")+ {+ Console.WriteLine("Imported-hole experiment: <input.step> [inventory | move <seed-face> <dx-mm> <dy-mm> [output-directory] | qualify [output-directory]] [--import-tolerance-mm value]");+ return;+ }+ var toleranceIndex = Array.IndexOf(args, "--import-tolerance-mm");+ var tolerance = toleranceIndex >= 0 && toleranceIndex + 1 < args.Length+ ? double.Parse(args[toleranceIndex + 1], System.Globalization.CultureInfo.InvariantCulture)+ : args.Length > 1 && args[1] == "qualify" ? .01 : .001;+ var imported = Step242Importer.ImportBody(File.ReadAllText(args[0]), new Aetheris.Kernel.Core.Import.ImportPolicy(PcurveQualificationToleranceMillimetres: tolerance));+ if (!imported.IsSuccess) throw new Exception(JsonSerializer.Serialize(imported.Diagnostics));+ var body = imported.Value;+ if (args.Length > 1 && args[1] == "move")+ {+ if (args.Length < 5) throw new ArgumentException("move requires seed-face, dx-mm and dy-mm.");+ MoveExperiment.Run(body, int.Parse(args[2]), new(double.Parse(args[3], System.Globalization.CultureInfo.InvariantCulture), double.Parse(args[4], System.Globalization.CultureInfo.InvariantCulture), 0),+ args.Length > 5 && !args[5].StartsWith("--", StringComparison.Ordinal) ? args[5] : "artifacts/local/imported-hole-experiment");+ return;+ }+ if (args.Length > 1 && args[1] == "qualify")+ {+ MoveExperiment.Qualify(body, args.Length > 2 && !args[2].StartsWith("--", StringComparison.Ordinal) ? args[2] : "artifacts/local/imported-hole-experiment");+ return;+ }+ if (args.Length > 1 && args[1] != "inventory")+ throw new ArgumentException($"Unknown experimental operation '{args[1]}'.");+ var edgeFaces = body.Topology.Faces.SelectMany(f => f.LoopIds.SelectMany(l => body.Topology.GetLoop(l).CoedgeIds)+ .Select(c => body.Topology.GetCoedge(c).EdgeId).Distinct().Select(e => (Edge: e, Face: f.Id)))+ .GroupBy(x => x.Edge).ToDictionary(g => g.Key, g => g.Select(x => x.Face).ToArray());+ var inventory = body.Topology.Faces.Where(f => body.TryGetFaceSurfaceGeometry(f.Id, out var s) && s!.Kind == SurfaceGeometryKind.Cylinder).Select(f =>+ {+ body.TryGetFaceSurfaceGeometry(f.Id, out var s);+ var cylinder = s!.Cylinder!.Value;+ var edges = f.LoopIds.SelectMany(l => body.Topology.GetLoop(l).CoedgeIds).Select(c => body.Topology.GetCoedge(c).EdgeId).Distinct().ToArray();+ return new+ {+ face = f.Id.Value,+ step = body.Bindings.GetFaceBinding(f.Id).SourceStepEntityId,+ radius = cylinder.Radius,+ origin = cylinder.Origin,+ axis = cylinder.Axis,+ aligned = body.Bindings.GetFaceBinding(f.Id).Orientation.IsAlignedWithSurface,+ neighbors = edges.SelectMany(e => edgeFaces[e]).Where(id => id != f.Id).Distinct().Select(id =>+ {+ body.TryGetFaceSurfaceGeometry(id, out var ns);+ return new { face = id.Value, kind = ns!.Kind.ToString(), loops = body.Topology.GetFace(id).LoopIds.Count };+ }),+ edges = edges.Select(id =>+ {+ body.TryGetEdgeCurveGeometry(id, out var c); var edge = body.Topology.GetEdge(id); return new+ {+ id = id.Value,+ curve = c!.Kind.ToString(),+ circle = c.Circle3,+ start = edge.StartVertexId.Value,+ end = edge.EndVertexId.Value,+ trim = body.Bindings.GetEdgeBinding(id).TrimInterval+ };+ })+ };+ });+ Console.WriteLine(JsonSerializer.Serialize(inventory, new JsonSerializerOptions { WriteIndented = true }));+}+catch (Exception error)+{+ Console.Error.WriteLine(JsonSerializer.Serialize(new { status = "experiment-failed", errorType = error.GetType().Name, reason = error.Message }));+ Environment.ExitCode = 2;+}diff --git a/tools/Aetheris.ImportedHoleExperiment/README.md b/tools/Aetheris.ImportedHoleExperiment/README.mdnew file mode 100644index 00000000..21755ad9--- /dev/null+++ b/tools/Aetheris.ImportedHoleExperiment/README.md@@ -0,0 +1,50 @@+# Imported-hole qualification harness++This repository-local tool consumes the production `BrepThroughHoleRevision`+owner. It does not contain a second surgery engine or parse Firmament. Use the+[golden Firmament fixture](../../fixtures/Regression/InlineStep/production/ctc01-hole-move.firmament)+for the complete source pin, explicit geometry-only import, structured diagnostics+and replacement-hole semantic PMI path.++From the repository root in PowerShell:++```powershell+dotnet build tools/Aetheris.ImportedHoleExperiment -c Release -m:1 -nr:false -p:UseSharedCompilation=false+dotnet tools/Aetheris.ImportedHoleExperiment/bin/Release/net10.0/Aetheris.ImportedHoleExperiment.dll testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp qualify artifacts/local/imported-hole-production/kernel-cases+```++`qualify` is a CTC-01-specific witness, using the source's 0.01 mm accuracy. It+checks three accepted cases (30 mm move, overlapping 5 mm move and no-op) and five+refusals (collision, breakout, non-hole, blind hole and intersecting lobe). Each+success must export/reimport as qualified. Input topology and geometry must remain+unchanged after every case. An unexpected acceptance/failure exits nonzero.++Other operations:++```powershell+# Inspect cylindrical face geometry, source entities and adjacency.+dotnet tools/Aetheris.ImportedHoleExperiment/bin/Release/net10.0/Aetheris.ImportedHoleExperiment.dll testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp inventory++# Move the complete coaxial group containing sequential face 1 by +30 mm X.+# CTC requires the explicit source accuracy budget; the normal default is .001 mm.+dotnet tools/Aetheris.ImportedHoleExperiment/bin/Release/net10.0/Aetheris.ImportedHoleExperiment.dll testdata/step242/nist/CTC/nist_ctc_01_asme1_ap242-e1.stp move 1 30 0 artifacts/local/imported-hole-production/single --import-tolerance-mm 0.01+```++`move` writes `replace.step` and `report.json`; `qualify` also writes `cases.json`.+Outputs default to ignored `artifacts/local/imported-hole-experiment/`. These are+geometry-only kernel witnesses, not annotation-preserving manufacturing releases.+The auto-generated 2.5 mm stock padding belongs to this fixture harness; production+Firmament requires the author to declare the `within` envelope.++The initial family is an isolated, constant-diameter Z-axis round through-hole+between two planar supports. Conservative whole-support bounds reject unproved+clearance. Unknown support/curve bounds, blind/intersecting/blended/threaded holes,+resizing and other frames reject. The kernel validates intermediate suppression,+final incidence, pcurves and export preflight. No general Boolean fallback occurs.++CTC now qualifies all 636 trims at its declared 0.01 mm accuracy. A cone-apex chart+fix repairs four singular generators; remaining strict .001 mm failures reflect+actual source curve/support discrepancies around .0034 mm. Geometry is not refit.+See the [production closeout](../../docs/release/IMPORTED-HOLE-REVISION-PRODUCTION-2026-10-20.md).+Original dual-strategy experiments are retained as historical reports, rather+than executable alternative production implementations.