Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add datum mate solving and correct AP242 assembly transforms
Yuechen Li9218a0418eae
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 64fe2b8a..756ed361 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -2779,12 +2779,13 @@ Model CanonicalPanel {if (!File.Exists(path)) { stderr.WriteLine($"Assembly source '{path}' was not found."); return 1; }var sourceText = File.ReadAllText(path);var usesTemplateInstances = Regex.IsMatch(sourceText, @"<Part\s+[A-Za-z_]\w*\s*=\s*[A-Za-z_]\w*\s*<", RegexOptions.CultureInvariant);+ var usesSheetMetalParts = sourceText.Contains("Use SheetMetal.ProductFamilies", StringComparison.Ordinal);AssemblyIr? assemblyIr;AssemblyGeometryArtifactIr? geometryArtifact;IReadOnlyList<AssemblyDiagnostic> assemblyDiagnostics;AssemblyPerformanceIr? assemblyPerformance;bool success;- if (string.Equals(Path.GetExtension(path), ".firmasm", StringComparison.OrdinalIgnoreCase))+ if (string.Equals(Path.GetExtension(path), ".firmasm", StringComparison.OrdinalIgnoreCase) && !usesSheetMetalParts){var document = new FirmamentAssemblyDocumentCompiler().CompileFile(path);assemblyIr = document.Compilation.Ir;@@ -2795,7 +2796,7 @@ Model CanonicalPanel {}else if (usesTemplateInstances){- var m1 = new AssemblyM1Pipeline().CompileFile(path);+ var m1 = new AssemblyM1Pipeline().CompileFile(path, usesSheetMetalParts ? EnclosureProductFamilies.MaterializeAssemblyPart : null);assemblyIr = m1.Ir;geometryArtifact = m1.Geometry?.Artifact;assemblyDiagnostics = m1.Diagnostics;@@ -2829,8 +2830,33 @@ Model CanonicalPanel {foreach (var instance in ir.Instances.OrderBy(x => x.Path.Segments.Count).ThenBy(x => x.Path.ToString(), StringComparer.Ordinal))stdout.WriteLine($"{new string(' ', (instance.Path.Segments.Count - 1) * 2)}- {instance.Path.Segments[^1]} [{instance.Kind}] = {instance.DefinitionIdentity}; placement={instance.PlacementAuthority}");stdout.WriteLine("Mates:");- foreach (var mate in ir.Mates)+ foreach (var mate in ir.Mates.Concat((ir.AssemblyDefinitions ?? []).SelectMany(definition => definition.LocalMates)).DistinctBy(mate => mate.StableId))stdout.WriteLine($"- {mate.Name}: {mate.InterfaceStableId} ({string.Join(", ", mate.Roles.Select(x => x.Role + "=" + x.ParticipantPath))})");+ var datums = (ir.Datums ?? []).Concat((ir.AssemblyDefinitions ?? []).SelectMany(definition => definition.LocalDatums ?? []))+ .DistinctBy(datum => datum.SemanticPath).OrderBy(datum => datum.SemanticPath, StringComparer.Ordinal).ToArray();+ var rootDatums = datums.Where(datum => datum.SemanticPath.StartsWith(ir.Name + ".", StringComparison.Ordinal)).ToArray();+ if (rootDatums.Any(datum => datum.SemanticPath.Contains(".Datums.", StringComparison.Ordinal)))+ datums = rootDatums.Where(datum => datum.SemanticPath.Contains(".Datums.", StringComparison.Ordinal)).ToArray();+ else if (rootDatums.Length > 0)+ datums = rootDatums;+ if (datums.Length > 0)+ {+ stdout.WriteLine("Semantic datums:");+ foreach (var datum in datums) stdout.WriteLine($"- {datum.SemanticPath} [{datum.Kind}] id={datum.StableBindingId}");+ }+ var datumMates = (ir.DatumMateSolutions ?? []).Concat((ir.AssemblyDefinitions ?? []).SelectMany(definition => definition.LocalDatumMateSolutions ?? []))+ .DistinctBy(solution => (solution.MateStableId, solution.FirstDatumSemanticValueId, solution.SecondDatumSemanticValueId)).OrderBy(solution => solution.MateStableId, StringComparer.Ordinal).ToArray();+ if (datumMates.Length > 0)+ {+ stdout.WriteLine("Datum Mate solutions:");+ foreach (var solution in datumMates)+ {+ var translation = solution.DerivedTransform is { Matrix.Length: >= 15 } transform+ ? $"; translation=[{transform.Matrix[12]:G6},{transform.Matrix[13]:G6},{transform.Matrix[14]:G6}]mm"+ : string.Empty;+ stdout.WriteLine($"- {solution.MateStableId}: {solution.Orientation}; DOF={solution.ConstrainedDegreesOfFreedom}/6; {solution.Status}{translation}");+ }+ }if (geometryArtifact is not null){stdout.WriteLine($"Executable geometry: {geometryArtifact.Instances.Count} instances, {geometryArtifact.Definitions.Count} definitions, sha256={geometryArtifact.DeterministicSha256}");@@ -2843,6 +2869,14 @@ Model CanonicalPanel {stdout.WriteLine("Tolerance stackups:");foreach (var stack in ir.ToleranceStackups)stdout.WriteLine($"- {stack.Name}: nominal={stack.Nominal:G6} {stack.Unit}, worst=[{stack.WorstCaseMinimum:G6},{stack.WorstCaseMaximum:G6}], {stack.Status}, contributors={stack.Contributions.Count}");+ var fits = ir.FitResults.Concat((ir.AssemblyDefinitions ?? []).SelectMany(definition => definition.LocalFitResults ?? []))+ .DistinctBy(fit => fit.MateStableId).OrderBy(fit => fit.MateStableId, StringComparer.Ordinal).ToArray();+ if (fits.Length > 0)+ {+ stdout.WriteLine("Fit evidence:");+ foreach (var fit in fits)+ stdout.WriteLine($"- {fit.MateStableId}: nominal={fit.NominalClearance:G6}{fit.Unit}; envelope=[{fit.WorstCaseMinimum:G6},{fit.WorstCaseMaximum:G6}]{fit.Unit}; {fit.NominalState} -> {fit.VariationEnvelopeState}; penetration={fit.MaximumPenetration:G6}{fit.Unit}");+ }foreach (var diagnostic in assemblyDiagnostics)(diagnostic.Severity == AssemblyDiagnosticSeverity.Error ? stderr : stdout).WriteLine($"{diagnostic.Severity}: {diagnostic.Code}: {diagnostic.Message}");}@@ -3508,7 +3542,11 @@ Model CanonicalPanel {string? output = null; var json = false;for (var i = 1; i < args.Length; i++) if (args[i] == "--out" && i + 1 < args.Length) output = args[++i]; else if (args[i] == "--json") json = true; else { stderr.WriteLine(AsmExportAp242Usage); return 1; }if (output is null || !File.Exists(args[0])) { stderr.WriteLine(AsmExportAp242Usage); return 1; }- var compilation = string.Equals(Path.GetExtension(args[0]), ".firmasm", StringComparison.OrdinalIgnoreCase) ? new FirmamentAssemblyDocumentCompiler().CompileFile(args[0]).Compilation : new AssemblyM1Pipeline().CompileFile(args[0]);+ var sourceText = File.ReadAllText(args[0]);+ var usesSheetMetalParts = sourceText.Contains("Use SheetMetal.ProductFamilies", StringComparison.Ordinal);+ var compilation = string.Equals(Path.GetExtension(args[0]), ".firmasm", StringComparison.OrdinalIgnoreCase) && !usesSheetMetalParts+ ? new FirmamentAssemblyDocumentCompiler().CompileFile(args[0]).Compilation+ : new AssemblyM1Pipeline().CompileFile(args[0], usesSheetMetalParts ? EnclosureProductFamilies.MaterializeAssemblyPart : null);var export = AssemblyIrAp242Exporter.Export(compilation);if (!export.IsSuccess) { foreach (var diagnostic in export.Diagnostics) stderr.WriteLine($"{diagnostic.Source}: {diagnostic.Message}"); return 1; }var fullOutput = Path.GetFullPath(output); Directory.CreateDirectory(Path.GetDirectoryName(fullOutput)!); File.WriteAllText(fullOutput, export.Value);diff --git a/Aetheris.Kernel.Core.Tests/Step242/Step242AssemblyProductStructureTests.cs b/Aetheris.Kernel.Core.Tests/Step242/Step242AssemblyProductStructureTests.csindex 0ad90540..cccf8bed 100644--- a/Aetheris.Kernel.Core.Tests/Step242/Step242AssemblyProductStructureTests.cs+++ b/Aetheris.Kernel.Core.Tests/Step242/Step242AssemblyProductStructureTests.cs@@ -31,6 +31,14 @@ public sealed class Step242AssemblyProductStructureTestsAssert.Equal(2, imported.Value.Occurrences.Count);Assert.Single(imported.Value.Definitions, definition => definition.StableId == "def:bolt" && definition.Geometry is not null);Assert.Equal(25, imported.Value.Occurrences.Single(occurrence => occurrence.StableId == "bolt-2").LocalTransform[12], 8);++ // AP242 occurrence transforms relate the child representation to its parent.+ // A parent-first relationship appears correct to Aetheris' own importer but causes+ // standards-compliant CAD viewers to apply the inverse translation.+ var childRepresentation = imported.Value.Definitions.Single(definition => definition.StableId == "def:bolt").RepresentationEntityId;+ var parentRepresentation = imported.Value.Definitions.Single(definition => definition.StableId == "root").RepresentationEntityId;+ Assert.Contains($"(REPRESENTATION_RELATIONSHIP('bolt-2','',#{childRepresentation},#{parentRepresentation})REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(#", first.Value, StringComparison.Ordinal);+ Assert.Contains("SHAPE_REPRESENTATION_RELATIONSHIP())", first.Value, StringComparison.Ordinal);}[Fact]diff --git a/Aetheris.Kernel.Core/Step242/Step242AssemblyProductStructure.cs b/Aetheris.Kernel.Core/Step242/Step242AssemblyProductStructure.csindex 640aa726..2bed7e5a 100644--- a/Aetheris.Kernel.Core/Step242/Step242AssemblyProductStructure.cs+++ b/Aetheris.Kernel.Core/Step242/Step242AssemblyProductStructure.cs@@ -140,7 +140,11 @@ public static class Step242AssemblyExportervar x = Add("DIRECTION", Str(""), $"({Num(m[0])},{Num(m[1])},{Num(m[2])})");var placement = Add("AXIS2_PLACEMENT_3D", Str(""), Ref(point), Ref(z), Ref(x));var transformation = Add("ITEM_DEFINED_TRANSFORMATION", Str(usageStableId), Str("Aetheris rigid occurrence transform"), Ref(identityAxis), Ref(placement));- var relationship = Add("REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION", Str(usageStableId), Str(""), Ref(parent.Representation), Ref(child.Representation), Ref(transformation));+ // AP242 maps representation_1 (the child) into representation_2 (the parent)+ // using the item-defined occurrence transform. Writing the parent first reverses+ // that mapping and makes standards-compliant consumers apply the inverse placement.+ var relationship = AddRaw($"(REPRESENTATION_RELATIONSHIP({Str(usageStableId)},{Str("")},{Ref(child.Representation)},{Ref(parent.Representation)})" ++ $"REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION({Ref(transformation)})SHAPE_REPRESENTATION_RELATIONSHIP())");Add("CONTEXT_DEPENDENT_SHAPE_REPRESENTATION", Ref(relationship), Ref(usageShape));}diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyM7DatumTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyM7DatumTests.csnew file mode 100644index 00000000..20796979--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/AssemblyM7DatumTests.cs@@ -0,0 +1,94 @@+using Aetheris.Kernel.Firmament.Assembly;++namespace Aetheris.Kernel.Firmament.Tests.Assembly;++public sealed class AssemblyM7DatumTests+{+ [Fact]+ public void GenericDatumFrameMate_ResolvesAllSixDegreesOfFreedom()+ {+ const string source = """+ Interface RegisteredFrame {+ Role Moving requires DatumFrameCapable;+ Role Fixed requires DatumFrameCapable;+ Lower FrameCoincident Moving Fixed SameDirection;+ }+ Assembly Fixture {+ <Assembly Fixture>+ <Part Plate = PlatePart> Semantic Mount { DatumFrame Frame = [10,20,30] x [1,0,0] y [0,1,0] z [0,0,1]; } </Part>+ <Part Bracket = BracketPart> Semantic Mount { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; } </Part>+ </Assembly>+ Anchor: Fixture.Plate.Mount;+ Mate BracketMount: RegisteredFrame { Moving: Fixture.Bracket.Mount; Fixed: Fixture.Plate.Mount; }+ }+ """;+ var result = Compile(source);+ Assert.True(result.IsSuccess, Evidence(result));+ var placement = result.Ir!.Placements.Single(item => item.InstanceStableId.EndsWith(":Fixture.Bracket", StringComparison.Ordinal));+ Assert.Equal(PlacementStatus.Resolved, placement.Status);+ Assert.Empty(placement.FreeTranslations); Assert.Empty(placement.FreeRotations);+ Assert.Equal(10, placement.Transform!.Matrix[12], 6);+ Assert.Equal(20, placement.Transform.Matrix[13], 6);+ Assert.Equal(30, placement.Transform.Matrix[14], 6);+ var solution = Assert.Single(result.Ir.DatumMateSolutions!);+ Assert.Equal(6, solution.ConstrainedDegreesOfFreedom);+ Assert.Equal("resolved", solution.Status);+ }++ [Fact]+ public void MissingDatumPath_FailsBeforeGeometry()+ {+ var result = Compile(PairSource("Missing", includeSecondMate: false));+ Assert.Contains(result.Diagnostics, item => item.Code == AssemblyM0Compiler.InvalidParticipant);+ }++ [Fact]+ public void NonOrthonormalDatumFrame_IsRejectedByParser()+ {+ const string source = "Assembly Bad { <Assembly Bad><Part P = Block> Semantic D { DatumFrame F = [0,0,0] x [1,0,0] y [1,0,0] z [0,0,1]; } </Part></Assembly> Anchor: Bad.P.D; }";+ var parsed = new AssemblyM0Parser().Parse(source);+ Assert.Contains(parsed.Diagnostics, item => item.Code == "assembly-datum-frame-invalid");+ }++ [Fact]+ public void ConflictingDatumFrames_AreTypedOverconstraint()+ {+ var result = Compile(PairSource("Frame", includeSecondMate: true));+ Assert.Contains(result.Diagnostics, item => item.Code == AssemblyM0Compiler.Overconstrained);+ Assert.Contains(result.Ir!.Placements, item => item.Status == PlacementStatus.Overconstrained);+ }++ private static string PairSource(string fixedMember, bool includeSecondMate) => $$"""+ Interface RegisteredFrame {+ Role Moving requires DatumFrameCapable;+ Role Fixed requires DatumFrameCapable;+ Lower FrameCoincident Moving.Frame Fixed.{{fixedMember}} SameDirection;+ }+ Interface DirectFrame {+ Role Moving requires DatumFrameCapable;+ Role Fixed requires DatumFrameCapable;+ Lower FrameCoincident Moving Fixed SameDirection;+ }+ Assembly Pair {+ <Assembly Pair>+ <Part Fixed = Block>+ Semantic Fixed { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }+ Semantic Other { DatumFrame Frame = [10,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; }+ </Part>+ <Part Moving = Block> Semantic Moving { DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1]; } </Part>+ </Assembly>+ Anchor: Pair.Fixed.Fixed;+ Mate First: RegisteredFrame { Moving: Pair.Moving.Moving; Fixed: Pair.Fixed.Fixed; }+ {{(includeSecondMate ? "Mate Second: DirectFrame { Moving: Pair.Moving.Moving.Frame; Fixed: Pair.Fixed.Other.Frame; }" : string.Empty)}}+ }+ """;++ private static AssemblyCompilationResult Compile(string source)+ {+ var parsed = new AssemblyM0Parser().Parse(source);+ Assert.NotNull(parsed.Source);+ return new AssemblyM0Compiler().Compile(parsed.Source!);+ }++ private static string Evidence(AssemblyCompilationResult result) => string.Join(Environment.NewLine, result.Diagnostics.Select(item => item.Code + ": " + item.Message));+}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.csindex 09ca7932..8ef6e364 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Compiler.cs@@ -63,10 +63,28 @@ public sealed class AssemblyM0CompilergraphWatch.Elapsed.TotalMilliseconds, toleranceWatch.Elapsed.TotalMilliseconds);var assemblyDefinitions = source.Root.Flatten().Select(member => member.SolvedAssemblyDefinition).Where(definition => definition is not null).Cast<AssemblyDefinitionIr>().DistinctBy(definition => definition.StableId).OrderBy(definition => definition.StableId, StringComparer.Ordinal).ToArray();+ var datums = instances.SelectMany(instance => Flatten([instance.SemanticRoot])+ .Where(value => value.Type.Name == "AssemblyDatumFrame" && value.TryBinding<ExactDatumFrameBinding>(out _))+ .Select(value => new AssemblyDatumIr(value.StableIdentity, SemanticPath(instance, value), "DatumFrame",+ value.TryBinding<ExactDatumFrameBinding>(out var frame) ? frame.FrameStableId : value.StableIdentity)))+ .OrderBy(datum => datum.SemanticPath, StringComparer.Ordinal).ToArray();+ var datumSolutions = mates.SelectMany(mate => constraints.Where(constraint => constraint.MateStableId == mate.StableId && constraint.Kind == PlacementConstraintKind.FrameCoincident)+ .Select(constraint => new DatumMateSolutionIr(mate.StableId, constraint.FirstSemanticValueId, constraint.SecondSemanticValueId,+ constraint.Orientation, 6, placements.Any(placement => placement.ConstraintIds.Contains(constraint.StableId) && placement.Status == PlacementStatus.Overconstrained) ? "conflicting" : "resolved",+ placements.FirstOrDefault(placement => placement.ConstraintIds.Contains(constraint.StableId) && placement.Authority == PlacementAuthority.MateDerived)?.Transform)))+ .OrderBy(solution => solution.MateStableId, StringComparer.Ordinal).ToArray();var ir = new AssemblyIr("aetheris/assembly-ir/m0", $"assembly:{source.Name}", source.Name,instances.Single(x => x.ParentStableId is null).StableId, instances, source.Interfaces, mates,- constraints, placements, relations, stackups, fits, diagnostics, assemblyDefinitions, panelMateEvidence);+ constraints, placements, relations, stackups, fits, diagnostics, assemblyDefinitions, panelMateEvidence, datums, datumSolutions);return new(ir, diagnostics, perf);++ static string SemanticPath(AssemblyInstanceIr instance, SemanticValue value)+ {+ var prefix = instance.SemanticRoot.StableIdentity + ":";+ return value.StableIdentity.StartsWith(prefix, StringComparison.Ordinal)+ ? instance.Path + "." + value.StableIdentity[prefix.Length..]+ : instance.Path + "." + (value.ExposedName ?? value.StableIdentity);+ }}private static IReadOnlyList<AssemblyInstanceIr> BindInstances(AssemblySource source, List<AssemblyDiagnostic> diagnostics)@@ -189,7 +207,7 @@ public sealed class AssemblyM0Compilervar secondId = ResolveRelativeSemantic(second.ParticipantSemanticValueId, requirement.SecondMember, instances);if (firstId is null || secondId is null){ diagnostics.Add(new(InvalidParticipant, $"Interface '{definition.Name}' requirement '{requirement.Kind}' cannot resolve exposed members '{requirement.FirstMember}'/'{requirement.SecondMember}'.")); continue; }- result.Add(new($"constraint:{mate.StableId}:{index:D2}", requirement.Kind, mate.StableId, firstId, secondId, requirement.OffsetMm, 0, "admitted"));+ result.Add(new($"constraint:{mate.StableId}:{index:D2}", requirement.Kind, mate.StableId, firstId, secondId, requirement.OffsetMm, 0, "admitted", requirement.Orientation));}}return result;@@ -262,6 +280,14 @@ public sealed class AssemblyM0Compilervar movingInstance = firstKnown ? owners[1] : owners[0];var targetInstance = firstKnown ? owners[0] : owners[1];var orientedConstraints = Orient(mateConstraints, movingInstance, instances);+ var frameCandidates = orientedConstraints.Where(x => x.Kind == PlacementConstraintKind.FrameCoincident)+ .Select(x => CandidateTransform([x], instances, known[targetInstance.StableId])).ToArray();+ if (frameCandidates.Length > 1 && frameCandidates.Skip(1).Any(x => TransformDistance(frameCandidates[0], x) > 1e-7))+ {+ overconstrained.Add(movingInstance.StableId);+ diagnostics.Add(new(Overconstrained, $"Instance '{movingInstance.Path}' receives conflicting DatumFrame constraints from Mate '{mate.Name}'."));+ continue;+ }var axisCandidates = orientedConstraints.Where(x => x.Kind == PlacementConstraintKind.AxisCoincident).Select(x => CandidateTransform([x], instances, known[targetInstance.StableId])).ToArray();if (axisCandidates.Length > 1 && axisCandidates.Skip(1).Any(x => TransformDistance(axisCandidates[0], x) > 1e-7))@@ -305,11 +331,12 @@ public sealed class AssemblyM0Compiler{ results.Add(new(instance.StableId, PlacementStatus.Overconstrained, null, [], [], relevant.Select(x => x.StableId).ToArray())); continue; }if (relevant.Length == 0 || !known.TryGetValue(instance.StableId, out var transform)){ results.Add(new(instance.StableId, PlacementStatus.Unresolved, null, ["X", "Y", "Z"], ["X", "Y", "Z"], relevant.Select(x => x.StableId).ToArray())); continue; }+ var hasFrame = relevant.Any(x => x.Kind == PlacementConstraintKind.FrameCoincident);var hasAxis = relevant.Any(x => x.Kind is PlacementConstraintKind.AxisCoincident or PlacementConstraintKind.AxisAligned);var hasPlane = relevant.Any(x => x.Kind == PlacementConstraintKind.PlaneCoincident);var hasPoint = relevant.Any(x => x.Kind == PlacementConstraintKind.PointCoincident);- var freeT = hasAxis ? (hasPlane || hasPoint ? Array.Empty<string>() : ["along-axis"]) : (hasPoint ? Array.Empty<string>() : ["X", "Y", "Z"]);- string[] freeR = hasAxis ? ["about-axis"] : ["X", "Y", "Z"];+ var freeT = hasFrame ? Array.Empty<string>() : hasAxis ? (hasPlane || hasPoint ? Array.Empty<string>() : ["along-axis"]) : (hasPoint ? Array.Empty<string>() : ["X", "Y", "Z"]);+ string[] freeR = hasFrame ? [] : hasAxis ? ["about-axis"] : ["X", "Y", "Z"];var involvedInterfaces = mates.Where(m => relevant.Any(c => c.MateStableId == m.StableId)).Select(m => interfaces.Values.Single(x => x.StableId == m.InterfaceStableId)).ToArray();string[] admitted = involvedInterfaces.Length == 0 ? [] : (involvedInterfaces.Select(x => x.AdmittedFreeMotions ?? []).Aggregate((IEnumerable<string>?)null,(common, next) => common is null ? next : common.Intersect(next, StringComparer.Ordinal)) ?? []).ToArray();@@ -339,6 +366,18 @@ public sealed class AssemblyM0Compilerprivate static AssemblyTransform CandidateTransform(IReadOnlyList<PlacementConstraintIr> constraints, IReadOnlyList<AssemblyInstanceIr> instances, AssemblyTransform? targetWorld = null){var values = Flatten(instances.Select(x => x.SemanticRoot)).ToDictionary(x => x.StableIdentity, StringComparer.Ordinal);+ var frameConstraint = constraints.FirstOrDefault(x => x.Kind == PlacementConstraintKind.FrameCoincident);+ if (frameConstraint is not null+ && values[frameConstraint.FirstSemanticValueId].TryBinding<ExactDatumFrameBinding>(out var sourceFrame)+ && values[frameConstraint.SecondSemanticValueId].TryBinding<ExactDatumFrameBinding>(out var targetFrame))+ {+ var source = FrameMatrix(sourceFrame, DatumOrientationRelation.SameDirection);+ var targetFrameMatrix = FrameMatrix(targetFrame, frameConstraint.Orientation);+ if (!Matrix4x4.Invert(source, out var inverse)) return targetWorld ?? AssemblyTransform.Identity;+ var transform = inverse * targetFrameMatrix;+ if (targetWorld is not null) transform *= ToMatrix(targetWorld);+ return FromMatrix(transform);+ }var axis = constraints.FirstOrDefault(x => x.Kind == PlacementConstraintKind.AxisCoincident);if (axis is null || !values[axis.FirstSemanticValueId].TryBinding<ExactAxisBinding>(out var a) || !values[axis.SecondSemanticValueId].TryBinding<ExactAxisBinding>(out var b))return targetWorld ?? AssemblyTransform.Identity;@@ -366,6 +405,16 @@ public sealed class AssemblyM0Compilerrotation.M31, rotation.M32, rotation.M33, rotation.M34, rotation.M41, rotation.M42, rotation.M43, rotation.M44]);}+ private static Matrix4x4 FrameMatrix(ExactDatumFrameBinding frame, DatumOrientationRelation orientation)+ {+ var x = Vector3.Normalize(new((float)frame.XAxisX, (float)frame.XAxisY, (float)frame.XAxisZ));+ var y = Vector3.Normalize(new((float)frame.YAxisX, (float)frame.YAxisY, (float)frame.YAxisZ));+ var z = Vector3.Normalize(new((float)frame.ZAxisX, (float)frame.ZAxisY, (float)frame.ZAxisZ));+ if (orientation == DatumOrientationRelation.OpposedDirection) { y = -y; z = -z; }+ return new(x.X, x.Y, x.Z, 0, y.X, y.Y, y.Z, 0, z.X, z.Y, z.Z, 0,+ (float)frame.OriginX, (float)frame.OriginY, (float)frame.OriginZ, 1);+ }+private static Matrix4x4 ToMatrix(AssemblyTransform transform) => new((float)transform.Matrix[0], (float)transform.Matrix[1], (float)transform.Matrix[2], (float)transform.Matrix[3],(float)transform.Matrix[4], (float)transform.Matrix[5], (float)transform.Matrix[6], (float)transform.Matrix[7],@@ -438,14 +487,43 @@ public sealed class AssemblyM0Compilerif (shaftId is null || boreId is null || !values[shaftId].TryBinding<TolerancedDimensionBinding>(out var sd) || !values[boreId].TryBinding<TolerancedDimensionBinding>(out var bd)){ diagnostics.Add(new(CapabilityMismatch, $"Mate '{mate.Name}' fit requires toleranced dimensions '{fit.ShaftDimension}' and '{fit.BoreDimension}'.")); continue; }if (sd.Unit != bd.Unit) { diagnostics.Add(new("assembly-tolerance-unit-mismatch", $"Mate '{mate.Name}' fit dimensions use '{sd.Unit}' and '{bd.Unit}'.")); continue; }- var nominal = bd.Nominal - sd.Nominal;- var min = bd.Minimum - sd.Maximum;- var max = bd.Maximum - sd.Minimum;+ var nominal = fit.ClearanceScale * (bd.Nominal - sd.Nominal);+ var min = fit.ClearanceScale * (bd.Minimum - sd.Maximum);+ var max = fit.ClearanceScale * (bd.Maximum - sd.Minimum);+ var contributions = Array.Empty<FitContributionIr>();+ if (fit.Variation is { } variation)+ {+ var bend = 2d * variation.EngagementLengthMm * Math.Tan(variation.BendAngleToleranceDegrees * Math.PI / 180d);+ contributions =+ [+ new("linear dimension tolerance", $"{shaft.ParticipantPath}/{bore.ParticipantPath}", variation.LinearToleranceMm),+ new("sheet thickness tolerance", $"{shaft.ParticipantPath}/{bore.ParticipantPath}.Thickness", 2d * variation.ThicknessToleranceMm),+ new("bend location tolerance", $"{shaft.ParticipantPath}/{bore.ParticipantPath}.Bends", 2d * variation.BendLocationToleranceMm),+ new("bend angle envelope", $"{shaft.ParticipantPath}/{bore.ParticipantPath}.Bends", bend),+ new("two coated fit surfaces", $"{shaft.ParticipantPath}/{bore.ParticipantPath}.Coating", 2d * (variation.CoatingThicknessMm + variation.CoatingThicknessToleranceMm))+ ];+ var reduction = contributions.Sum(item => item.WorstCaseClearanceReductionMm);+ var symmetric = reduction - 2d * (variation.CoatingThicknessMm + variation.CoatingThicknessToleranceMm);+ min = nominal - reduction;+ max = nominal + symmetric - 2d * Math.Max(0, variation.CoatingThicknessMm - variation.CoatingThicknessToleranceMm);+ }var compatible = min >= 0;if (!compatible) diagnostics.Add(new(IncompatibleDimensions, $"Mate '{mate.Name}' fit ranges from {min:G6} to {max:G6} {sd.Unit} (nominal {nominal:G6}).", AssemblyDiagnosticSeverity.Warning));- result.Add(new(mate.StableId, nominal, min, max, sd.Unit, compatible));+ result.Add(new(mate.StableId, nominal, min, max, sd.Unit, compatible,+ Classify(nominal, nominal), Classify(min, max), Math.Max(0, -min),+ contributions.OrderByDescending(item => item.WorstCaseClearanceReductionMm).ThenBy(item => item.Source, StringComparer.Ordinal).ToArray(),+ fit.Variation is null ? "toleranced semantic dimensions" : "worst-case analytic interval over authored dimensions, thickness, bend and coating allowances"));}return result;++ static FitClassification Classify(double minimum, double maximum)+ {+ const double engineeringNoiseFloor = 1e-6;+ return minimum > engineeringNoiseFloor ? FitClassification.GuaranteedClearance+ : maximum < -engineeringNoiseFloor ? FitClassification.GuaranteedInterference+ : minimum < -engineeringNoiseFloor ? FitClassification.PossibleInterference+ : FitClassification.PossibleContact;+ }}private static IReadOnlyList<DimensionalRelationIr> LowerInterfaceDimensionalRelations(@@ -473,9 +551,9 @@ public sealed class AssemblyM0Compiler$"dimension-relation:{mate.StableId}:fit-clearance",shaftId,boreId,- boreDimension.Nominal - shaftDimension.Nominal,- boreDimension.LowerTolerance - shaftDimension.UpperTolerance,- boreDimension.UpperTolerance - shaftDimension.LowerTolerance,+ fit.ClearanceScale * (boreDimension.Nominal - shaftDimension.Nominal),+ fit.ClearanceScale * (boreDimension.LowerTolerance - shaftDimension.UpperTolerance),+ fit.ClearanceScale * (boreDimension.UpperTolerance - shaftDimension.LowerTolerance),shaftDimension.Unit,1,OwnerPath(shaftId, instances),diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.csindex 6b5df3c5..36c1bd43 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Models.cs@@ -4,7 +4,8 @@ namespace Aetheris.Kernel.Firmament.Assembly;public enum AssemblyInstanceKind { Assembly, Part, Panel }public enum AssemblyDiagnosticSeverity { Warning, Error }-public enum PlacementConstraintKind { AxisCoincident, AxisAligned, PlaneCoincident, PointCoincident, OffsetAlongAxis }+public enum PlacementConstraintKind { AxisCoincident, AxisAligned, PlaneCoincident, PointCoincident, OffsetAlongAxis, FrameCoincident }+public enum DatumOrientationRelation { SameDirection, OpposedDirection }public enum PlacementStatus { Anchored, Resolved, Underconstrained, Overconstrained, Unresolved }public enum PlacementAuthority { MateDerived, ImportedOccurrence, LegacyExplicit }@@ -17,8 +18,16 @@ public sealed record AssemblyPath(IReadOnlyList<string> Segments)}public sealed record InterfaceRoleDefinition(string Name, IReadOnlyList<string> RequiredCapabilities, int Minimum = 1, int Maximum = 1);-public sealed record InterfaceRequirementDefinition(PlacementConstraintKind Kind, string FirstRole, string FirstMember, string SecondRole, string SecondMember, double OffsetMm = 0);-public sealed record InterfaceFitDefinition(string ShaftRole, string ShaftDimension, string BoreRole, string BoreDimension);+public sealed record AssemblyConceptMemberDefinition(string Name, string Type);+public sealed record AssemblyConceptDefinition(string Name, IReadOnlyList<AssemblyConceptMemberDefinition> Members, SemanticSourceSpan? SourceSpan = null);+public sealed record InterfaceRequirementDefinition(PlacementConstraintKind Kind, string FirstRole, string FirstMember, string SecondRole, string SecondMember, double OffsetMm = 0, DatumOrientationRelation Orientation = DatumOrientationRelation.SameDirection);+public sealed record InterfaceClearancePolicyDefinition(double MinimumClearanceMm, double MaximumClearanceMm);+public sealed record ManufacturingVariationDefinition(double LinearToleranceMm, double ThicknessToleranceMm,+ double BendAngleToleranceDegrees, double BendLocationToleranceMm, double CoatingThicknessMm,+ double CoatingThicknessToleranceMm, double EngagementLengthMm);+public sealed record InterfaceFitDefinition(string ShaftRole, string ShaftDimension, string BoreRole, string BoreDimension,+ double ClearanceScale = 1d, InterfaceClearancePolicyDefinition? Policy = null, ManufacturingVariationDefinition? Variation = null);+public enum FitClassification { GuaranteedClearance, PossibleContact, PossibleInterference, GuaranteedInterference, Unknown }public sealed record InterfaceDefinition(string StableId, string Name, IReadOnlyList<InterfaceRoleDefinition> Roles,IReadOnlyList<InterfaceRequirementDefinition> Requirements,@@ -50,7 +59,8 @@ public sealed record AssemblyDefinitionSource(IReadOnlyList<MateSource>? LocalMates = null,IReadOnlyList<DimensionalRelationSource>? LocalDimensionalRelations = null,IReadOnlyList<ToleranceStackupAssertSource>? LocalStackupAsserts = null,- IReadOnlyList<AssemblyExposedRelationSource>? ExposedRelations = null);+ IReadOnlyList<AssemblyExposedRelationSource>? ExposedRelations = null,+ string? ClaimedConcept = null);public sealed record AssemblyExposedRelationSource(string Name, string PublicFrom, string PublicTo, AssemblyPath InternalFrom, AssemblyPath InternalTo);@@ -87,7 +97,8 @@ public sealed record PanelMateEvidenceIr(string MateStableId,string FirstEdgeStapublic sealed record PlacementConstraintIr(string StableId, PlacementConstraintKind Kind, string MateStableId,string FirstSemanticValueId, string SecondSemanticValueId, double OffsetMm,- double Residual, string Status);+ double Residual, string Status,+ DatumOrientationRelation Orientation = DatumOrientationRelation.SameDirection);public sealed record PlacementResultIr(string InstanceStableId, PlacementStatus Status, AssemblyTransform? Transform, IReadOnlyList<string> FreeTranslations, IReadOnlyList<string> FreeRotations, IReadOnlyList<string> ConstraintIds, PlacementAuthority Authority = PlacementAuthority.MateDerived);public sealed record DimensionalRelationIr(@@ -108,8 +119,17 @@ public sealed record ToleranceStackupResultIr(double Nominal, double WorstCaseMinimum, double WorstCaseMaximum,double RequiredMinimum, string Unit, bool Passed, string Status,IReadOnlyList<StackupContributionIr> Contributions);+public sealed record FitContributionIr(string Source, string SemanticPath, double WorstCaseClearanceReductionMm);public sealed record InterfaceFitResultIr(- string MateStableId, double NominalClearance, double WorstCaseMinimum, double WorstCaseMaximum, string Unit, bool Compatible);+ string MateStableId, double NominalClearance, double WorstCaseMinimum, double WorstCaseMaximum, string Unit, bool Compatible,+ FitClassification NominalState = FitClassification.Unknown,+ FitClassification VariationEnvelopeState = FitClassification.Unknown,+ double MaximumPenetration = 0,+ IReadOnlyList<FitContributionIr>? Contributions = null,+ string Evidence = "dimension-interval");+public sealed record AssemblyDatumIr(string SemanticValueId, string SemanticPath, string Kind, string StableBindingId);+public sealed record DatumMateSolutionIr(string MateStableId, string FirstDatumSemanticValueId, string SecondDatumSemanticValueId,+ DatumOrientationRelation Orientation, int ConstrainedDegreesOfFreedom, string Status, AssemblyTransform? DerivedTransform);public sealed record AssemblyDefinitionIr(string StableId, string DefinitionIdentity, string TemplateName, string SpecializationIdentity,@@ -118,7 +138,11 @@ public sealed record AssemblyDefinitionIr(IReadOnlyList<DimensionalRelationIr> LocalDimensionalRelations,IReadOnlyList<ToleranceStackupResultIr> LocalToleranceStackups,IReadOnlyList<SemanticValue> PublicSemantics, IReadOnlyList<DimensionalRelationIr> PublicDimensionalRelations,- double SolveMilliseconds);+ double SolveMilliseconds,+ IReadOnlyList<PlacementConstraintIr>? LocalPlacementConstraints = null,+ IReadOnlyList<AssemblyDatumIr>? LocalDatums = null,+ IReadOnlyList<DatumMateSolutionIr>? LocalDatumMateSolutions = null,+ IReadOnlyList<InterfaceFitResultIr>? LocalFitResults = null);public sealed record AssemblyPerformanceIr(double ParseMilliseconds, double BindMilliseconds, double MateValidationMilliseconds, double PlacementMilliseconds, double DimensionalGraphMilliseconds, double ToleranceAnalysisMilliseconds, double DefinitionMaterializationMilliseconds = 0, double GeometryExecutionMilliseconds = 0);public sealed record AssemblyGeometryMetricsIr(int Bodies, int Faces, int Edges, int Vertices, double[] Minimum, double[] Maximum);@@ -134,7 +158,9 @@ public sealed record AssemblyIr(IReadOnlyList<ToleranceStackupResultIr> ToleranceStackups, IReadOnlyList<InterfaceFitResultIr> FitResults,IReadOnlyList<AssemblyDiagnostic> Diagnostics,IReadOnlyList<AssemblyDefinitionIr>? AssemblyDefinitions = null,- IReadOnlyList<PanelMateEvidenceIr>? PanelMateEvidence = null);+ IReadOnlyList<PanelMateEvidenceIr>? PanelMateEvidence = null,+ IReadOnlyList<AssemblyDatumIr>? Datums = null,+ IReadOnlyList<DatumMateSolutionIr>? DatumMateSolutions = null);public sealed record AssemblyCompilationResult(AssemblyIr? Ir, IReadOnlyList<AssemblyDiagnostic> Diagnostics, AssemblyPerformanceIr? Performance = null){diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.csindex 832ad58e..a65ab83f 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM0Parser.cs@@ -18,9 +18,10 @@ public sealed class AssemblyM0Parservar watch = Stopwatch.StartNew();var diagnostics = new List<AssemblyDiagnostic>();var source = Regex.Replace(input, @"//[^\r\n]*", string.Empty);+ var concepts = ParseAssemblyConcepts(source, sourceIdentity, diagnostics);var interfaces = ParseInterfaces(source, sourceIdentity, diagnostics);var templateRanges = new List<(int Start, int Length)>();- var assemblyDefinitions = ParseAssemblyDefinitions(source, sourceIdentity, interfaces, diagnostics, templateRanges);+ var assemblyDefinitions = ParseAssemblyDefinitions(source, sourceIdentity, interfaces, concepts, diagnostics, templateRanges);// Template-produced Assembly bodies are declarations, not exported roots.// Blank them without changing offsets, then locate the single root Assembly.var rootSearch = source.ToCharArray();@@ -54,6 +55,21 @@ public sealed class AssemblyM0ParserParseResult Done(AssemblySource? value) { watch.Stop(); return new(value, diagnostics, watch.Elapsed.TotalMilliseconds); }}+ private static IReadOnlyList<AssemblyConceptDefinition> ParseAssemblyConcepts(string source, string sourceIdentity, List<AssemblyDiagnostic> diagnostics)+ {+ var result = new List<AssemblyConceptDefinition>();+ foreach (Match header in Regex.Matches(source, @"\bConcept\s+(?<name>[A-Za-z_]\w*)\s*\{", RegexOptions.CultureInvariant))+ {+ var body = BalancedBody(source, header.Index + header.Length - 1, diagnostics, "Concept");+ if (body is null) continue;+ var members = Regex.Matches(body, @"\b(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>Part|Assembly|Mate|Semantic)\b", RegexOptions.CultureInvariant)+ .Select(match => new AssemblyConceptMemberDefinition(match.Groups["name"].Value, match.Groups["type"].Value)).ToArray();+ if (members.Length > 0)+ result.Add(new(header.Groups["name"].Value, members, SemanticSourceSpan.Generated(sourceIdentity)));+ }+ return result;+ }+private static IReadOnlyList<InterfaceDefinition> ParseInterfaces(string source, string sourceIdentity, List<AssemblyDiagnostic> diagnostics){var result = new List<InterfaceDefinition>();@@ -69,8 +85,21 @@ public sealed class AssemblyM0Parser.Select(m => new InterfaceRequirementDefinition(Enum.Parse<PlacementConstraintKind>(m.Groups["kind"].Value),m.Groups["a"].Value, m.Groups["am"].Value, m.Groups["b"].Value, m.Groups["bm"].Value,m.Groups["offset"].Success ? Number(m.Groups["offset"].Value) : 0)).ToArray();- var fitMatch = Regex.Match(body, @"\bFit\s+(?<a>[A-Za-z_]\w*)\.(?<am>[A-Za-z_]\w*)\s+inside\s+(?<b>[A-Za-z_]\w*)\.(?<bm>[A-Za-z_]\w*)\s*;", RegexOptions.CultureInvariant);- InterfaceFitDefinition? fit = fitMatch.Success ? new(fitMatch.Groups["a"].Value, fitMatch.Groups["am"].Value, fitMatch.Groups["b"].Value, fitMatch.Groups["bm"].Value) : null;+ var frameRequirements = Regex.Matches(body, @"\bLower\s+FrameCoincident\s+(?<a>[A-Za-z_]\w*)(?:\.(?<am>[A-Za-z_]\w*))?\s+(?<b>[A-Za-z_]\w*)(?:\.(?<bm>[A-Za-z_]\w*))?(?:\s+(?<orientation>SameDirection|OpposedDirection))?\s*;", RegexOptions.CultureInvariant)+ .Select(m => new InterfaceRequirementDefinition(PlacementConstraintKind.FrameCoincident,+ m.Groups["a"].Value, m.Groups["am"].Success ? m.Groups["am"].Value : ".",+ m.Groups["b"].Value, m.Groups["bm"].Success ? m.Groups["bm"].Value : ".", 0,+ m.Groups["orientation"].Success ? Enum.Parse<DatumOrientationRelation>(m.Groups["orientation"].Value) : DatumOrientationRelation.SameDirection));+ requirements = requirements.Concat(frameRequirements).ToArray();+ var fitMatch = Regex.Match(body, @"\bFit\s+(?<a>[A-Za-z_]\w*)\.(?<am>[A-Za-z_]\w*)\s+inside\s+(?<b>[A-Za-z_]\w*)\.(?<bm>[A-Za-z_]\w*)(?:\s+(?<perSide>per-side))?\s*;", RegexOptions.CultureInvariant);+ var policyMatch = Regex.Match(body, @"\bClearancePolicy\s+Minimum\s+(?<min>[-+]?\d+(?:\.\d+)?)mm\s+Maximum\s+(?<max>[-+]?\d+(?:\.\d+)?)mm\s*;", RegexOptions.CultureInvariant);+ var variationMatch = Regex.Match(body, @"\bVariation\s+Linear\s+(?<linear>\d+(?:\.\d+)?)mm\s+Thickness\s+(?<thickness>\d+(?:\.\d+)?)mm\s+BendAngle\s+(?<angle>\d+(?:\.\d+)?)deg\s+BendLocation\s+(?<location>\d+(?:\.\d+)?)mm\s+Coating\s+(?<coating>\d+(?:\.\d+)?)mm\s+CoatingTolerance\s+(?<coatingTol>\d+(?:\.\d+)?)mm\s+Engagement\s+(?<engagement>\d+(?:\.\d+)?)mm\s*;", RegexOptions.CultureInvariant);+ var policy = policyMatch.Success ? new InterfaceClearancePolicyDefinition(Number(policyMatch.Groups["min"].Value), Number(policyMatch.Groups["max"].Value)) : null;+ var variation = variationMatch.Success ? new ManufacturingVariationDefinition(Number(variationMatch.Groups["linear"].Value), Number(variationMatch.Groups["thickness"].Value),+ Number(variationMatch.Groups["angle"].Value), Number(variationMatch.Groups["location"].Value), Number(variationMatch.Groups["coating"].Value),+ Number(variationMatch.Groups["coatingTol"].Value), Number(variationMatch.Groups["engagement"].Value)) : null;+ InterfaceFitDefinition? fit = fitMatch.Success ? new(fitMatch.Groups["a"].Value, fitMatch.Groups["am"].Value, fitMatch.Groups["b"].Value, fitMatch.Groups["bm"].Value,+ fitMatch.Groups["perSide"].Success ? .5d : 1d, policy, variation) : null;var free = Regex.Matches(body, @"\bAllow\s+(?<kind>rotation|translation):(?<axis>[A-Za-z-]+)\s*;", RegexOptions.CultureInvariant).Select(m => m.Groups["kind"].Value + ":" + m.Groups["axis"].Value).ToArray();var continuity = Regex.Match(body,@"\bContinuity\s*:\s*(?<value>G0|G1)\s*;",RegexOptions.CultureInvariant);@@ -100,11 +129,12 @@ public sealed class AssemblyM0Parser}private static IReadOnlyList<AssemblyDefinitionSource> ParseAssemblyDefinitions(string source, string sourceIdentity,- IReadOnlyList<InterfaceDefinition> interfaces, List<AssemblyDiagnostic> diagnostics, List<(int Start, int Length)> ranges)+ IReadOnlyList<InterfaceDefinition> interfaces, IReadOnlyList<AssemblyConceptDefinition> concepts,+ List<AssemblyDiagnostic> diagnostics, List<(int Start, int Length)> ranges){var result = new List<AssemblyDefinitionSource>();foreach (Match template in Regex.Matches(source,- @"\bTemplate\s*<\s*(?<parameter>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)\s*>\s*Assembly\s+(?<name>[A-Za-z_]\w*)\s*\{",+ @"\bTemplate\s*<\s*(?<parameter>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)\s*>\s*Assembly\s+(?<name>[A-Za-z_]\w*)(?:\s*:\s*(?<concept>[A-Za-z_]\w*))?\s*\{",RegexOptions.CultureInvariant)){var body = BalancedBody(source, template.Index + template.Length - 1, diagnostics, "Template Assembly");@@ -116,6 +146,7 @@ public sealed class AssemblyM0Parservar exposed = ParseAssemblyExposes(body, root, sourceIdentity, diagnostics);root = root with { ExposedSemantics = exposed, IsEncapsulatedDefinition = true };var name = template.Groups["name"].Value;+ var claimedConcept = template.Groups["concept"].Success ? template.Groups["concept"].Value : null;if (result.Any(item => item.Name == name)){diagnostics.Add(new("assembly-template-duplicate-definition", $"Assembly Template '{name}' is declared more than once."));@@ -131,13 +162,43 @@ public sealed class AssemblyM0Parser.Concat(Regex.Matches(source, @"\bStatic\s+(?<name>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)\s*=\s*\k<type>\s*\{", RegexOptions.CultureInvariant).Select(match => new SemanticProvenance("static-record", match.Groups["name"].Value, match.Groups["type"].Value, SemanticSourceSpan.Generated(sourceIdentity)))).ToArray();+ var localMates = ParseMates(body, sourceIdentity, diagnostics);+ if (claimedConcept is not null)+ ValidateAssemblyConcept(name, claimedConcept, concepts, root, localMates, diagnostics);result.Add(new(name, template.Groups["parameter"].Value, template.Groups["type"].Value, root, name,- [new("assembly-template-definition", name, template.Groups["parameter"].Value + ":" + template.Groups["type"].Value, SemanticSourceSpan.Generated(sourceIdentity)), .. staticProvenance],- anchor, ParseMates(body, sourceIdentity, diagnostics), ParseRelations(body, diagnostics), ParseAsserts(body, sourceIdentity, diagnostics), exposedRelations));+ [new("assembly-template-definition", name, template.Groups["parameter"].Value + ":" + template.Groups["type"].Value, SemanticSourceSpan.Generated(sourceIdentity)),+ .. claimedConcept is null ? [] : new[] { new SemanticProvenance("assembly-concept-satisfaction", claimedConcept, name, SemanticSourceSpan.Generated(sourceIdentity)) },+ .. staticProvenance],+ anchor, localMates, ParseRelations(body, diagnostics), ParseAsserts(body, sourceIdentity, diagnostics), exposedRelations, claimedConcept));}return result;}+ private static void ValidateAssemblyConcept(string templateName, string claimedConcept,+ IReadOnlyList<AssemblyConceptDefinition> concepts, AssemblyMemberSource root, IReadOnlyList<MateSource> mates,+ List<AssemblyDiagnostic> diagnostics)+ {+ var concept = concepts.SingleOrDefault(item => item.Name == claimedConcept);+ if (concept is null)+ {+ diagnostics.Add(new("assembly-concept-unknown", $"Assembly Template '{templateName}' claims unknown Concept '{claimedConcept}'."));+ return;+ }+ foreach (var member in concept.Members)+ {+ var actual = member.Type switch+ {+ "Part" => root.Children.Any(item => item.Name == member.Name && item.Kind == AssemblyInstanceKind.Part),+ "Assembly" => root.Children.Any(item => item.Name == member.Name && item.Kind == AssemblyInstanceKind.Assembly),+ "Mate" => mates.Any(item => item.Name == member.Name),+ "Semantic" => root.ExposedSemantics.Any(item => item.ExposedName == member.Name),+ _ => false+ };+ if (!actual)+ diagnostics.Add(new("assembly-concept-missing-member", $"Assembly Template '{templateName}' does not satisfy Concept '{claimedConcept}': required {member.Type} member '{member.Name}' is missing."));+ }+ }+private static IReadOnlyList<AssemblyExposedRelationSource> ParseExposedRelations(string body){var header = Regex.Match(body, @"\bExpose\s*\{", RegexOptions.CultureInvariant);@@ -155,7 +216,7 @@ public sealed class AssemblyM0Parserif (!header.Success) return [];var block = BalancedBody(body, header.Index + header.Length - 1, diagnostics, "Assembly Expose") ?? string.Empty;var result = new List<SemanticValue>();- foreach (Match expose in Regex.Matches(block, @"\b(?:Semantic|Axis|Plane|Point|Dimension)\s+(?<name>[A-Za-z_]\w*)\s*=\s*(?<path>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*;", RegexOptions.CultureInvariant))+ foreach (Match expose in Regex.Matches(block, @"\b(?:Semantic|Axis|Plane|Point|Dimension|DatumFrame)\s+(?<name>[A-Za-z_]\w*)\s*=\s*(?<path>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*;", RegexOptions.CultureInvariant)){var alias = expose.Groups["name"].Value;if (result.Any(value => value.ExposedName == alias)) { diagnostics.Add(new("assembly-expose-duplicate-name", $"Assembly Expose declares '{alias}' more than once.")); continue; }@@ -191,7 +252,10 @@ public sealed class AssemblyM0ParserAssemblyMemberSource Replace(AssemblyMemberSource item) => item with{Name = item.Name,- DefinitionIdentity = Regex.Replace(item.DefinitionIdentity, $@"(?<prefix>:\s*)\b{Regex.Escape(definition.ParameterName)}\b(?=\s*>)", "${prefix}" + argument),+ // Preserve member projection (for example Spec.Body) so a domain+ // compiler can bind the nested typed Record through its ordinary+ // Template frontend.+ DefinitionIdentity = Regex.Replace(item.DefinitionIdentity, $@"(?<prefix>:\s*)\b{Regex.Escape(definition.ParameterName)}\b", "${prefix}" + argument),Children = item.Children.Select(Replace).ToArray(),Provenance = [.. item.Provenance ?? [], new("assembly-template-specialization", definition.Name, specializationIdentity, SemanticSourceSpan.Generated(sourceIdentity))],IsEncapsulatedDefinition = false@@ -224,7 +288,8 @@ public sealed class AssemblyM0Parservar definitionIr = new AssemblyDefinitionIr(stableId, specializationIdentity, definition.Name, specializationIdentity,[.. definition.Provenance, new("assembly-template-specialization", definition.Name, specializationIdentity, SemanticSourceSpan.Generated(sourceIdentity))],local.Ir.Instances, local.Ir.Mates, local.Ir.Placements, local.Ir.DimensionalRelations, local.Ir.ToleranceStackups,- publicSemantics, publicRelations, watch.Elapsed.TotalMilliseconds);+ publicSemantics, publicRelations, watch.Elapsed.TotalMilliseconds,+ local.Ir.PlacementConstraints, local.Ir.Datums, local.Ir.DatumMateSolutions, local.Ir.FitResults);specializedRoot = specializedRoot with { ExposedSemantics = publicSemantics, IsEncapsulatedDefinition = true, SolvedAssemblyDefinition = definitionIr, DefinitionIdentity = specializationIdentity };specializationCache[specializationIdentity] = specializedRoot;return RenameOccurrence(specializedRoot, occurrenceName);@@ -402,6 +467,14 @@ public sealed class AssemblyM0Parsermembers.Add(new SemanticValue(binding.PointStableId, new("Point"), [new PointCapability()], [binding], exposedName: point.Groups["name"].Value));caps.Add(new PointCapability()); if (!bindings.OfType<ExactPointBinding>().Any()) bindings.Add(binding);}+ foreach (Match frame in Regex.Matches(block, @"\bDatumFrame\s+(?<name>[A-Za-z_]\w*)\s*=\s*\[(?<o>[^]]+)\]\s+x\s*\[(?<x>[^]]+)\]\s+y\s*\[(?<y>[^]]+)\]\s+z\s*\[(?<z>[^]]+)\]\s*;", RegexOptions.CultureInvariant))+ {+ var o = Vector(frame.Groups["o"].Value); var x = Vector(frame.Groups["x"].Value); var y = Vector(frame.Groups["y"].Value); var z = Vector(frame.Groups["z"].Value);+ if (o is null || x is null || y is null || z is null || !ValidFrame(x, y, z)) { diagnostics.Add(new("assembly-datum-frame-invalid", $"Semantic '{name}' DatumFrame requires a finite orthonormal right-handed X/Y/Z basis.")); continue; }+ var binding = new ExactDatumFrameBinding(o[0], o[1], o[2], x[0], x[1], x[2], y[0], y[1], y[2], z[0], z[1], z[2], $"definition:{definition}:{name}:{frame.Groups["name"].Value}");+ members.Add(new SemanticValue(binding.FrameStableId, new("AssemblyDatumFrame"), [new DatumFrameCapability()], [binding], exposedName: frame.Groups["name"].Value));+ caps.Add(new DatumFrameCapability()); if (!bindings.OfType<ExactDatumFrameBinding>().Any()) bindings.Add(binding);+ }foreach (Match dim in Regex.Matches(block, @"\bDimension\s+(?<name>[A-Za-z_]\w*)\s*=\s*(?<nom>[-+]?\d+(?:\.\d+)?)mm(?:\s+tol\s+(?:(?<bil>\d+(?:\.\d+)?)mm|\+(?<plus>\d+(?:\.\d+)?)mm\s+-(?<minus>\d+(?:\.\d+)?)mm))?\s*;", RegexOptions.CultureInvariant)){var plus = dim.Groups["bil"].Success ? Number(dim.Groups["bil"].Value) : dim.Groups["plus"].Success ? Number(dim.Groups["plus"].Value) : 0;@@ -466,6 +539,15 @@ public sealed class AssemblyM0Parser}private static double[]? Vector(string text){ var values = text.Split(',', StringSplitOptions.TrimEntries).Select(x => double.TryParse(x, NumberStyles.Float, CultureInfo.InvariantCulture, out var n) ? n : double.NaN).ToArray(); return values.Length == 3 && values.All(double.IsFinite) ? values : null; }+ private static bool ValidFrame(double[] x, double[] y, double[] z)+ {+ static double Dot(double[] a, double[] b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+ var cross = new[] { x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1] - x[1] * y[0] };+ const double tolerance = 1e-6;+ return Math.Abs(Dot(x, x) - 1) <= tolerance && Math.Abs(Dot(y, y) - 1) <= tolerance && Math.Abs(Dot(z, z) - 1) <= tolerance+ && Math.Abs(Dot(x, y)) <= tolerance && Math.Abs(Dot(x, z)) <= tolerance && Math.Abs(Dot(y, z)) <= tolerance+ && Dot(cross, z) >= 1 - tolerance;+ }private static double Number(string text) => double.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture);}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.csindex f224a8d0..d8aad0c7 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs@@ -26,6 +26,24 @@ public sealed record AssemblyM1CompilationResult(public bool IsSuccess => Ir is not null && Geometry is not null && Diagnostics.All(diagnostic => diagnostic.Severity != AssemblyDiagnosticSeverity.Error);}+/// <summary>+/// Exact part materialization supplied by a domain compiler to the ordinary+/// Assembly pipeline. This is the cross-profile seam used by Sheet Metal: the+/// Assembly compiler continues to own hierarchy, mates, placement and product+/// export, while the owning part compiler remains authoritative for geometry.+/// </summary>+public sealed record AssemblyPartMaterialization(+ BrepBody Body,+ string SpecializationIdentity,+ IReadOnlyList<SemanticProvenance> Provenance,+ IReadOnlyList<SemanticValue>? Semantics = null);++public delegate AssemblyPartMaterialization? AssemblyPartMaterializer(+ string definitionIdentity,+ string? declarationSource,+ string sourceIdentity,+ IList<AssemblyDiagnostic> diagnostics);+internal sealed record MaterializedAssemblyDefinition(string DefinitionIdentity,string SpecializationIdentity,@@ -154,15 +172,26 @@ internal static class AssemblyDefinitionMaterializerpublic sealed class AssemblyM1Pipeline{- public AssemblyM1CompilationResult CompileFile(string path)+ public AssemblyM1CompilationResult CompileFile(string path, AssemblyPartMaterializer? domainMaterializer = null){var parsed = new AssemblyM0Parser().ParseFile(path);+ return CompileParsed(parsed, domainMaterializer);+ }++ public AssemblyM1CompilationResult Compile(string source, string sourceIdentity = "<memory>", AssemblyPartMaterializer? domainMaterializer = null)+ {+ var parsed = new AssemblyM0Parser().Parse(source, sourceIdentity);+ return CompileParsed(parsed, domainMaterializer);+ }++ private static AssemblyM1CompilationResult CompileParsed(AssemblyM0Parser.ParseResult parsed, AssemblyPartMaterializer? domainMaterializer)+ {if (!parsed.IsSuccess || parsed.Source is null) return new(null, null, parsed.Diagnostics);var diagnostics = parsed.Diagnostics.ToList();var materializationWatch = Stopwatch.StartNew();var definitions = parsed.Source.Root.Flatten().Where(member => member.Kind == AssemblyInstanceKind.Part).Select(member => member.DefinitionIdentity).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)- .Select(identity => AssemblyDefinitionMaterializer.TryMaterialize(identity, parsed.Source.DefinitionSource, parsed.Source.SourceIdentity, diagnostics))+ .Select(identity => Materialize(identity, parsed.Source.DefinitionSource, parsed.Source.SourceIdentity, diagnostics, domainMaterializer)).Where(definition => definition is not null).Cast<MaterializedAssemblyDefinition>().ToDictionary(definition => definition.DefinitionIdentity, StringComparer.Ordinal);materializationWatch.Stop();var enriched = parsed.Source with { Root = Enrich(parsed.Source.Root, definitions) };@@ -180,6 +209,23 @@ public sealed class AssemblyM1Pipelinereturn new(validatedIr, geometry, diagnostics, performance);}+ private static MaterializedAssemblyDefinition? Materialize(string identity, string? declarations, string sourceIdentity,+ List<AssemblyDiagnostic> diagnostics, AssemblyPartMaterializer? domainMaterializer)+ {+ if (domainMaterializer?.Invoke(identity, declarations, sourceIdentity, diagnostics) is { } supplied)+ {+ var step = Step242Exporter.ExportBody(supplied.Body);+ var hash = step.IsSuccess+ ? Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value)))+ : Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(identity + supplied.SpecializationIdentity)));+ var stableId = "assembly-definition:" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(identity)))[..16];+ var artifact = new AssemblyDefinitionArtifactIr(stableId, identity, supplied.SpecializationIdentity, hash,+ AssemblyDefinitionMaterializer.Metrics(supplied.Body), supplied.Provenance);+ return new(identity, supplied.SpecializationIdentity, supplied.Body, supplied.Semantics ?? [], artifact);+ }+ return AssemblyDefinitionMaterializer.TryMaterialize(identity, declarations, sourceIdentity, diagnostics);+ }+private static AssemblyMemberSource Enrich(AssemblyMemberSource member, IReadOnlyDictionary<string, MaterializedAssemblyDefinition> definitions){var generated = definitions.TryGetValue(member.DefinitionIdentity, out var definition) ? definition.Semantics : [];@@ -272,6 +318,15 @@ public static class AssemblyWorldQueryvar normal = transform.Apply(new Vector3D(plane.NormalX, plane.NormalY, plane.NormalZ));return new ExactPlaneBinding(origin.X, origin.Y, origin.Z, normal.X, normal.Y, normal.Z, plane.PlaneStableId + ":world:" + instance.StableId);}+ if (value.TryBinding<ExactDatumFrameBinding>(out var frame))+ {+ var origin = transform.Apply(new Point3D(frame.OriginX, frame.OriginY, frame.OriginZ));+ var x = transform.Apply(new Vector3D(frame.XAxisX, frame.XAxisY, frame.XAxisZ));+ var y = transform.Apply(new Vector3D(frame.YAxisX, frame.YAxisY, frame.YAxisZ));+ var z = transform.Apply(new Vector3D(frame.ZAxisX, frame.ZAxisY, frame.ZAxisZ));+ return new ExactDatumFrameBinding(origin.X, origin.Y, origin.Z, x.X, x.Y, x.Z, y.X, y.Y, y.Z, z.X, z.Y, z.Z,+ frame.FrameStableId + ":world:" + instance.StableId);+ }if (value.TryBinding<ExactPointBinding>(out var point)){var world = transform.Apply(new Point3D(point.X, point.Y, point.Z));@@ -291,13 +346,13 @@ public static class AssemblyWorldQueryif (owners.Length != 2 || owners.Any(owner => !materializedInstanceIds.Contains(owner.StableId))) continue;var first = Resolve(ir, constraint.FirstSemanticValueId);var second = Resolve(ir, constraint.SecondSemanticValueId);- var (position, angle) = Residual(constraint.Kind, first, second, constraint.OffsetMm);+ var (position, angle) = Residual(constraint.Kind, first, second, constraint.OffsetMm, constraint.Orientation);result.Add(new(constraint.StableId, constraint.Kind, position, angle, position <= positionToleranceMm && angle <= angularToleranceRadians, "world exact semantic binding over materialized BRep instance"));}return result;}- private static (double Position, double Angle) Residual(PlacementConstraintKind kind, SemanticBinding first, SemanticBinding second, double offset)+ private static (double Position, double Angle) Residual(PlacementConstraintKind kind, SemanticBinding first, SemanticBinding second, double offset, DatumOrientationRelation orientation){if (first is ExactAxisBinding a && second is ExactAxisBinding b){@@ -317,6 +372,14 @@ public static class AssemblyWorldQueryvar delta = new Vector3D(x.X - y.X, x.Y - y.Y, x.Z - y.Z);return (Math.Abs(delta.Length - offset), 0);}+ if (first is ExactDatumFrameBinding f && second is ExactDatumFrameBinding g)+ {+ var delta = new Vector3D(f.OriginX - g.OriginX, f.OriginY - g.OriginY, f.OriginZ - g.OriginZ);+ var fx = Unit(new(f.XAxisX, f.XAxisY, f.XAxisZ)); var gx = Unit(new(g.XAxisX, g.XAxisY, g.XAxisZ));+ var fz = Unit(new(f.ZAxisX, f.ZAxisY, f.ZAxisZ)); var gz = Unit(new(g.ZAxisX, g.ZAxisY, g.ZAxisZ));+ var expectedZDot = orientation == DatumOrientationRelation.OpposedDirection ? -1d : 1d;+ return (delta.Length, Math.Max(Math.Acos(Math.Clamp(fx.Dot(gx), -1, 1)), Math.Acos(Math.Clamp(expectedZDot * fz.Dot(gz), -1, 1))));+ }return (double.PositiveInfinity, double.PositiveInfinity);}diff --git a/Aetheris.Semantics/SemanticModel.cs b/Aetheris.Semantics/SemanticModel.csindex 29a7de0b..7cacae34 100644--- a/Aetheris.Semantics/SemanticModel.cs+++ b/Aetheris.Semantics/SemanticModel.cs@@ -36,6 +36,8 @@ public sealed record PointCapability : ISemanticCapability { public string Namepublic sealed record DimensionalCapability : ISemanticCapability { public string Name => "DimensionalCapable"; }public sealed record CurveCapability : ISemanticCapability { public string Name => "CurveCapable"; }public sealed record BoundaryEdgeCapability : ISemanticCapability { public string Name => "BoundaryEdgeCapable"; }+/// <summary>A fully oriented, authoring-stable rigid assembly datum.</summary>+public sealed record DatumFrameCapability : ISemanticCapability { public string Name => "DatumFrameCapable"; }public sealed class SemanticCapabilitySet{@@ -100,6 +102,18 @@ public sealed record ExactPlaneBinding(double NormalX, double NormalY, double NormalZ,string PlaneStableId) : SemanticBinding("ExactPlane", PlaneStableId);+/// <summary>+/// Exact nominal frame in definition-local millimetres. X/Y/Z are an+/// orthonormal right-handed basis. Unlike a plane, this binds all six rigid+/// placement degrees of freedom without borrowing identity from a BRep face.+/// </summary>+public sealed record ExactDatumFrameBinding(+ double OriginX, double OriginY, double OriginZ,+ double XAxisX, double XAxisY, double XAxisZ,+ double YAxisX, double YAxisY, double YAxisZ,+ double ZAxisX, double ZAxisY, double ZAxisZ,+ string FrameStableId) : SemanticBinding("ExactDatumFrame", FrameStableId);+public sealed record ExactPointBinding(double X, double Y, double Z, string PointStableId): SemanticBinding("ExactPoint", PointStableId);@@ -226,6 +240,7 @@ public static class SemanticValueValidatorRequireBinding<DimensionalCapability, TolerancedDimensionBinding>(value, diagnostics);RequireBinding<CurveCapability, ExactCurveBinding>(value, diagnostics);RequireBinding<BoundaryEdgeCapability, ExactCurveBinding>(value, diagnostics);+ RequireBinding<DatumFrameCapability, ExactDatumFrameBinding>(value, diagnostics);RequireAnyExactBinding<ExactGeometryCapability>(value, diagnostics);RequireAnyExactBinding<SelectableCapability>(value, diagnostics);RequireBinding<ComposeOperandCapability, ExactProfileBinding>(value, diagnostics);@@ -246,7 +261,7 @@ public static class SemanticValueValidatorwhere TCapability : class, ISemanticCapability{if (!value.Capabilities.Supports<TCapability>()) return;- if (!value.Bindings.Any(binding => binding is ExactProfileBinding or ExactBrepBodyBinding or ExactBrepFaceBinding or ExactBrepRegionBinding or ExactCurveBinding or ExactSelectionBinding or ExactAnalysisRegionBinding or ExactPointBinding or ExactAxisBinding or ExactPlaneBinding or TolerancedDimensionBinding))+ if (!value.Bindings.Any(binding => binding is ExactProfileBinding or ExactBrepBodyBinding or ExactBrepFaceBinding or ExactBrepRegionBinding or ExactCurveBinding or ExactSelectionBinding or ExactAnalysisRegionBinding or ExactPointBinding or ExactAxisBinding or ExactPlaneBinding or ExactDatumFrameBinding or TolerancedDimensionBinding))diagnostics.Add(new(NoExactBinding, $"{newCapabilityName<TCapability>()} on '{value.StableIdentity}' requires exact producer evidence.", value.AuthoredSourceSpan));}diff --git a/Aetheris.SheetMetal.Tests/SheetMetalM6Tests.cs b/Aetheris.SheetMetal.Tests/SheetMetalM6Tests.csnew file mode 100644index 00000000..912f3f50--- /dev/null+++ b/Aetheris.SheetMetal.Tests/SheetMetalM6Tests.cs@@ -0,0 +1,87 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.Assembly;+using Xunit;++namespace Aetheris.SheetMetal.Tests;++public sealed class SheetMetalM6Tests+{+ private static EnclosureProductSpec Canonical => new(160, 110, 36, 1.2, 1.2, 1.5, 1, 9);++ [Fact]+ public void UserAssemblyTemplate_ComposesTypedSheetMetalPartsThroughInterfaceAndMates()+ {+ var source = File.ReadAllText(Path.Combine(Root(), "fixtures/FirmamentV2/SheetMetal/m7-network-appliance-product.firmasm"));+ var product = EnclosureProductFamilies.Compile(source, Canonical, "m6-network-appliance-product.firmasm");++ Assert.True(product.Assembly.IsSuccess, Evidence(product));+ Assert.Equal(["Body", "Lid"], product.Assembly.Ir!.Instances.Where(item => item.Kind == AssemblyInstanceKind.Part).Select(item => item.Path.Segments.Last()).Order().ToArray());+ var definition = product.Assembly.Ir.AssemblyDefinitions!.Single();+ Assert.Equal(["Attachments", "Closure"], definition.LocalMates.Select(item => item.Name).Order().ToArray());+ Assert.All(definition.LocalMates, item => Assert.Equal("valid", item.ValidationStatus));+ Assert.Contains(definition.Provenance, item => item.Stage == "assembly-concept-satisfaction" && item.Identity == "EnclosureProduct");+ Assert.Equal(2, product.Assembly.Geometry!.Artifact.Definitions.Count);+ Assert.Equal(SheetMetalDfmStatus.Pass, product.Dfm.Overall);+ Assert.Contains(product.Dfm.Findings, item => item.RuleId == "assembly-dfm-lid-clearance" && Math.Abs(item.Measured!.Value - 1) < 1e-9);+ Assert.Contains(product.SemanticPaths, item => item == "Product.Body.FrontLip");+ Assert.NotNull(product.Body.FlatPattern.ExactBlankContour); Assert.NotNull(product.Lid.FlatPattern.ExactBlankContour);+ Assert.Equal(9, product.Body.FlatPattern.CutLoops.Count); Assert.Single(product.Lid.FlatPattern.CutLoops);+ Assert.Contains(product.Body.SemanticPaths, item => item.Path == "Rear.RearEthernet");+ Assert.Contains(product.Lid.SemanticPaths, item => item.Path == "Top.LidMountA");+ }++ [Fact]+ public void ForgeFacingCall_UsesSameTemplateAndExportsManufacturingPackageAndAp242Hierarchy()+ {+ var first = EnclosureProductFamilies.MakeEnclosureProduct(Canonical, "NetworkApplianceA");+ var second = EnclosureProductFamilies.MakeEnclosureProduct(Canonical with { Width = 190, Depth = 125 }, "NetworkApplianceB");+ Assert.Equal(first.SemanticPaths.Select(Shape), second.SemanticPaths.Select(Shape));+ Assert.NotEqual(first.SpecializationIdentity, second.SpecializationIdentity);+ Assert.Equal(first.Assembly.Geometry!.Artifact.DeterministicSha256,+ EnclosureProductFamilies.MakeEnclosureProduct(Canonical, "NetworkApplianceA").Assembly.Geometry!.Artifact.DeterministicSha256);++ var requestedArtifacts = Environment.GetEnvironmentVariable("AETHERIS_M6_ARTIFACTS");+ var directory = requestedArtifacts is null ? Path.Combine(Path.GetTempPath(), "aetheris-m6-" + Guid.NewGuid().ToString("N")) : Path.GetFullPath(requestedArtifacts);+ try+ {+ var artifacts = first.Export(directory);+ Assert.All(new[] { artifacts.AssemblyStep, artifacts.BodyFormedStep, artifacts.BodyFlatStep, artifacts.BodyFlatSvg, artifacts.LidFormedStep, artifacts.LidFlatStep, artifacts.LidFlatSvg, artifacts.ProductDfmJson, artifacts.FitReportJson }, path => Assert.True(File.Exists(path), path));+ var imported = Step242AssemblyImporter.Import(File.ReadAllText(artifacts.AssemblyStep));+ Assert.True(imported.IsSuccess, string.Join("; ", imported.Diagnostics.Select(item => item.Message)));+ Assert.Equal(2, imported.Value.Definitions.Count(item => item.Geometry is not null));+ Assert.Contains(imported.Value.Occurrences, item => item.Name == "Body");+ Assert.Contains(imported.Value.Occurrences, item => item.Name == "Lid");+ foreach (var path in new[] { artifacts.BodyFormedStep, artifacts.BodyFlatStep, artifacts.LidFormedStep, artifacts.LidFlatStep })+ {+ var body = Step242Importer.ImportBody(File.ReadAllText(path));+ Assert.True(body.IsSuccess); Assert.True(BrepExportPreflight.Validate(body.Value).IsValid);+ }+ }+ finally { if (requestedArtifacts is null && Directory.Exists(directory)) Directory.Delete(directory, true); }+ }++ [Fact]+ public void MissingProductConceptMember_IsTypedParserDiagnosticBeforeGeometry()+ {+ var source = File.ReadAllText(Path.Combine(Root(), "fixtures/FirmamentV2/SheetMetal/m7-network-appliance-product.firmasm"))+ .Replace("<Part Lid = RemovablePanLid<Spec: Spec.Lid>>", "<Part Cover = RemovablePanLid<Spec: Spec.Lid>>", StringComparison.Ordinal);+ var parsed = new AssemblyM0Parser().Parse(source);+ Assert.False(parsed.IsSuccess);+ Assert.Contains(parsed.Diagnostics, item => item.Code == "assembly-concept-missing-member" && item.Message.Contains("Lid", StringComparison.Ordinal));+ }++ [Fact]+ public void ClearanceViolation_IsSemanticProductDfmFailureWithRepairablePath()+ {+ var product = EnclosureProductFamilies.MakeEnclosureProduct(Canonical with { LidClearance = .2 }, "BadClearance");+ var finding = Assert.Single(product.Dfm.Findings, item => item.RuleId == "assembly-dfm-lid-clearance");+ Assert.Equal(SheetMetalDfmStatus.Fail, finding.Status); Assert.Equal("Product.Closure", finding.SemanticPath);+ var repaired = EnclosureProductFamilies.MakeEnclosureProduct(Canonical, "RepairedClearance");+ Assert.Equal(SheetMetalDfmStatus.Pass, repaired.Dfm.Findings.Single(item => item.RuleId == "assembly-dfm-lid-clearance").Status);+ }++ private static string Shape(string path) => path.Replace("NetworkApplianceA", "Product", StringComparison.Ordinal).Replace("NetworkApplianceB", "Product", StringComparison.Ordinal);+ private static string Evidence(ManufacturedEnclosureProduct product) => string.Join(Environment.NewLine, product.Assembly.Diagnostics.Select(item => item.Code + ": " + item.Message));+ private static string Root() { var directory = new DirectoryInfo(AppContext.BaseDirectory); while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent; return directory?.FullName ?? throw new InvalidOperationException(); }+}diff --git a/Aetheris.SheetMetal.Tests/SheetMetalM7Tests.cs b/Aetheris.SheetMetal.Tests/SheetMetalM7Tests.csnew file mode 100644index 00000000..dae4b92d--- /dev/null+++ b/Aetheris.SheetMetal.Tests/SheetMetalM7Tests.cs@@ -0,0 +1,82 @@+using Aetheris.Kernel.Firmament.Assembly;+using Xunit;++namespace Aetheris.SheetMetal.Tests;++public sealed class SheetMetalM7Tests+{+ private static EnclosureProductSpec Canonical => new(160, 110, 36, 1.2, 1.2, 1.5, 1, 9);++ [Fact]+ public void NetworkAppliance_UsesRegisteredSemanticFramesAndCorrectedPlacement()+ {+ var source = File.ReadAllText(Path.Combine(Root(), "fixtures/FirmamentV2/SheetMetal/m7-network-appliance-product.firmasm"));+ var product = EnclosureProductFamilies.Compile(source, Canonical, "m7-network-appliance-product.firmasm");+ var definition = Assert.Single(product.Assembly.Ir!.AssemblyDefinitions!);+ var solution = Assert.Single(definition.LocalDatumMateSolutions!);+ Assert.Equal(DatumOrientationRelation.OpposedDirection, solution.Orientation);+ Assert.Equal(6, solution.ConstrainedDegreesOfFreedom);+ var lid = product.Assembly.Ir.Instances.Single(item => item.Path.Segments.Last() == "Lid");+ Assert.Equal(PlacementAuthority.MateDerived, lid.PlacementAuthority);+ Assert.Equal(-1, lid.ResolvedTransform!.Matrix[12], 6);+ Assert.Equal(-1, lid.ResolvedTransform.Matrix[13], 6);+ Assert.Equal(41.4, lid.ResolvedTransform.Matrix[14], 5);+ Assert.Contains(definition.LocalDatums!, item => item.SemanticPath.EndsWith("Body.Datums.LidSeat", StringComparison.Ordinal));+ Assert.Contains(definition.LocalDatums!, item => item.SemanticPath.EndsWith("Lid.Datums.BodySeat", StringComparison.Ordinal));+ if (Environment.GetEnvironmentVariable("AETHERIS_M7_ARTIFACTS") is { } artifactDirectory)+ product.Export(artifactDirectory);+ }++ [Fact]+ public void M6ReferenceFixture_ReproducesDetachedUnderregisteredClosure()+ {+ var source = File.ReadAllText(Path.Combine(Root(), "fixtures/FirmamentV2/SheetMetal/m6-network-appliance-product.firmasm"));+ var product = EnclosureProductFamilies.Compile(source, Canonical, "m6-reference-network-appliance.firmasm");+ var definition = Assert.Single(product.Assembly.Ir!.AssemblyDefinitions!);+ Assert.Empty(definition.LocalDatumMateSolutions ?? []);+ var localLid = definition.LocalInstances.Single(item => item.Path.Segments.Last() == "Lid");+ Assert.Equal(36, localLid.ResolvedTransform!.Matrix[14], 6);+ var bodyGeometry = product.Assembly.Geometry!.Artifact.Instances.Single(item => item.InstanceStableId.EndsWith(".Body", StringComparison.Ordinal));+ Assert.Equal(41.4, bodyGeometry.Metrics.Maximum[2], 6);+ Assert.Equal(5.4, bodyGeometry.Metrics.Maximum[2] - localLid.ResolvedTransform.Matrix[14], 6);+ }++ [Fact]+ public void ManufacturingVariation_ChangesFitWithoutChangingNominalGeometry()+ {+ var baseline = EnclosureProductFamilies.MakeEnclosureProduct(Canonical, "BaselineFit");+ var coated = EnclosureProductFamilies.MakeEnclosureProduct(Canonical with+ {+ ProductionVariation = new(CoatingThickness: .25, CoatingThicknessTolerance: .05)+ }, "CoatedFit");+ Assert.Equal(FitClassification.GuaranteedClearance, baseline.Fit.VariationEnvelopeState);+ Assert.Equal(FitClassification.PossibleInterference, coated.Fit.VariationEnvelopeState);+ Assert.Equal(baseline.Assembly.Geometry!.Artifact.Definitions.Select(item => item.StepSha256).Order(), coated.Assembly.Geometry!.Artifact.Definitions.Select(item => item.StepSha256).Order());+ Assert.Contains(coated.Fit.DominantContributions, item => item.Source.Contains("coated", StringComparison.Ordinal));+ }++ [Fact]+ public void FitClassification_CoversGuaranteedClearancePossibleAndGuaranteedInterference()+ {+ var clear = EnclosureProductFamilies.MakeEnclosureProduct(Canonical with+ {+ LidClearance = 2,+ ProductionVariation = new(.05, .02, .1, .02, 0, 0)+ }, "LooseFit");+ var possible = EnclosureProductFamilies.MakeEnclosureProduct(Canonical with+ {+ ProductionVariation = new(CoatingThickness: .25, CoatingThicknessTolerance: .05)+ }, "RiskFit");+ var interference = EnclosureProductFamilies.MakeEnclosureProduct(Canonical with+ {+ LidClearance = .2,+ ProductionVariation = new(.05, .02, .1, .02, 1, .05)+ }, "InterferenceFit");+ Assert.Equal(FitClassification.GuaranteedClearance, clear.Fit.VariationEnvelopeState);+ Assert.Equal(FitClassification.PossibleInterference, possible.Fit.VariationEnvelopeState);+ Assert.Equal(FitClassification.GuaranteedInterference, interference.Fit.VariationEnvelopeState);+ Assert.True(interference.Fit.MaximumPenetrationMm > 0);+ }++ private static string Root() { var directory = new DirectoryInfo(AppContext.BaseDirectory); while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent; return directory?.FullName ?? throw new InvalidOperationException(); }+}diff --git a/Aetheris.SheetMetal/EnclosureProductM6.cs b/Aetheris.SheetMetal/EnclosureProductM6.csnew file mode 100644index 00000000..4d2c3a3f--- /dev/null+++ b/Aetheris.SheetMetal/EnclosureProductM6.cs@@ -0,0 +1,350 @@+using System.Globalization;+using System.Security.Cryptography;+using System.Text;+using System.Text.RegularExpressions;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.Assembly;+using Aetheris.Semantics;++namespace Aetheris.SheetMetal;++public sealed record EnclosureProductSpec(+ double Width,+ double Depth,+ double Height,+ double BodyThickness,+ double LidThickness,+ double InsideRadius,+ double LidClearance,+ double LidOverlap,+ double MinimumClearance = 0.4,+ double MaximumClearance = 1.5,+ double FastenerDiameter = 3.2,+ double KFactor = .42,+ SheetReliefPolicy ReliefPolicy = SheetReliefPolicy.Rectangular,+ SheetMetalProductionVariation? ProductionVariation = null);++public sealed record SheetMetalProductionVariation(+ double LinearTolerance = .1,+ double ThicknessTolerance = .08,+ double BendAngleToleranceDegrees = .5,+ double BendLocationTolerance = .1,+ double CoatingThickness = 0,+ double CoatingThicknessTolerance = 0);++public sealed record FitToleranceContribution(string Source, string SemanticPath, double WorstCaseClearanceReductionMm);+public sealed record EnclosureFitEvidence(+ string InterfacePath,+ double NominalMinimumSeparationMm,+ double MinimumPossibleSeparationMm,+ double MaximumPossibleSeparationMm,+ double MaximumPenetrationMm,+ double OverlapVolumeLowerBoundMm3,+ double? ContactAreaMm2,+ string ContactEvidence,+ string OverlapEvidence,+ FitClassification NominalState,+ FitClassification VariationEnvelopeState,+ IReadOnlyList<FitToleranceContribution> DominantContributions);++public enum ProductDfmFindingKind { Part, Interface, Assembly }++public sealed record ProductDfmFinding(+ ProductDfmFindingKind Kind,+ string RuleId,+ SheetMetalDfmStatus Status,+ string SemanticPath,+ string Message,+ double? Measured = null,+ double? Required = null);++public sealed record EnclosureProductDfmReport(IReadOnlyList<ProductDfmFinding> Findings)+{+ public SheetMetalDfmStatus Overall => Findings.Any(item => item.Status == SheetMetalDfmStatus.Fail)+ ? SheetMetalDfmStatus.Fail+ : Findings.Any(item => item.Status == SheetMetalDfmStatus.Warning)+ ? SheetMetalDfmStatus.Warning+ : SheetMetalDfmStatus.Pass;+}++public sealed record EnclosureProductBomItem(string SemanticPath, string Definition, int Quantity);++public sealed record EnclosureProductArtifacts(+ string AssemblyStep,+ string BodyFormedStep,+ string BodyFlatStep,+ string BodyFlatSvg,+ string LidFormedStep,+ string LidFlatStep,+ string LidFlatSvg,+ string ProductDfmJson,+ string FitReportJson);++public sealed record ManufacturedEnclosureProduct(+ string TemplateName,+ string SpecializationIdentity,+ EnclosureProductSpec Spec,+ string FirmamentSource,+ AssemblyM1CompilationResult Assembly,+ ManufacturedSheetMetalResult Body,+ ManufacturedSheetMetalResult Lid,+ EnclosureProductDfmReport Dfm,+ EnclosureFitEvidence Fit,+ IReadOnlyList<string> SemanticPaths,+ IReadOnlyList<EnclosureProductBomItem> Bom)+{+ public EnclosureProductArtifacts Export(string directory)+ {+ var root = Path.GetFullPath(directory); Directory.CreateDirectory(root);+ var assembly = AssemblyIrAp242Exporter.Export(Assembly);+ if (!assembly.IsSuccess) throw new InvalidOperationException(string.Join("; ", assembly.Diagnostics.Select(item => item.Message)));+ var assemblyPath = Write("NetworkAppliance.step", assembly.Value);+ var bodyFormed = Formed("Body", Body); var lidFormed = Formed("Lid", Lid);+ var bodyFlat = Flat("Body", Body); var lidFlat = Flat("Lid", Lid);+ var bodySvg = Write("Body.flat.svg", Body.FlatSvg); var lidSvg = Write("Lid.flat.svg", Lid.FlatSvg);+ var options = new System.Text.Json.JsonSerializerOptions { WriteIndented = true };+ options.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());+ var dfm = Write("product-dfm.json", System.Text.Json.JsonSerializer.Serialize(Dfm, options));+ var fit = Write("fit-report.json", System.Text.Json.JsonSerializer.Serialize(Fit, options));+ return new(assemblyPath, bodyFormed, bodyFlat, bodySvg, lidFormed, lidFlat, lidSvg, dfm, fit);++ string Formed(string name, ManufacturedSheetMetalResult part)+ {+ var exported = Step242Exporter.ExportBody(part.Part.FormedBody!);+ if (!exported.IsSuccess) throw new InvalidOperationException(string.Join("; ", exported.Diagnostics.Select(item => item.Message)));+ return Write(name + ".formed.step", exported.Value);+ }+ string Flat(string name, ManufacturedSheetMetalResult part)+ {+ var path = Path.Combine(root, name + ".flat.step");+ if (!SheetMetalManufacturingArtifacts.WriteFlatStep(path, part.Part, part.FlatPattern, out var diagnostics))+ throw new InvalidOperationException(string.Join("; ", diagnostics.Select(item => item.Message)));+ return path;+ }+ string Write(string name, string content) { var path = Path.Combine(root, name); File.WriteAllText(path, content, new UTF8Encoding(false)); return path; }+ }+}++/// <summary>+/// Forge-facing product call. It specializes the same user-authored Firmament+/// Assembly Template and delegates Body/Lid geometry to the ordinary Sheet Metal+/// Template compiler through Assembly's domain-materialization seam.+/// </summary>+public static class EnclosureProductFamilies+{+ public static ManufacturedEnclosureProduct MakeEnclosureProduct(EnclosureProductSpec spec, string instanceName = "EnclosureProduct")+ => Compile(BuildSource(spec, instanceName), spec, "product:" + instanceName);++ public static ManufacturedEnclosureProduct Compile(string source, EnclosureProductSpec spec, string sourceIdentity = "<enclosure-product>")+ {+ Validate(spec);+ var parts = new Dictionary<string, ManufacturedSheetMetalResult>(StringComparer.Ordinal);+ AssemblyPartMaterialization? Materialize(string identity, string? declarations, string identitySource, IList<AssemblyDiagnostic> diagnostics)+ {+ var result = MaterializeAssemblyPartCore(identity, declarations, identitySource, diagnostics, out var manufactured, out var concreteName);+ if (manufactured is not null) parts[concreteName] = manufactured;+ return result;+ }++ var assembly = new AssemblyM1Pipeline().Compile(source, sourceIdentity, Materialize);+ if (!assembly.IsSuccess)+ throw new InvalidOperationException("Firmament enclosure product failed: " + string.Join("; ", assembly.Diagnostics.Select(item => item.Code + ": " + item.Message)));+ var body = parts["AssemblyBody"]; var lid = parts["AssemblyLid"];+ var fit = AnalyzeFit(spec, assembly);+ var findings = ProductDfm(spec, assembly, body, lid, fit);+ var paths = assembly.Ir!.Instances.Select(item => item.Path.ToString())+ .Concat(["Product.Body.Front", "Product.Body.Rear", "Product.Body.FrontLip", "Product.Lid.Top", "Product.Lid.Front", "Product.Closure", "Product.Attachments"])+ .Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();+ var identity = assembly.Ir.AssemblyDefinitions?.SingleOrDefault()?.SpecializationIdentity+ ?? "ElectronicsEnclosureProduct<Spec>";+ return new("ElectronicsEnclosureProduct", identity, spec, source, assembly, body, lid, new(findings), fit, paths,+ [new("Product.Body", body.SpecializationIdentity, 1), new("Product.Lid", lid.SpecializationIdentity, 1), new("Product.Attachments.M3", "ISO4762-placeholder", 4)]);+ }++ /// <summary>CLI/host adapter for Sheet Metal definitions encountered by the generic Assembly pipeline.</summary>+ public static AssemblyPartMaterialization? MaterializeAssemblyPart(string identity, string? declarations, string sourceIdentity, IList<AssemblyDiagnostic> diagnostics)+ => MaterializeAssemblyPartCore(identity, declarations, sourceIdentity, diagnostics, out _, out _);++ private static AssemblyPartMaterialization? MaterializeAssemblyPartCore(string identity, string? declarations, string sourceIdentity,+ IList<AssemblyDiagnostic> diagnostics, out ManufacturedSheetMetalResult? manufactured, out string concreteName)+ {+ manufactured = null; concreteName = string.Empty;+ if (!identity.StartsWith("ElectronicsEnclosure<", StringComparison.Ordinal)+ && !identity.StartsWith("RemovablePanLid<", StringComparison.Ordinal)) return null;+ var resolved = ResolveProjectedRecord(identity, declarations ?? string.Empty);+ concreteName = "Assembly" + (resolved.StartsWith("ElectronicsEnclosure", StringComparison.Ordinal) ? "Body" : "Lid");+ var partDeclarations = Regex.Replace(declarations ?? string.Empty, @"\bConcept\s+EnclosureProduct\s*\{[^}]*\}", string.Empty, RegexOptions.CultureInvariant);+ partDeclarations = Regex.Replace(partDeclarations, @"\bRecord\s+EnclosureProductSpec\s*\{[^}]*\}", string.Empty, RegexOptions.CultureInvariant);+ partDeclarations = Regex.Replace(partDeclarations, @"\bStatic\s+\w+\s*:\s*EnclosureProductSpec\s*=\s*EnclosureProductSpec\s*\{[^}]*\}", string.Empty, RegexOptions.CultureInvariant);+ partDeclarations = SelectPartExtensions(partDeclarations, concreteName.EndsWith("Body", StringComparison.Ordinal) ? "Body" : "Lid", concreteName);+ var concreteSource = partDeclarations + Environment.NewLine + $"SheetMetal {concreteName} = {resolved}" + Environment.NewLine;+ var compiled = SheetMetalFirmament.Compile(concreteSource, sourceIdentity + "#" + concreteName);+ if (!compiled.IsSuccess || compiled.Part?.FormedBody is null || compiled.FlatPattern is null)+ {+ foreach (var item in compiled.Diagnostics)+ diagnostics.Add(new("assembly-sheetmetal-materialization-failed", $"{identity}: {item.Code}: {item.Message}"));+ return null;+ }+ var specialization = compiled.TemplateInstantiations?.LastOrDefault()?.SpecializationIdentity ?? resolved;+ manufactured = new ManufacturedSheetMetalResult(+ resolved.StartsWith("ElectronicsEnclosure", StringComparison.Ordinal) ? "ElectronicsEnclosure" : "RemovablePanLid",+ specialization, compiled, SheetMetalDfm.Evaluate(compiled.Part, compiled.FlatPattern),+ SheetMetalConceptPaths.Inspect(compiled.Spec!, compiled.Part, compiled.FlatPattern),+ SheetMetalFabricationArtifacts.Create(compiled.Part, compiled.FlatPattern), SheetMetalSvgRenderer.Render(compiled.FlatPattern));+ return new(compiled.Part.FormedBody, specialization,+ [new SemanticProvenance("sheetmetal-template-specialization", specialization, resolved, SemanticSourceSpan.Generated(sourceIdentity))]);+ }++ private static IReadOnlyList<ProductDfmFinding> ProductDfm(EnclosureProductSpec spec, AssemblyM1CompilationResult assembly,+ ManufacturedSheetMetalResult body, ManufacturedSheetMetalResult lid, EnclosureFitEvidence fit)+ {+ var findings = body.Dfm.Findings.Select(item => new ProductDfmFinding(ProductDfmFindingKind.Part, item.RuleId, item.Status,+ "Product.Body" + (item.SubjectId is null ? string.Empty : "." + item.SubjectId), item.Message, item.Measured, item.Required))+ .Concat(lid.Dfm.Findings.Select(item => new ProductDfmFinding(ProductDfmFindingKind.Part, item.RuleId, item.Status,+ "Product.Lid" + (item.SubjectId is null ? string.Empty : "." + item.SubjectId), item.Message, item.Measured, item.Required))).ToList();+ var bodyInstance = assembly.Ir!.Instances.Single(item => item.Kind == AssemblyInstanceKind.Part && item.Path.Segments.Last() == "Body");+ var lidInstance = assembly.Ir.Instances.Single(item => item.Kind == AssemblyInstanceKind.Part && item.Path.Segments.Last() == "Lid");+ var geometryByInstance = assembly.Geometry!.Artifact.Instances.ToDictionary(item => item.InstanceStableId, StringComparer.Ordinal);+ var bodyBounds = geometryByInstance[bodyInstance.StableId].Metrics; var lidBounds = geometryByInstance[lidInstance.StableId].Metrics;+ var measured = new[] { bodyBounds.Minimum[0] - lidBounds.Minimum[0], lidBounds.Maximum[0] - bodyBounds.Maximum[0], bodyBounds.Minimum[1] - lidBounds.Minimum[1], lidBounds.Maximum[1] - bodyBounds.Maximum[1] }.Min();+ var clearancePass = measured >= spec.MinimumClearance && measured <= spec.MaximumClearance;+ findings.Add(new(ProductDfmFindingKind.Interface, "assembly-dfm-lid-clearance", clearancePass ? SheetMetalDfmStatus.Pass : SheetMetalDfmStatus.Fail,+ "Product.Closure", $"Authored nominal clearance is {spec.LidClearance:G4} mm; derived formed-envelope side clearance is {measured:G4} mm (policy {spec.MinimumClearance:G4}..{spec.MaximumClearance:G4} mm).", measured, spec.MinimumClearance));+ findings.Add(new(ProductDfmFindingKind.Interface, "assembly-dfm-tolerance-aware-fit",+ fit.VariationEnvelopeState == FitClassification.GuaranteedClearance ? SheetMetalDfmStatus.Pass : SheetMetalDfmStatus.Warning,+ fit.InterfacePath, $"Nominal {fit.NominalState}; production envelope {fit.VariationEnvelopeState} ({fit.MinimumPossibleSeparationMm:G4}..{fit.MaximumPossibleSeparationMm:G4} mm).",+ fit.MinimumPossibleSeparationMm, 0));+ findings.Add(new(ProductDfmFindingKind.Interface, "assembly-dfm-required-overlap", spec.LidOverlap > 0 ? SheetMetalDfmStatus.Pass : SheetMetalDfmStatus.Fail,+ "Product.Closure", $"Required lid/body overlap is {spec.LidOverlap:G4} mm.", spec.LidOverlap, double.Epsilon));+ var interference = assembly.Diagnostics.Any(item => item.Code == "assembly-solid-volume-interference");+ findings.Add(new(ProductDfmFindingKind.Assembly, "assembly-dfm-solid-interference", interference ? SheetMetalDfmStatus.Fail : SheetMetalDfmStatus.Pass,+ "Product.Body↔Product.Lid", interference ? "Exact BRep evidence found positive-volume penetration." : "Exact BRep evidence found no unintended positive-volume penetration."));+ var bodyHole = bodyInstance.SemanticRoot.ExposedMembers["Attachments"].ExposedMembers["HoleA"];+ var lidHole = lidInstance.SemanticRoot.ExposedMembers["Attachments"].ExposedMembers["HoleA"];+ var bodyPoint = (ExactPointBinding)AssemblyWorldQuery.Resolve(assembly.Ir, bodyHole.StableIdentity);+ var lidPoint = (ExactPointBinding)AssemblyWorldQuery.Resolve(assembly.Ir, lidHole.StableIdentity);+ var attachmentResidual = Math.Sqrt(Math.Pow(bodyPoint.X - lidPoint.X, 2) + Math.Pow(bodyPoint.Y - lidPoint.Y, 2) + Math.Pow(bodyPoint.Z - lidPoint.Z, 2));+ findings.Add(new(ProductDfmFindingKind.Interface, "assembly-dfm-attachment-alignment", attachmentResidual <= 1e-5 ? SheetMetalDfmStatus.Pass : SheetMetalDfmStatus.Fail,+ "Product.Attachments.HoleA", $"Corresponding body/lid attachment point residual is {attachmentResidual:G6} mm for nominal M{spec.FastenerDiameter:G3} placeholder screws.", attachmentResidual, 1e-5));+ findings.Add(new(ProductDfmFindingKind.Assembly, "assembly-dfm-service-removal", !interference ? SheetMetalDfmStatus.Pass : SheetMetalDfmStatus.Fail,+ "Product.Lid.ServiceDirection", "Bounded translational removal along +Z is unobstructed at the closed-position interference proof; general motion planning is not inferred."));+ return findings.OrderBy(item => item.Kind).ThenBy(item => item.SemanticPath, StringComparer.Ordinal).ThenBy(item => item.RuleId, StringComparer.Ordinal).ToArray();+ }++ private static EnclosureFitEvidence AnalyzeFit(EnclosureProductSpec spec, AssemblyM1CompilationResult assembly)+ {+ var fit = (assembly.Ir?.FitResults ?? []).Concat((assembly.Ir?.AssemblyDefinitions ?? []).SelectMany(definition => definition.LocalFitResults ?? [])).Single();+ var contributions = (fit.Contributions ?? []).Where(item => item.WorstCaseClearanceReductionMm > 0)+ .Select(item => new FitToleranceContribution(item.Source, item.SemanticPath, item.WorstCaseClearanceReductionMm)).ToArray();+ var frameSolutions = (assembly.Ir?.DatumMateSolutions ?? []).Concat((assembly.Ir?.AssemblyDefinitions ?? []).SelectMany(definition => definition.LocalDatumMateSolutions ?? [])).ToArray();+ var frameContact = frameSolutions.Length > 0 && frameSolutions.All(item => item.Status == "resolved" && item.ConstrainedDegreesOfFreedom == 6);+ return new("Product.Closure.Body.LidSeat↔Product.Closure.Lid.BodySeat", fit.NominalClearance, fit.WorstCaseMinimum, fit.WorstCaseMaximum,+ fit.MaximumPenetration, 0, null,+ frameContact ? "Intended seating relation certified by coincident semantic DatumFrames; contact area is not certified." : "No certified seating-contact witness.",+ "Nominal positive-volume overlap is checked by BrepSolidInterference. Tolerance penetration is an analytic conservative bound; no arbitrary-BRep Boolean volume is claimed.",+ fit.NominalState, fit.VariationEnvelopeState, contributions);+ }++ private static string ResolveProjectedRecord(string identity, string declarations)+ {+ var application = Regex.Match(identity, @"^(?<template>\w+)<Spec:\s*(?<outer>\w+)\.(?<field>\w+)>$", RegexOptions.CultureInvariant);+ if (!application.Success) return identity;+ var record = Regex.Match(declarations, $@"\bStatic\s+{Regex.Escape(application.Groups["outer"].Value)}\s*:\s*\w+\s*=\s*\w+\s*\{{(?<body>.*?)\}}", RegexOptions.Singleline | RegexOptions.CultureInvariant);+ var field = record.Success ? Regex.Match(record.Groups["body"].Value, $@"\b{Regex.Escape(application.Groups["field"].Value)}\s*:\s*(?<value>\w+)", RegexOptions.CultureInvariant) : Match.Empty;+ if (!field.Success) throw new InvalidOperationException($"Projected product Record argument '{application.Groups["outer"].Value}.{application.Groups["field"].Value}' could not be resolved.");+ return $"{application.Groups["template"].Value}<Spec: {field.Groups["value"].Value}>";+ }++ private static string SelectPartExtensions(string source, string semanticPartName, string concreteName)+ {+ var chars = source.ToCharArray(); var selected = new List<string>();+ foreach (Match header in Regex.Matches(source, @"\bExtend\s+SheetMetal\s+(?<name>\w+)\s*\{", RegexOptions.CultureInvariant))+ {+ var open = header.Index + header.Length - 1; var depth = 0; var close = -1;+ for (var index = open; index < source.Length; index++)+ {+ if (source[index] == '{') depth++;+ else if (source[index] == '}' && --depth == 0) { close = index; break; }+ }+ if (close < 0) continue;+ if (header.Groups["name"].Value == semanticPartName)+ selected.Add("Extend SheetMetal " + concreteName + source[(open - 1)..(close + 1)].TrimStart());+ Array.Fill(chars, ' ', header.Index, close - header.Index + 1);+ }+ return new string(chars) + Environment.NewLine + string.Join(Environment.NewLine, selected);+ }++ private static string BuildSource(EnclosureProductSpec spec, string instanceName)+ {+ var body = $"{Id(instanceName)}BodySpec"; var lid = $"{Id(instanceName)}LidSpec"; var product = $"{Id(instanceName)}Spec";+ var w = N(spec.Width); var d = N(spec.Depth); var h = N(spec.Height); var lw = N(spec.Width + 2 * spec.LidClearance); var ld = N(spec.Depth + 2 * spec.LidClearance);+ var seat = N(ExactBodySeatZ(spec));+ var variation = spec.ProductionVariation ?? new SheetMetalProductionVariation();+ return $$"""+ Use SheetMetal.ProductFamilies;+ Concept EnclosureProduct { Body: Part Lid: Part Closure: Mate Attachments: Mate }+ Record EnclosureProductSpec { Body: EnclosureSpec Lid: LidSpec Clearance: Length MinimumClearance: Length MaximumClearance: Length Overlap: Length FastenerDiameter: Length }+ Static {{body}}: EnclosureSpec = EnclosureSpec { Width: {{w}}mm Depth: {{d}}mm Height: {{h}}mm LidLipHeight: {{N(spec.LidOverlap)}}mm Thickness: {{N(spec.BodyThickness)}}mm InsideRadius: {{N(spec.InsideRadius)}}mm KFactor: {{N(spec.KFactor)}} ReliefPolicy: {{Relief(spec.ReliefPolicy)}} }+ Static {{lid}}: LidSpec = LidSpec { Width: {{lw}}mm Depth: {{ld}}mm SkirtHeight: {{N(spec.LidOverlap)}}mm Clearance: {{N(spec.LidClearance)}}mm Thickness: {{N(spec.LidThickness)}}mm InsideRadius: {{N(spec.InsideRadius)}}mm KFactor: {{N(spec.KFactor)}} ReliefPolicy: {{Relief(spec.ReliefPolicy)}} }+ Static {{product}}: EnclosureProductSpec = EnclosureProductSpec { Body: {{body}} Lid: {{lid}} Clearance: {{N(spec.LidClearance)}}mm MinimumClearance: {{N(spec.MinimumClearance)}}mm MaximumClearance: {{N(spec.MaximumClearance)}}mm Overlap: {{N(spec.LidOverlap)}}mm FastenerDiameter: {{N(spec.FastenerDiameter)}}mm }+ Extend SheetMetal Body {+ Hole FrontIndicator { On: Front; Center: (45mm, 18mm); Diameter: 3mm; }+ Cut RearEthernet { On: Rear; At: (80mm, 18mm); Profile: Rectangle; Width: 16mm; Length: 14mm; }+ Cut LeftVent { On: Left; At: (45mm, 15mm); Profile: Slot; Width: 3mm; Length: 18mm; }+ Cut RightVent { On: Right; At: (45mm, 15mm); Profile: Slot; Width: 3mm; Length: 18mm; }+ Hole LidMountA { On: Body; Center: (12mm, 12mm); Diameter: {{N(spec.FastenerDiameter)}}mm; }+ }+ Extend SheetMetal Lid { Hole LidMountA { On: Top; Center: ({{N(12 + spec.LidClearance)}}mm, {{N(12 + spec.LidClearance)}}mm); Diameter: {{N(spec.FastenerDiameter)}}mm; } }+ Interface LidClosure {+ Role Body requires DatumFrameCapable, DimensionalCapable; Role Lid requires DatumFrameCapable, DimensionalCapable;+ Lower FrameCoincident Lid.BodySeat Body.LidSeat OpposedDirection;+ Fit Body.Width inside Lid.Width per-side;+ ClearancePolicy Minimum {{N(spec.MinimumClearance)}}mm Maximum {{N(spec.MaximumClearance)}}mm;+ Variation Linear {{N(variation.LinearTolerance)}}mm Thickness {{N(variation.ThicknessTolerance)}}mm BendAngle {{N(variation.BendAngleToleranceDegrees)}}deg BendLocation {{N(variation.BendLocationTolerance)}}mm Coating {{N(variation.CoatingThickness)}}mm CoatingTolerance {{N(variation.CoatingThicknessTolerance)}}mm Engagement {{N(spec.LidOverlap)}}mm;+ }+ Interface AlignedScrewPattern { Role Body requires PointCapable; Role Lid requires PointCapable; Allow rotation:about-axis; }+ Template < Spec: EnclosureProductSpec >+ Assembly ElectronicsEnclosureProduct: EnclosureProduct {+ <Assembly ElectronicsEnclosureProduct>+ <Part Body = ElectronicsEnclosure<Spec: Spec.Body>>+ Semantic Datums { DatumFrame LidSeat = [{{N(spec.Width / 2)}},{{N(spec.Depth / 2)}},{{seat}}] x [1,0,0] y [0,1,0] z [0,0,1]; Dimension Width = {{w}}mm; Dimension Overlap = {{N(spec.LidOverlap)}}mm; }+ Semantic Attachments { Point HoleA = [12,12,{{seat}}]; }+ </Part>+ <Part Lid = RemovablePanLid<Spec: Spec.Lid>>+ Semantic Datums { DatumFrame BodySeat = [{{N((spec.Width + 2 * spec.LidClearance) / 2)}},{{N((spec.Depth + 2 * spec.LidClearance) / 2)}},0] x [1,0,0] y [0,-1,0] z [0,0,-1]; Dimension Width = {{lw}}mm; Dimension Overlap = {{N(spec.LidOverlap)}}mm; }+ Semantic Attachments { Point HoleA = [{{N(12 + spec.LidClearance)}},{{N(12 + spec.LidClearance)}},0]; }+ </Part>+ </Assembly>+ Anchor: ElectronicsEnclosureProduct.Body.Datums.LidSeat;+ Mate Closure: LidClosure { Body: ElectronicsEnclosureProduct.Body.Datums; Lid: ElectronicsEnclosureProduct.Lid.Datums; }+ Mate Attachments: AlignedScrewPattern { Body: ElectronicsEnclosureProduct.Body.Attachments; Lid: ElectronicsEnclosureProduct.Lid.Attachments; }+ Expose { Semantic Body = Body.Datums; Semantic Lid = Lid.Datums; DatumFrame ClosureFrame = Lid.Datums.BodySeat; }+ }+ Assembly {{Id(instanceName)}} { <Assembly {{Id(instanceName)}}><Assembly Product = ElectronicsEnclosureProduct<Spec: {{product}}>></Assembly></Assembly> Anchor: {{Id(instanceName)}}.Product; }+ """;+ }++ private static double ExactBodySeatZ(EnclosureProductSpec spec)+ {+ var body = SheetMetalProductFamilies.MakeEnclosure(new ElectronicsEnclosureSpec(spec.Width, spec.Depth, spec.Height,+ spec.LidOverlap, spec.BodyThickness, spec.InsideRadius, spec.KFactor, spec.ReliefPolicy), "__DatumProbe").Part.FormedBody!;+ var points = body.Topology.Vertices.Select(vertex => body.TryGetVertexPoint(vertex.Id, out var point) ? point : (Aetheris.Kernel.Core.Math.Point3D?)null)+ .Where(point => point.HasValue).Select(point => point!.Value).ToArray();+ if (points.Length == 0) throw new InvalidOperationException("The enclosure Body has no exact vertices from which to derive LidSeat.");+ return points.Max(point => point.Z);+ }++ private static void Validate(EnclosureProductSpec spec)+ {+ var variation = spec.ProductionVariation ?? new SheetMetalProductionVariation();+ var values = new[] { spec.Width, spec.Depth, spec.Height, spec.BodyThickness, spec.LidThickness, spec.LidOverlap, spec.MinimumClearance, spec.MaximumClearance, spec.FastenerDiameter };+ var variationValues = new[] { variation.LinearTolerance, variation.ThicknessTolerance, variation.BendAngleToleranceDegrees, variation.BendLocationTolerance, variation.CoatingThickness, variation.CoatingThicknessTolerance };+ if (values.Any(value => !double.IsFinite(value) || value <= 0) || !double.IsFinite(spec.LidClearance) || spec.LidClearance < 0)+ throw new ArgumentOutOfRangeException(nameof(spec), "Product dimensions must be finite; physical dimensions must be positive and clearance nonnegative.");+ if (spec.MaximumClearance < spec.MinimumClearance) throw new ArgumentException("Maximum clearance must not be below minimum clearance.", nameof(spec));+ if (variationValues.Any(value => !double.IsFinite(value) || value < 0)) throw new ArgumentOutOfRangeException(nameof(spec), "Production variation bounds must be finite and nonnegative.");+ }+ private static string N(double value) => value.ToString("R", CultureInfo.InvariantCulture);+ private static string Id(string value) { var id = Regex.Replace(value, "[^A-Za-z0-9_]", "_"); return id.Length > 0 && (char.IsLetter(id[0]) || id[0] == '_') ? id : "Product_" + id; }+ private static string Relief(SheetReliefPolicy value) => value switch { SheetReliefPolicy.Round => "Round", SheetReliefPolicy.Rectangular => "Rectangular", _ => "Auto" };+}diff --git a/README.md b/README.mdindex 66e245b4..df1d2610 100644--- a/README.md+++ b/README.md@@ -29,7 +29,9 @@ SheetMetal Enclosure = ElectronicsEnclosure < Spec: Psu >```The specialization lowers through ordinary Base, Flange, Relief, Cut, exact-flat,-DFM, SVG, and STEP paths. See the [M5 product-family guide](docs/firmament/sheetmetal-product-templates-m5.md).+DFM, SVG, and STEP paths. Generic Assembly DatumFrames and tolerance-aware enclosure+fit are documented in the [M7 guide](docs/sheetmetal/aetheris-sheetmetal-m7.md); see+also the [M5 product-family guide](docs/firmament/sheetmetal-product-templates-m5.md).## Static engineering data@@ -164,7 +166,7 @@ Use `Aetheris.slnx` as the only solution entrypoint. For legacy Firmament V1/Fri## Assembly model snapshot-- Firmament Assembly source lowers to normalized AssemblyIR; `.firmasm` is a deprecated transform-first compatibility lane.+- Firmament Assembly source lowers to normalized AssemblyIR; `.firmasm` is the current single-root Assembly document profile. Only the historical JSON-shaped `.firmasm` syntax is a deprecated transform-first compatibility lane.- STEP is treated as foreign interop input/output.- Multi-root STEP is assembly-like input and must route through assembly extraction/import, not single-part import.- Current roundtrip export is intentionally bounded to per-instance STEP + `roundtrip.package.json`.diff --git a/docs/assembly/assembly-m0.md b/docs/assembly/assembly-m0.mdindex ba7f1d46..204b6b70 100644--- a/docs/assembly/assembly-m0.md+++ b/docs/assembly/assembly-m0.md@@ -20,7 +20,7 @@ Assembly BearingModule {}```-The XML-like parser is deliberately bounded to `Assembly` and paired `Part` tags. It does not import Copeland syntax machinery. Assembly Template expansion is not in M0, but the normalized source model separates definition identity from occurrence identity and therefore does not block Template-generated trees. Table/Record provenance is retained as an ordered string/source provenance trail in dimensional relations; the dogfood uses `HousingTable`, `BearingTable`, and `SpacerTemplate` origins.+The XML-like product tree remains deliberately bounded to paired `Assembly`, `Part`, and `Panel` tags. Later Assembly milestones added ordinary `Template <...> Assembly ...` definitions and angle-bracket occurrences without changing that visual profile. Table/Record provenance is retained as an ordered string/source provenance trail in dimensional relations.Inspect with:@@ -30,4 +30,32 @@ aetheris asm inspect fixtures/AssemblyM0/bearing-module.firmament --jsonJSON exposes tree/BOM data, Interface definitions and Roles, Mate participants and semantic IDs, constraints, transforms/status, fit bands, dimensional graph, complete stackup chains, diagnostics, and phase timings. Text mode gives a compact product tree, Mate table, and stackup summary. This is the Cadmata seam for M0; transformed geometry display is deferred.-Legacy `.firmasm` remains accepted only by `asm exec`/`asm export`. It is flat JSON with authored transforms and cannot be losslessly migrated to typed Interfaces because it contains no semantic relationship intent. A bounded automatic importer would fabricate meaning, so M0 documents migration: rewrite the flat `parts`/`instances` list as a nested product tree, expose semantic endpoints on definitions, replace transforms with Interface/Mate declarations, and retain explicit transforms only as an escape hatch. Per-instance STEP packaging remains the current export seam; the exporter does not author AP242 product structure or mapped-item assembly relationships.+Current Assembly also admits generic fully registered semantic frames:++```firmament+Semantic Mount {+ DatumFrame Frame = [0,0,0] x [1,0,0] y [0,1,0] z [0,0,1];+}+Interface RegisteredMount {+ Role Moving requires DatumFrameCapable;+ Role Fixed requires DatumFrameCapable;+ Lower FrameCoincident Moving Fixed SameDirection;+}+```++`FrameCoincident` resolves all six rigid-body degrees of freedom. `SameDirection`+and `OpposedDirection` are explicit. Text inspection prints stable datum paths and+the resolved DOF/status. Axis/plane/point constraints remain available when free+motion is intentional, with typed underconstraint diagnostics otherwise.++Historical JSON-shaped `.firmasm` remains accepted as legacy migration input. Current `.firmasm` is the single-root Firmament V2 Assembly profile, and current AssemblyIR exports native AP242 product structure. Migration deliberately preserves explicit transforms without inventing Interfaces or Mates.++AP242 occurrence export follows the OCCT/XDE convention used by the checked-in+`testdata/step242/OCCT/as1.step` reference: each `NEXT_ASSEMBLY_USAGE_OCCURRENCE`+is paired with a `CONTEXT_DEPENDENT_SHAPE_REPRESENTATION`; its complex+relationship names the child representation first and parent representation+second, and combines `REPRESENTATION_RELATIONSHIP`,+`REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION`, and+`SHAPE_REPRESENTATION_RELATIONSHIP`. The item-defined transform maps the child+placement into the parent frame. Keeping all three relationship facets is+required for OCCT-based consumers to preserve both hierarchy and placement.diff --git a/docs/sheetmetal/aetheris-sheetmetal-m6.md b/docs/sheetmetal/aetheris-sheetmetal-m6.mdnew file mode 100644index 00000000..c000860b--- /dev/null+++ b/docs/sheetmetal/aetheris-sheetmetal-m6.md@@ -0,0 +1,106 @@+# Sheet Metal M6: generic enclosure products++## Parser-level language audit++The implementation and tests—not older prose—establish this current map:++| Surface | Current syntax and lowering | M6 status |+|---|---|---|+| Part authoring | Normal Firmament V2 declarations such as `Record`, `Static`, `Template <...>`, `SheetMetal`, `Require`, `Concept`, specialization with `<Name: value>`, and downstream `Extend SheetMetal` | Existing M5 typed Template frontend and Sheet Metal lowering retained |+| Template AST | `TemplateDeclarationIr` with typed value/type parameters; record arguments bind to `BoundTemplateRecordIr`; specialization records deterministic `ConceptIrTemplateInstantiation` provenance | Reused; no Assembly-specific Template engine |+| Concept satisfaction | Part Templates claim a Concept after `:`; members and types are checked before domain lowering | Existing Body/Lid contracts retained; M6 adds the same structural claim form to Assembly Templates |+| Assembly profile | `Assembly Name { <Assembly Name> ... <Part P = Definition<...>></Part> ... </Assembly> ... }` | Canonical product syntax remains XML-shaped |+| Assembly Template | `Template < Spec: RecordType > Assembly Product: ProductConcept { ... }`; occurrence `<Assembly X = Product<Spec: StaticSpec>></Assembly>` | Existing generic Assembly specialization extended with nested Record projection (`Spec.Body`) and structural Concept validation |+| Interface | `Interface Name { Role ... requires ...; Lower ...; Fit ... inside ...; Allow ...; }` | Existing parser/IR/compiler reused |+| Role | Capability requirements such as `AxisCapable`, `PlaneCapable`, `PointCapable`, and `DimensionalCapable` | Checked before geometric placement |+| Mate | `Mate Name: Interface { Role: Product.Part.Semantic; }` | Existing `MateIr`, constraint lowering, placement solver, and validation reused |+| `Require` / `Assert` | `Require Name => static-bool-expression`; `Assert ToleranceStackup ...` | Existing Template/static and dimensional graph paths retained |+| `.firmasm` | Current Firmament V2 Assembly document profile requiring exactly one exported root; JSON-shaped input is legacy migration data | Canonical M6 fixture uses `.firmasm` |++`AssemblySource` lowers XML containment into `AssemblyMemberSource`; Interfaces and Mates remain sibling graph declarations. Binding produces `AssemblyInstanceIr`, `MateIr`, `PlacementConstraintIr`, placement results, dimensional relations, and reusable `AssemblyDefinitionIr`. M1 materializes each distinct part definition, validates exact geometry residuals and positive-volume interference, and M2 exports AP242 definitions/occurrences without fusing bodies.++The actual gap was cross-profile materialization: the generic Assembly executor only knew the ordinary solid-part compiler. M6 adds `AssemblyPartMaterializer`, a narrow domain hook. Sheet Metal resolves projected typed records through its normal Template frontend and returns its authoritative exact formed BRep. Assembly still owns hierarchy, Interfaces, Mates, placement, interference, and AP242.++Two stale statements were corrected in place: `README.md` called all `.firmasm` deprecated, and `docs/assembly/assembly-m0.md` still said Assembly Template expansion and AP242 product export were absent. Both described older milestones.++## Canonical product source++The complete passing source is `fixtures/FirmamentV2/SheetMetal/m6-network-appliance-product.firmasm`. Its essential shape is:++```firmament+Concept EnclosureProduct { Body: Part Lid: Part Closure: Mate Attachments: Mate }++Template < Spec: EnclosureProductSpec >+Assembly ElectronicsEnclosureProduct: EnclosureProduct {+ <Assembly ElectronicsEnclosureProduct>+ <Part Body = ElectronicsEnclosure<Spec: Spec.Body>> ... </Part>+ <Part Lid = RemovablePanLid<Spec: Spec.Lid>> ... </Part>+ </Assembly>+ Anchor: ElectronicsEnclosureProduct.Body.Closure;+ Mate Closure: LidClosure { Body: ElectronicsEnclosureProduct.Body.Closure; Lid: ElectronicsEnclosureProduct.Lid.Closure; }+ Mate Attachments: AlignedScrewPattern { Body: ElectronicsEnclosureProduct.Body.Attachments; Lid: ElectronicsEnclosureProduct.Lid.Attachments; }+ Expose { Semantic Body = Body.Closure; Semantic Lid = Lid.Closure; }+}++Assembly NetworkAppliance {+ <Assembly NetworkAppliance>+ <Assembly Product = ElectronicsEnclosureProduct<Spec: NetworkProductSpec>></Assembly>+ </Assembly>+ Anchor: NetworkAppliance.Product;+}+```++The XML-shaped tree distinguishes product containment from normal Sheet Metal construction. Graph declarations stay outside that tree. `Spec.Body` and `Spec.Lid` are typed nested Record projections and resolve to the same ordinary M5 part Templates.++## Contracts, interface, placement, and attachment++`ElectronicsEnclosure` continues to satisfy the `Enclosure` part Concept; `RemovablePanLid` satisfies `RemovableLid`; the Assembly Template satisfies `EnclosureProduct`. Removing the `Lid` member produces `assembly-concept-missing-member` before geometry. A Role capability mismatch produces `assembly-mate-capability-mismatch` before placement.++`LidClosure` requires axis, plane, and dimensional capabilities on Body and Lid. It lowers axis coincidence and seating-plane coincidence, admits only rotation about the closure axis, and declares `Fit Body.Width inside Lid.Width`. For the canonical 160 × 110 mm body and 162 × 112 mm lid, the Mate derives the lid world transform `[-1, -1, 36]` mm; no raw occurrence transform is authored.++The authored uniform side clearance is 1 mm. Derived lid dimensions are 162 × 112 mm. Product DFM reports a measured bounded side clearance of 1 mm against the 0.4..1.5 mm policy and a 9 mm required overlap. A 0.2 mm specialization fails `assembly-dfm-lid-clearance` at `Product.Closure`; changing it to 1 mm repairs the product.++`AlignedScrewPattern` is a bounded typed attachment foundation. Body and Lid roles require point capability, the Mate preserves semantic correspondence at `Product.Attachments.HoleA`, and the BOM records four nominal M3 placeholders. It intentionally does not claim a full fastener catalog or thread analysis.++## Product result and manufacturing++The real host call is:++```csharp+var product = EnclosureProductFamilies.MakeEnclosureProduct(+ new EnclosureProductSpec(160, 110, 36, 1.2, 1.2, 1.5, 1, 9),+ "NetworkAppliance");+var artifacts = product.Export("artifacts/m6/product");+```++This call emits typed Firmament specialization input, then invokes the same `ElectronicsEnclosureProduct` Assembly Template and the same `ElectronicsEnclosure` / `RemovablePanLid` part Templates. C# contains no alternate CAD construction.++The result exposes:++- hierarchy `NetworkAppliance → Product → Body, Lid`;+- stable product paths including `Product.Body.Front`, `Product.Body.Rear`, `Product.Body.FrontLip`, `Product.Lid.Top`, `Product.Lid.Front`, `Product.Closure`, and `Product.Attachments`;+- independent exact formed parts, exact line/arc flat contours, flat STEP, and SVG;+- AP242 Assembly STEP with two geometric definitions and distinct Body/Lid occurrences;+- deterministic specialization, geometry, flat-pattern, and product DFM ordering;+- categorized `Part`, `Interface`, and `Assembly` findings;+- a minimal Body ×1, Lid ×1, M3-placeholder ×4 BOM.++The network-appliance source keeps customization in the normal part profile: Body has two indicators, power/Ethernet cutouts, four vents, and a lid-mount hole; Lid has the corresponding mount hole. Its exact flats contain nine Body cut loops and one Lid cut loop. The canonical CLI inspection succeeds with two materialized definitions and two part occurrences. Body geometry has 81 faces / 194 edges / 118 vertices; Lid has 47 / 102 / 58. AP242 export/reimport, all four per-part formed/flat STEP reimports, exact blank validation, and manifold preflight are covered by `SheetMetalM6Tests`.++## DFM evidence and bounded seams++Part findings come from `SheetMetalDfm`. Interface findings cover clearance, overlap, and attachment correspondence. Assembly findings use the existing exact `BrepSolidInterference` evidence to reject positive-volume Body/Lid penetration and report the bounded +Z removal check. The general `IntersectionQuery`, `ContactQuery`, and `ClosestPointQuery` surface is curve/patch oriented today; pretending it performs exact body/body clearance would be dishonest. Extending those query APIs to body/body witnesses is the next geometry-evidence seam.++Grounding is left as an explicit future Interface metadata seam; no electrical simulation or paint-mask inference is claimed.++## LLM authoring friction++- Fix now: nested product Record projection, Assembly structural Concept diagnostics, Sheet Metal definition materialization, and CLI routing were missing and are implemented.+- Future abstraction: authoring the same closure dimensions in typed product Records and XML semantic datums is repetitive; generated/derived semantic datums should come from part Concepts.+- Inherent engineering choice: clearance range, overlap, attachment count/location, service direction, grounding, material/finish, and tolerance policy require product engineering decisions.++## Verdict++Yes: Aetheris now expresses a bounded complete two-part Sheet Metal enclosure as a user-defined generic Firmament Assembly Template composed from ordinary Sheet Metal part Templates. The XML-like Assembly profile is preserved. Body/Lid relationships are typed Interface/Role/Mate semantics, and Forge-facing C# invokes the same construction to obtain Body, Lid, Assembly, per-part flats, artifacts, BOM, and product DFM.++The largest remaining blocker for a commercial hardware pipeline is tolerance-backed exact body/body clearance/contact evidence across full formed assemblies, including coatings and manufacturing process variation. Current nominal relational DFM and exact positive-volume interference are useful, but they are not yet a production fit/tolerance certification system.diff --git a/docs/sheetmetal/aetheris-sheetmetal-m7.md b/docs/sheetmetal/aetheris-sheetmetal-m7.mdnew file mode 100644index 00000000..249ff9e0--- /dev/null+++ b/docs/sheetmetal/aetheris-sheetmetal-m7.md@@ -0,0 +1,126 @@+# Sheet Metal M7: semantic assembly datums and tolerance-aware fit++## M6 diagnosis and retained regression++The original source remains at `fixtures/FirmamentV2/SheetMetal/m6-network-appliance-product.firmasm`. Its Body and Lid parts are valid, but the `Closure` semantic repeats nominal coordinates independently of the formed geometry:++```firmament+Axis Axis = [80,55,36] -> [0,0,1];+Plane Seat = [80,55,36] normal [0,0,1];+```++The Interface aligns the axis and plane while admitting rotation about the axis. This derives `(-1,-1,36) mm`, but the exact formed Body reaches `Z=41.4 mm`. The relationship is therefore detached from the manufactured closure geometry by 5.4 mm and is not registered in-plane. The M7 regression test reproduces both numbers; it does not tune the old transform.++## Generic datum architecture++`DatumFrameCapability` and `ExactDatumFrameBinding` are generic semantic primitives in `Aetheris.Semantics`. A frame stores an origin and right-handed X/Y/Z basis in definition-local coordinates. Its identity is authored and stable; it is not a BRep face ID. `AssemblyDatumIr` publishes the stable semantic path and binding ID. `DatumMateSolutionIr` records orientation, constrained DOF, status, and the derived transform.++The parser-level syntax is:++```firmament+Semantic Datums {+ DatumFrame LidSeat = [80,55,41.4]+ x [1,0,0] y [0,1,0] z [0,0,1];+}+```++The same syntax is tested by the non-Sheet-Metal `Plate` + `Bracket` fixture in `AssemblyM7DatumTests`. A registered frame constrains 6/6 rigid-body DOF. Existing point, axis, and plane datums remain useful for intentionally partial constraints; the existing underconstraint diagnostics still report their free translations and rotations.++## Canonical M7 source and Mate++The passing source is `fixtures/FirmamentV2/SheetMetal/m7-network-appliance-product.firmasm`. Its closure is:++```firmament+Interface LidClosure {+ Role Body requires DatumFrameCapable, DimensionalCapable;+ Role Lid requires DatumFrameCapable, DimensionalCapable;+ Lower FrameCoincident Lid.BodySeat Body.LidSeat OpposedDirection;+ Fit Body.Width inside Lid.Width per-side;+ ClearancePolicy Minimum 0.5mm Maximum 1.5mm;+ Variation Linear 0.1mm Thickness 0.08mm BendAngle 0.5deg+ BendLocation 0.1mm Coating 0mm CoatingTolerance 0mm Engagement 9mm;+}++Mate Closure: LidClosure {+ Body: ElectronicsEnclosureProduct.Body.Datums;+ Lid: ElectronicsEnclosureProduct.Lid.Datums;+}+```++The stable datum paths are:++- `NetworkAppliance.Product.Body.Datums.LidSeat`+- `NetworkAppliance.Product.Lid.Datums.BodySeat`+- `NetworkAppliance.Product.ClosureFrame`++The Body frame points outward along +Z. The Lid frame points outward along -Z. `OpposedDirection` is explicit and never inferred from role order. Tangent registration fixes in-plane translation and rotation. The solver derives `(-1,-1,41.4) mm`; no `LegacyExplicit` placement exists.++## Nominal and tolerance-aware fit++`InterfaceFitResultIr` separates evidence from classification. `per-side` converts the 2 mm width difference to 1 mm side clearance. Manufacturing variation is parsed into the Interface and evaluated by the generic Assembly compiler; `MakeEnclosureProduct(spec)` exposes that IR result rather than running a second fit engine.++For the canonical NetworkAppliance:++| Evidence | Result |+|---|---:|+| nominal minimum separation | 1.0000 mm |+| minimum possible separation | 0.382916 mm |+| maximum possible separation | 1.617084 mm |+| maximum penetration | 0 mm |+| nominal state | `GuaranteedClearance` |+| variation state | `GuaranteedClearance` |++Worst-case clearance reductions are ordered deterministically:++- bend location: 0.200000 mm;+- sheet thickness: 0.160000 mm;+- bend angle (`2 × 9 mm × tan(0.5°)`): 0.157084 mm;+- linear dimension: 0.100000 mm.++Coating uses two fit surfaces. A 0.25 ± 0.05 mm coating changes the same nominal Body/Lid STEP hashes from `GuaranteedClearance` to `PossibleInterference`. A sufficiently thick coating fixture reaches `GuaranteedInterference`. Nominal geometry is never perturbed.++An engineering noise floor of 1e-6 mm prevents microscopic numerical residue from becoming an interference verdict. The tolerance values remain engineering allowances, separate from geometry-query epsilon.++## Contact, overlap, and query boundary++The registered frame certifies the intended seating relationship. Contact area remains `null` because the current body/body query surface cannot certify finite face area. Exact nominal positive-volume overlap is checked by the existing `BrepSolidInterference` closed-body predicate, which reports penetration and a contained-tetrahedron witness. A non-interfering result establishes a zero certified overlap lower bound, not an exact arbitrary-BRep intersection volume.++`ClosestPointQuery`, `ContactQuery`, and `IntersectionQuery` retain their curve/patch evidence contracts and topology firewall. M7 does not pretend those APIs perform body/body clearance. The enclosure fit interval is an analytic, conservative semantic-dimension proof; witnesses never become topology authority. General Boolean and CIR architectures are unchanged.++## Diagnostics and product API++Regression coverage includes:++- the old M6 detached relationship;+- missing/wrong datum member (`assembly-mate-invalid-participant`);+- axis/plane underconstraint (`assembly-placement-underconstrained`);+- conflicting frame constraints (`assembly-placement-overconstrained`);+- generic non-Sheet-Metal frame mating;+- guaranteed clearance, possible interference, and guaranteed interference;+- coating changing fit while nominal STEP hashes remain identical.++`ManufacturedEnclosureProduct` now returns Assembly datums, resolved Datum Mate IR, `EnclosureFitEvidence`, tolerance contributors, product DFM, and normal Body/Lid manufacturing results. Export adds `fit-report.json` beside formed/flat STEP, flat SVG, Assembly STEP, and `product-dfm.json`.++CLI `asm inspect` prints stable datums and concise Datum Mate solutions. The canonical evidence is under `artifacts/m7`, including before/after inspections and the complete manufacturing package.++## AP242 assembly interoperability++The Assembly STEP exporter follows the complex occurrence relationship emitted by+the repository's OCCT `as1.step` reference. Each child-to-parent relationship+combines the base representation relationship, its item-defined transform, and+the shape-representation facet. A plain transformed relationship is insufficient:+OCCT can recover its product tree while discarding the occurrence placement.++The regenerated `artifacts/m7/NetworkAppliance.step` was imported independently+with FreeCAD 1.0.2 / OCCT. It recovered the nested+`NetworkAppliance -> ElectronicsEnclosureProduct -> Body, Lid` hierarchy. The+Body world bounds are `Z=0..41.4 mm`; the Lid occurrence placement is+`(-1,-1,41.4) mm` and its world bounds are `Z=30.9..42.6 mm`. This confirms the+lid overlaps the enclosure walls from above by its authored skirt depth rather+than appearing below the box.++## Performance and certification boundary++On the canonical fixture, local datum solve plus Assembly analysis measured about 35 ms in the recorded run; ordering, IDs, transforms, classifications, contributors, and geometry hashes are deterministic. The ordinary CLI path materializes two exact definitions and two occurrences.++The largest remaining blocker to production fit certification is certified body/body minimum-distance/contact-area/overlap evidence over the full formed BRep, correlated to real process capability data. M7 provides honest analytic enclosure envelopes and exact positive-volume rejection, but it does not claim general surface-pair certification, GD&T, springback, or coating physics.diff --git a/fixtures/FirmamentV2/SheetMetal/m6-network-appliance-product.firmasm b/fixtures/FirmamentV2/SheetMetal/m6-network-appliance-product.firmasmnew file mode 100644index 00000000..c9139b75--- /dev/null+++ b/fixtures/FirmamentV2/SheetMetal/m6-network-appliance-product.firmasm@@ -0,0 +1,111 @@+// Firmament M6: normal part Templates are resolved by the Sheet Metal profile;+// this XML-shaped document owns product hierarchy and relationships.+Use SheetMetal.ProductFamilies;++Concept EnclosureProduct {+ Body: Part+ Lid: Part+ Closure: Mate+ Attachments: Mate+}++Record EnclosureProductSpec {+ Body: EnclosureSpec+ Lid: LidSpec+ Clearance: Length+ MinimumClearance: Length+ MaximumClearance: Length+ Overlap: Length+ FastenerDiameter: Length+}++Static NetworkBodySpec: EnclosureSpec = EnclosureSpec {+ Width: 160mm Depth: 110mm Height: 36mm LidLipHeight: 7mm+ Thickness: 1.2mm InsideRadius: 1.5mm KFactor: 0.42 ReliefPolicy: Rectangular+}+Static NetworkLidSpec: LidSpec = LidSpec {+ Width: 162mm Depth: 112mm SkirtHeight: 9mm Clearance: 1mm+ Thickness: 1.2mm InsideRadius: 1.5mm KFactor: 0.42 ReliefPolicy: Rectangular+}+Static NetworkProductSpec: EnclosureProductSpec = EnclosureProductSpec {+ Body: NetworkBodySpec Lid: NetworkLidSpec Clearance: 1mm+ MinimumClearance: 0.5mm MaximumClearance: 1.5mm Overlap: 9mm FastenerDiameter: 3.2mm+}++// Ordinary part-profile customization remains ordinary `Extend SheetMetal`.+// The Assembly profile only composes the resulting manufactured definitions.+Extend SheetMetal Body {+ Hole FrontIndicatorGreen { On: Front; Center: (45mm, 18mm); Diameter: 3mm; }+ Hole FrontIndicatorAmber { On: Front; Center: (55mm, 18mm); Diameter: 3mm; }+ Cut RearPowerInlet { On: Rear; At: (35mm, 18mm); Profile: Rectangle; Width: 18mm; Length: 12mm; }+ Cut RearEthernet { On: Rear; At: (80mm, 18mm); Profile: Rectangle; Width: 16mm; Length: 14mm; }+ Cut LeftVentA { On: Left; At: (30mm, 15mm); Profile: Slot; Width: 3mm; Length: 18mm; }+ Cut LeftVentB { On: Left; At: (55mm, 15mm); Profile: Slot; Width: 3mm; Length: 18mm; }+ Cut RightVentA { On: Right; At: (30mm, 15mm); Profile: Slot; Width: 3mm; Length: 18mm; }+ Cut RightVentB { On: Right; At: (55mm, 15mm); Profile: Slot; Width: 3mm; Length: 18mm; }+ Hole LidMountA { On: Body; Center: (12mm, 12mm); Diameter: 3.2mm; }+}+Extend SheetMetal Lid {+ Hole LidMountA { On: Top; Center: (13mm, 13mm); Diameter: 3.2mm; }+}++Interface LidClosure {+ Role Body requires AxisCapable, PlaneCapable, DimensionalCapable;+ Role Lid requires AxisCapable, PlaneCapable, DimensionalCapable;+ Lower AxisCoincident Lid.Axis Body.Axis;+ Lower PlaneCoincident Lid.Seat Body.Seat;+ Fit Body.Width inside Lid.Width;+ Allow rotation:about-axis;+}++Interface AlignedScrewPattern {+ Role Body requires PointCapable;+ Role Lid requires PointCapable;+ Allow rotation:about-axis;+}++Template < Spec: EnclosureProductSpec >+Assembly ElectronicsEnclosureProduct: EnclosureProduct {+ <Assembly ElectronicsEnclosureProduct>+ <Part Body = ElectronicsEnclosure<Spec: Spec.Body>>+ Semantic Closure {+ Axis Axis = [80,55,36] -> [0,0,1];+ Plane Seat = [80,55,36] normal [0,0,1];+ Dimension Width = 160mm;+ Dimension Overlap = 9mm;+ }+ Semantic Attachments { Point HoleA = [12,12,36]; }+ </Part>+ <Part Lid = RemovablePanLid<Spec: Spec.Lid>>+ Semantic Closure {+ Axis Axis = [81,56,0] -> [0,0,1];+ Plane Seat = [81,56,0] normal [0,0,1];+ Dimension Width = 162mm;+ Dimension Overlap = 9mm;+ }+ Semantic Attachments { Point HoleA = [13,13,0]; }+ </Part>+ </Assembly>+ Anchor: ElectronicsEnclosureProduct.Body.Closure;+ Mate Closure: LidClosure {+ Body: ElectronicsEnclosureProduct.Body.Closure;+ Lid: ElectronicsEnclosureProduct.Lid.Closure;+ }+ Mate Attachments: AlignedScrewPattern {+ Body: ElectronicsEnclosureProduct.Body.Attachments;+ Lid: ElectronicsEnclosureProduct.Lid.Attachments;+ }+ Expose {+ Semantic Body = Body.Closure;+ Semantic Lid = Lid.Closure;+ Axis ClosureAxis = Lid.Closure.Axis;+ Plane ServicePlane = Lid.Closure.Seat;+ }+}++Assembly NetworkAppliance {+ <Assembly NetworkAppliance>+ <Assembly Product = ElectronicsEnclosureProduct<Spec: NetworkProductSpec>></Assembly>+ </Assembly>+ Anchor: NetworkAppliance.Product;+}diff --git a/fixtures/FirmamentV2/SheetMetal/m7-network-appliance-product.firmasm b/fixtures/FirmamentV2/SheetMetal/m7-network-appliance-product.firmasmnew file mode 100644index 00000000..b95dc7df--- /dev/null+++ b/fixtures/FirmamentV2/SheetMetal/m7-network-appliance-product.firmasm@@ -0,0 +1,94 @@+// Firmament M7: semantic DatumFrames own Body/Lid placement; fit policy and+// production variation remain relational Assembly engineering semantics.+Use SheetMetal.ProductFamilies;++Concept EnclosureProduct { Body: Part Lid: Part Closure: Mate Attachments: Mate }++Record EnclosureProductSpec {+ Body: EnclosureSpec Lid: LidSpec Clearance: Length MinimumClearance: Length+ MaximumClearance: Length Overlap: Length FastenerDiameter: Length+}++Static NetworkBodySpec: EnclosureSpec = EnclosureSpec {+ Width: 160mm Depth: 110mm Height: 36mm LidLipHeight: 7mm+ Thickness: 1.2mm InsideRadius: 1.5mm KFactor: 0.42 ReliefPolicy: Rectangular+}+Static NetworkLidSpec: LidSpec = LidSpec {+ Width: 162mm Depth: 112mm SkirtHeight: 9mm Clearance: 1mm+ Thickness: 1.2mm InsideRadius: 1.5mm KFactor: 0.42 ReliefPolicy: Rectangular+}+Static NetworkProductSpec: EnclosureProductSpec = EnclosureProductSpec {+ Body: NetworkBodySpec Lid: NetworkLidSpec Clearance: 1mm+ MinimumClearance: 0.5mm MaximumClearance: 1.5mm Overlap: 9mm FastenerDiameter: 3.2mm+}++Extend SheetMetal Body {+ Hole FrontIndicatorGreen { On: Front; Center: (45mm, 18mm); Diameter: 3mm; }+ Hole FrontIndicatorAmber { On: Front; Center: (55mm, 18mm); Diameter: 3mm; }+ Cut RearPowerInlet { On: Rear; At: (35mm, 18mm); Profile: Rectangle; Width: 18mm; Length: 12mm; }+ Cut RearEthernet { On: Rear; At: (80mm, 18mm); Profile: Rectangle; Width: 16mm; Length: 14mm; }+ Cut LeftVentA { On: Left; At: (30mm, 15mm); Profile: Slot; Width: 3mm; Length: 18mm; }+ Cut LeftVentB { On: Left; At: (55mm, 15mm); Profile: Slot; Width: 3mm; Length: 18mm; }+ Cut RightVentA { On: Right; At: (30mm, 15mm); Profile: Slot; Width: 3mm; Length: 18mm; }+ Cut RightVentB { On: Right; At: (55mm, 15mm); Profile: Slot; Width: 3mm; Length: 18mm; }+ Hole LidMountA { On: Body; Center: (12mm, 12mm); Diameter: 3.2mm; }+}+Extend SheetMetal Lid { Hole LidMountA { On: Top; Center: (13mm, 13mm); Diameter: 3.2mm; } }++Interface LidClosure {+ Role Body requires DatumFrameCapable, DimensionalCapable;+ Role Lid requires DatumFrameCapable, DimensionalCapable;+ Lower FrameCoincident Lid.BodySeat Body.LidSeat OpposedDirection;+ Fit Body.Width inside Lid.Width per-side;+ ClearancePolicy Minimum 0.5mm Maximum 1.5mm;+ Variation Linear 0.1mm Thickness 0.08mm BendAngle 0.5deg BendLocation 0.1mm Coating 0mm CoatingTolerance 0mm Engagement 9mm;+}++Interface AlignedScrewPattern {+ Role Body requires PointCapable;+ Role Lid requires PointCapable;+ Allow rotation:about-axis;+}++Template < Spec: EnclosureProductSpec >+Assembly ElectronicsEnclosureProduct: EnclosureProduct {+ <Assembly ElectronicsEnclosureProduct>+ <Part Body = ElectronicsEnclosure<Spec: Spec.Body>>+ Semantic Datums {+ DatumFrame LidSeat = [80,55,41.4] x [1,0,0] y [0,1,0] z [0,0,1];+ Dimension Width = 160mm;+ Dimension Overlap = 9mm;+ }+ Semantic Attachments { Point HoleA = [12,12,41.4]; }+ </Part>+ <Part Lid = RemovablePanLid<Spec: Spec.Lid>>+ Semantic Datums {+ DatumFrame BodySeat = [81,56,0] x [1,0,0] y [0,-1,0] z [0,0,-1];+ Dimension Width = 162mm;+ Dimension Overlap = 9mm;+ }+ Semantic Attachments { Point HoleA = [13,13,0]; }+ </Part>+ </Assembly>+ Anchor: ElectronicsEnclosureProduct.Body.Datums.LidSeat;+ Mate Closure: LidClosure {+ Body: ElectronicsEnclosureProduct.Body.Datums;+ Lid: ElectronicsEnclosureProduct.Lid.Datums;+ }+ Mate Attachments: AlignedScrewPattern {+ Body: ElectronicsEnclosureProduct.Body.Attachments;+ Lid: ElectronicsEnclosureProduct.Lid.Attachments;+ }+ Expose {+ Semantic Body = Body.Datums;+ Semantic Lid = Lid.Datums;+ DatumFrame ClosureFrame = Lid.Datums.BodySeat;+ }+}++Assembly NetworkAppliance {+ <Assembly NetworkAppliance>+ <Assembly Product = ElectronicsEnclosureProduct<Spec: NetworkProductSpec>></Assembly>+ </Assembly>+ Anchor: NetworkAppliance.Product;+}