Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Expose concept IR and feature provenance in Firmament exports

Yuechen Lib1a0aeb83d6a
diff --git a/Aetheris.CLI.Tests/FirmamentV2ConceptPoint3HoleStepPipelineTests.cs b/Aetheris.CLI.Tests/FirmamentV2ConceptPoint3HoleStepPipelineTests.cs
new file mode 100644
index 00000000..2cd0c1a7
--- /dev/null
+++ b/Aetheris.CLI.Tests/FirmamentV2ConceptPoint3HoleStepPipelineTests.cs
@@ -0,0 +1,93 @@
+using System.Text.Json;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class FirmamentV2ConceptPoint3HoleStepPipelineTests
+{
+ [Fact]
+ public void ConceptPoint3_DrivesTwoSemanticHolesThroughStepAndIndependentAnalysis()
+ {
+ var dir = Path.Combine(Path.GetTempPath(), "aetheris-concept-materialization-m2", Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(dir);
+ var sourcePath = Path.Combine(dir, "concept-point-holes.firmament");
+ var stepPath = Path.Combine(dir, "concept-point-holes.step");
+ File.WriteAllText(sourcePath, Source);
+ var stdout = new StringWriter(); var stderr = new StringWriter();
+
+ var exit = CliRunner.Run(["build", sourcePath, "--out", stepPath, "--json"], stdout, stderr);
+
+ Assert.Equal(0, exit);
+ using var report = JsonDocument.Parse(stdout.ToString());
+ var root = report.RootElement;
+ Assert.Equal("Valid", root.GetProperty("conceptIr").GetProperty("materializedStruct").GetProperty("conformance").GetString());
+ Assert.False(root.GetProperty("conceptIr").GetProperty("structs")[0].GetProperty("materialized").GetBoolean());
+ Assert.Equal(4, root.GetProperty("conceptIr").GetProperty("materializedStruct").GetProperty("exposedMembers").GetArrayLength());
+ var features = root.GetProperty("features");
+ Assert.Equal(2, features.GetArrayLength());
+ Assert.Equal("concept:BracketConcept.MountPoints[0]", features[0].GetProperty("centerStableId").GetString());
+ Assert.Equal(-30d, features[0].GetProperty("resolvedPoint3")[0].GetDouble());
+ Assert.Equal(30d, features[1].GetProperty("resolvedPoint3")[0].GetDouble());
+ Assert.All(features.EnumerateArray(), f =>
+ {
+ Assert.Equal(8.5d, f.GetProperty("diameter").GetDouble());
+ Assert.Equal("AirHoleCompositeMaterializer", f.GetProperty("materializationRoute").GetString());
+ });
+
+ var import = Step242Importer.ImportBody(File.ReadAllText(stepPath));
+ Assert.True(import.IsSuccess, string.Join(Environment.NewLine, import.Diagnostics.Select(d => d.Message)));
+ var body = import.Value;
+ var cylinders = body.Topology.Faces.Select(f => body.TryGetFaceSurface(f.Id, out var surface) ? surface : null)
+ .Where(s => s?.Kind == SurfaceGeometryKind.Cylinder).Select(s => s!.Cylinder!.Value).OrderBy(c => c.Origin.X).ToArray();
+ Assert.Equal(2, cylinders.Length);
+ Assert.Equal([-30d, 30d], cylinders.Select(c => c.Origin.X));
+ Assert.All(cylinders, cylinder =>
+ {
+ Assert.Equal(0d, cylinder.Origin.Y);
+ Assert.Equal(4.25d, cylinder.Radius);
+ Assert.Equal(1d, cylinder.Axis.Z);
+ });
+ var points = body.Topology.Vertices.Select(v => body.TryGetVertexPoint(v.Id, out var point) ? point : throw new InvalidOperationException()).ToArray();
+ Assert.Equal((-40d, -25d, 0d, 40d, 25d, 25d),
+ (points.Min(p => p.X), points.Min(p => p.Y), points.Min(p => p.Z), points.Max(p => p.X), points.Max(p => p.Y), points.Max(p => p.Z)));
+ var topCircleCenters = body.Geometry.Curves.Select(entry => entry.Value).Where(c => c.Kind == CurveGeometryKind.Circle3 && Math.Abs(c.Circle3!.Value.Center.Z - 25d) < 1e-9)
+ .Select(c => c.Circle3!.Value.Center).OrderBy(p => p.X).ToArray();
+ Assert.Contains(topCircleCenters, p => Math.Abs(p.X + 30d) < 1e-9 && Math.Abs(p.Y) < 1e-9);
+ Assert.Contains(topCircleCenters, p => Math.Abs(p.X - 30d) < 1e-9 && Math.Abs(p.Y) < 1e-9);
+
+ var analyzeOut = new StringWriter();
+ Assert.Equal(0, CliRunner.Run(["analyze", stepPath, "--json"], analyzeOut, new StringWriter()));
+ using var analysis = JsonDocument.Parse(analyzeOut.ToString());
+ var summary = analysis.RootElement.GetProperty("summary");
+ Assert.Equal(1, summary.GetProperty("bodyCount").GetInt32());
+ Assert.Equal(1, summary.GetProperty("shellCount").GetInt32());
+ Assert.Equal("enclosed-manifold", summary.GetProperty("structuralAssessment").GetString());
+ Assert.Equal(2, summary.GetProperty("surfaceFamilies").GetProperty("cylinder").GetInt32());
+
+ var volume = StepAnalyzer.AnalyzeVolume(stepPath);
+ Assert.True(volume.Success);
+ Assert.True(volume.Exact);
+ Assert.Equal("analytic-box-minus-z-hole", volume.Method);
+ Assert.InRange(Math.Abs(volume.Volume - (80d * 50d * 25d - 2d * Math.PI * 4.25d * 4.25d * 25d)), 0d, 1e-8);
+ }
+
+ [Fact]
+ public void ConceptHolesCombinedWithProductionChamfer_FailsExplicitly()
+ {
+ var combined = Source.Replace(" }\r\n }\r\n Expose {", " }\r\n EdgeFinish TopBreak {\r\n Face: BracketConcept.TopPlane\r\n Target: Boundary\r\n Kind: Chamfer\r\n Distance: 1.5mm\r\n }\r\n }\r\n Expose {", StringComparison.Ordinal)
+ .Replace(" }\n }\n Expose {", " }\n EdgeFinish TopBreak {\n Face: BracketConcept.TopPlane\n Target: Boundary\n Kind: Chamfer\n Distance: 1.5mm\n }\n }\n Expose {", StringComparison.Ordinal);
+ var dir = Path.Combine(Path.GetTempPath(), "aetheris-concept-materialization-m2-combined", Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(dir);
+ var sourcePath = Path.Combine(dir, "combined.firmament"); File.WriteAllText(sourcePath, combined);
+ var stdout = new StringWriter();
+
+ var exit = CliRunner.Run(["build", sourcePath, "--out", Path.Combine(dir, "combined.step"), "--json"], stdout, new StringWriter());
+
+ Assert.Equal(1, exit);
+ Assert.Contains("air-chamfer-production-route-requires-one-box-and-one-edge-finish", stdout.ToString(), StringComparison.Ordinal);
+ }
+
+ private static string Source => File.ReadAllText(Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../demos/concept-materialization-m2.firmament")));
+}
diff --git a/Aetheris.CLI.Tests/FirmamentV2ConceptStructStepPipelineTests.cs b/Aetheris.CLI.Tests/FirmamentV2ConceptStructStepPipelineTests.cs
new file mode 100644
index 00000000..b2254210
--- /dev/null
+++ b/Aetheris.CLI.Tests/FirmamentV2ConceptStructStepPipelineTests.cs
@@ -0,0 +1,74 @@
+using System.Text;
+using System.Text.Json;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class FirmamentV2ConceptStructStepPipelineTests
+{
+ [Fact]
+ public void ConceptStruct_DrivesAirChamferAndExportsReimportableStepWithProvenance()
+ {
+ var dir = Path.Combine(Path.GetTempPath(), "aetheris-concept-expansion-m1", Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(dir);
+ var sourcePath = Path.Combine(dir, "concept-bracket.firmament");
+ var stepPath = Path.Combine(dir, "concept-bracket.step");
+ File.WriteAllText(sourcePath, Source);
+ var stdout = new StringWriter(); var stderr = new StringWriter();
+
+ var exit = CliRunner.Run(["build", sourcePath, "--out", stepPath, "--json"], stdout, stderr);
+
+ Assert.Equal(0, exit);
+ using var json = JsonDocument.Parse(stdout.ToString());
+ var conceptIr = json.RootElement.GetProperty("conceptIr");
+ Assert.Equal("ErasedBeforeFeatureAir", conceptIr.GetProperty("erasureStatus").GetString());
+ Assert.False(conceptIr.GetProperty("structs")[0].GetProperty("materialized").GetBoolean());
+ var air = json.RootElement.GetProperty("air");
+ Assert.Equal("BracketConcept.Bounds", air.GetProperty("feature").GetProperty("provenance").GetProperty("Bounds").GetString());
+ Assert.Equal("BracketConcept.TopPlane", air.GetProperty("feature").GetProperty("provenance").GetProperty("Selection").GetString());
+ Assert.Equal("AirPrismaticTopFaceBoundaryChamfer", air.GetProperty("materialization").GetProperty("route").GetString());
+ Assert.True(air.GetProperty("step").GetProperty("reimportSucceeded").GetBoolean());
+ var import = Step242Importer.ImportBody(File.ReadAllText(stepPath, Encoding.UTF8));
+ Assert.True(import.IsSuccess, string.Join(Environment.NewLine, import.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(1, json.RootElement.GetProperty("conceptIr").GetProperty("structs").GetArrayLength());
+ Assert.Equal(12, import.Value.Topology.Vertices.Count());
+ Assert.Equal(20, import.Value.Topology.Edges.Count());
+ Assert.Equal(10, import.Value.Topology.Faces.Count());
+ }
+
+ private const string Source = """
+ Concept MountingFrame {
+ Bounds: Box3
+ TopPlane: Plane
+ CenterAxis: Axis
+ MountPoints: Point3[]
+ }
+ Concept Struct BracketConcept: MountingFrame {
+ Bounds: Box3 { Size: [80mm, 50mm, 25mm] }
+ TopPlane: Bounds.Face(+Z)
+ CenterAxis: Bounds.Center.Axis(+Z)
+ MountPoints: Grid {
+ Within: Bounds.Face(+Z).Inset(10mm)
+ Columns: 2
+ Rows: 1
+ }
+ }
+ Struct Bracket: MountingFrame {
+ Box Base { Bounds: BracketConcept.Bounds }
+ Modify Base {
+ EdgeFinish TopBreak {
+ Face: BracketConcept.TopPlane
+ Target: Boundary
+ Kind: Chamfer
+ Distance: 1.5mm
+ }
+ }
+ Expose {
+ Bounds: BracketConcept.Bounds
+ TopPlane: Base.Top
+ CenterAxis: BracketConcept.CenterAxis
+ MountPoints: BracketConcept.MountPoints
+ }
+ }
+ """;
+}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 8da2cf2e..7ec92c14 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -261,7 +261,9 @@ public static class CliRunner
success = true,
sourcePath = build.Value.SourcePath,
outputPath = build.Value.OutputPath,
+ conceptIr = build.Value.Export.ConceptIr,
air = build.Value.Export.Air,
+ features = build.Value.Export.Features,
inlineStepMigration = build.Value.Export.InlineStepMigration,
inlineStepReplacementAssist = build.Value.Export.InlineStepReplacementAssist,
pmiExportEvidence = new
diff --git a/Aetheris.Kernel.Core/Air/AirHoleFeature.cs b/Aetheris.Kernel.Core/Air/AirHoleFeature.cs
index 60a6fdaa..bbdf2c05 100644
--- a/Aetheris.Kernel.Core/Air/AirHoleFeature.cs
+++ b/Aetheris.Kernel.Core/Air/AirHoleFeature.cs
@@ -146,7 +146,24 @@ internal sealed record AirHoleFeature(
private static AirDiagnostic Error(string code, string message) => new(code, AirDiagnosticSeverity.Error, message);
}
-internal sealed record AirFaceLocalHolePlacement(string EntryFaceName, double U, double V, string FrameConvention, string? StableFaceSelector = null);
+internal sealed record AirResolvedPoint3PlacementSource(
+ double X,
+ double Y,
+ double Z,
+ string StableId,
+ string SourceMember,
+ int? Ordinal,
+ string PlacementFace,
+ double PlaneDistance,
+ string SourceSpan);
+
+internal sealed record AirFaceLocalHolePlacement(
+ string EntryFaceName,
+ double U,
+ double V,
+ string FrameConvention,
+ string? StableFaceSelector = null,
+ AirResolvedPoint3PlacementSource? ResolvedPoint3 = null);
internal sealed record AirHoleAxis(Direction3D Direction, bool DefaultedFromEntryFaceNormal);
internal sealed record AirHoleShaft(double Diameter)
{
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2ConceptExpansionTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2ConceptExpansionTests.cs
new file mode 100644
index 00000000..465d8bdc
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2ConceptExpansionTests.cs
@@ -0,0 +1,176 @@
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class FirmamentV2ConceptExpansionTests
+{
+ [Fact]
+ public void ConceptStruct_ResolvesSpatialMembersAndDeterministicGridWithoutMaterializing()
+ {
+ var parse = FirmamentV2Parser.Parse(Source("Struct"));
+
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ var ir = Assert.IsType<ConceptIrDocument>(parse.Document!.ConceptIr);
+ var concept = Assert.Single(ir.Concepts);
+ Assert.Equal("MountingFrame", concept.Name);
+ Assert.Equal("Point3[]", concept.Members["MountPoints"].Type.ToString());
+ var conceptStruct = Assert.Single(ir.Structs);
+ Assert.False(conceptStruct.Materialized);
+ Assert.Equal("CompileTimeOnlyErased", conceptStruct.ErasureStatus);
+ var bounds = Assert.IsType<ConceptIrBox3Value>(conceptStruct.Members["Bounds"]);
+ Assert.Equal([80d, 50d, 25d], bounds.Size);
+ var plane = Assert.IsType<ConceptIrPlaneValue>(conceptStruct.Members["TopPlane"]);
+ Assert.Equal(new ConceptIrPoint3(0, 0, 25), plane.Origin);
+ Assert.Equal(new ConceptIrVector3(0, 0, 1), plane.Normal);
+ var axis = Assert.IsType<ConceptIrAxisValue>(conceptStruct.Members["CenterAxis"]);
+ Assert.Equal(new ConceptIrPoint3(0, 0, 12.5), axis.Origin);
+ var points = Assert.IsType<ConceptIrPointSetValue>(conceptStruct.Members["MountPoints"]);
+ Assert.Equal(2, points.Points.Count);
+ Assert.Equal(new ConceptIrPoint3(-30, 0, 25), points.Points[0].Point);
+ Assert.Equal(new ConceptIrPoint3(30, 0, 25), points.Points[1].Point);
+ Assert.Equal([0, 1], points.Points.Select(p => p.Ordinal));
+ Assert.All(points.Points, point => Assert.StartsWith("concept:BracketConcept.MountPoints[", point.StableId, StringComparison.Ordinal));
+ Assert.Equal("ErasedBeforeFeatureAir", ir.ErasureStatus);
+ Assert.Single(parse.Document.Solids);
+ }
+
+ [Theory]
+ [InlineData("Struct")]
+ [InlineData("Model")]
+ public void StructAndModel_NormalizeToSameMaterializedDocument(string spelling)
+ {
+ var parse = FirmamentV2Parser.Parse(Source(spelling));
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ Assert.Equal("Bracket", parse.Document!.ModelName);
+ Assert.Equal("Box", parse.Document.Solid.RecordType);
+ Assert.Equal([80d, 50d, 25d], parse.Document.Solid.Box!.Size);
+ Assert.Equal(spelling, parse.Document.ConceptIr!.MaterializedStruct.SourceSpelling);
+ }
+
+ [Fact]
+ public void StructuralConformance_ReportsMissingMember()
+ {
+ var source = Source("Struct").Replace(" CenterAxis: Bounds.Center.Axis(+Z)\r\n", string.Empty, StringComparison.Ordinal)
+ .Replace(" CenterAxis: Bounds.Center.Axis(+Z)\n", string.Empty, StringComparison.Ordinal);
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.False(parse.IsSuccess);
+ Assert.Contains(parse.Diagnostics, d => d.StartsWith(ConceptIrResolver.MissingMember + ":BracketConcept.CenterAxis", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void StaticReference_IndexOutOfRange_IsDiagnosedBeforeLowering()
+ {
+ var source = Source("Struct").Replace(" Box Base {", " Anchor: BracketConcept.MountPoints[2]\n Box Base {", StringComparison.Ordinal);
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.False(parse.IsSuccess);
+ Assert.Contains(parse.Diagnostics, d => d.StartsWith(ConceptIrResolver.IndexOutOfRange + ":BracketConcept.MountPoints[2]", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void ConceptStruct_CircularDependency_IsDiagnosed()
+ {
+ var source = Source("Struct").Replace(" TopPlane: Bounds.Face(+Z)", " TopPlane: CenterAxis\n CenterAxis: TopPlane", StringComparison.Ordinal)
+ .Replace(" CenterAxis: Bounds.Center.Axis(+Z)\n", string.Empty, StringComparison.Ordinal);
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.False(parse.IsSuccess);
+ Assert.Contains(ConceptIrResolver.CircularDependency, parse.Diagnostics);
+ }
+
+ [Fact]
+ public void MaterializedStruct_RequiresExplicitTypedExposeSurface()
+ {
+ var valid = FirmamentV2Parser.Parse(Source("Struct"));
+ Assert.True(valid.IsSuccess, string.Join(Environment.NewLine, valid.Diagnostics));
+ var materialized = valid.Document!.ConceptIr!.MaterializedStruct;
+ Assert.Equal("Valid", materialized.Conformance);
+ Assert.Equal(["Bounds", "TopPlane", "CenterAxis", "MountPoints"], materialized.ExposedMembers.Select(m => m.Name));
+ Assert.Equal(ConceptIrSemanticPhase.FeatureAir, materialized.ExposedMembers.Single(m => m.Name == "TopPlane").Phase);
+ Assert.Equal("Base.Top", materialized.ExposedMembers.Single(m => m.Name == "TopPlane").SemanticReference);
+
+ var missing = FirmamentV2Parser.Parse(Source("Struct").Replace(ExposeBlock, string.Empty, StringComparison.Ordinal));
+ Assert.False(missing.IsSuccess);
+ Assert.Contains(missing.Diagnostics, d => d == ConceptIrResolver.MissingMember + ":Bracket.Bounds");
+ }
+
+ [Fact]
+ public void MaterializedExpose_DiagnosesDuplicateUnknownMismatchInvalidAndCircularMembers()
+ {
+ var duplicate = FirmamentV2Parser.Parse(Source("Struct").Replace("Bounds: BracketConcept.Bounds", "Bounds: BracketConcept.Bounds\n Bounds: BracketConcept.Bounds", StringComparison.Ordinal));
+ Assert.Contains(duplicate.Diagnostics, d => d.StartsWith(ConceptIrResolver.DuplicateExposedMember, StringComparison.Ordinal));
+
+ var unknown = FirmamentV2Parser.Parse(Source("Struct").Replace("TopPlane: Base.Top", "TopPlane: Base.Top\n Extra: Base.Top", StringComparison.Ordinal));
+ Assert.Contains(unknown.Diagnostics, d => d == ConceptIrResolver.UnknownMember + ":Bracket.Extra");
+
+ var mismatch = FirmamentV2Parser.Parse(Source("Struct").Replace("TopPlane: Base.Top", "TopPlane: BracketConcept.Bounds", StringComparison.Ordinal));
+ Assert.Contains(mismatch.Diagnostics, d => d.StartsWith(ConceptIrResolver.TypeMismatch + ":Bracket.TopPlane", StringComparison.Ordinal));
+
+ var invalid = FirmamentV2Parser.Parse(Source("Struct").Replace("TopPlane: Base.Top", "TopPlane: Base.Bottomless", StringComparison.Ordinal));
+ Assert.Contains(invalid.Diagnostics, d => d.StartsWith(ConceptIrResolver.InvalidMaterializedReference + ":TopPlane", StringComparison.Ordinal));
+
+ var unrepresentable = FirmamentV2Parser.Parse(Source("Struct").Replace("TopPlane: Base.Top", "TopPlane: Base.TopFaceId", StringComparison.Ordinal));
+ Assert.Contains(unrepresentable.Diagnostics, d => d.StartsWith(ConceptIrResolver.ExposedMemberUnrepresentable + ":TopPlane", StringComparison.Ordinal));
+
+ var circular = FirmamentV2Parser.Parse(Source("Struct").Replace("TopPlane: Base.Top", "TopPlane: CenterAxis", StringComparison.Ordinal)
+ .Replace("CenterAxis: BracketConcept.CenterAxis", "CenterAxis: TopPlane", StringComparison.Ordinal));
+ Assert.Contains(circular.Diagnostics, d => d.StartsWith(ConceptIrResolver.CircularExposureDependency + ":TopPlane", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void PointIdentity_IsStableWhenUnrelatedConceptDeclarationIsAdded()
+ {
+ var baseline = FirmamentV2Parser.Parse(Source("Struct")).Document!.ConceptIr!.ResolvedValues.OfType<ConceptIrPoint3Value>().ToArray();
+ var changed = FirmamentV2Parser.Parse("Concept Unrelated { Datum: Plane }\n" + Source("Struct")).Document!.ConceptIr!.ResolvedValues.OfType<ConceptIrPoint3Value>().ToArray();
+ Assert.Equal(baseline.Select(p => (p.StableId, p.Ordinal, p.Point)), changed.Select(p => (p.StableId, p.Ordinal, p.Point)));
+ }
+
+ internal static string Source(string materializedKeyword) => $$"""
+ Concept MountingFrame {
+ Bounds: Box3
+ TopPlane: Plane
+ CenterAxis: Axis
+ MountPoints: Point3[]
+ }
+
+ Concept Struct BracketConcept: MountingFrame {
+ Bounds: Box3 {
+ Size: [80mm, 50mm, 25mm]
+ }
+ TopPlane: Bounds.Face(+Z)
+ CenterAxis: Bounds.Center.Axis(+Z)
+ MountPoints: Grid {
+ Within: Bounds.Face(+Z).Inset(10mm)
+ Columns: 2
+ Rows: 1
+ }
+ }
+
+ {{materializedKeyword}} Bracket: MountingFrame {
+ Box Base {
+ Bounds: BracketConcept.Bounds
+ }
+ Modify Base {
+ EdgeFinish TopBreak {
+ Face: BracketConcept.TopPlane
+ Target: Boundary
+ Kind: Chamfer
+ Distance: 1.5mm
+ }
+ }
+ Expose {
+ Bounds: BracketConcept.Bounds
+ TopPlane: Base.Top
+ CenterAxis: BracketConcept.CenterAxis
+ MountPoints: BracketConcept.MountPoints
+ }
+ }
+ """;
+
+ private const string ExposeBlock = """
+ Expose {
+ Bounds: BracketConcept.Bounds
+ TopPlane: Base.Top
+ CenterAxis: BracketConcept.CenterAxis
+ MountPoints: BracketConcept.MountPoints
+ }
+ """;
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2ConceptPoint3HoleTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2ConceptPoint3HoleTests.cs
new file mode 100644
index 00000000..27483e38
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2ConceptPoint3HoleTests.cs
@@ -0,0 +1,87 @@
+using Aetheris.Kernel.Core.Air;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class FirmamentV2ConceptPoint3HoleTests
+{
+ [Fact]
+ public void ConceptPoint3_LowersThroughSemanticHoleAirWithTypedPlacementProvenance()
+ {
+ var parse = FirmamentV2Parser.Parse(Source);
+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));
+ var holes = Assert.Single(parse.Document!.ModifyBlocks!).SemanticHoles;
+ Assert.Equal(2, holes.Count);
+ Assert.Equal([-30d, 30d], holes.Select(h => h.Center.U));
+ Assert.Equal([0, 1], holes.Select(h => h.ResolvedCenter!.Ordinal));
+ Assert.Equal(["concept:BracketConcept.MountPoints[0]", "concept:BracketConcept.MountPoints[1]"], holes.Select(h => h.ResolvedCenter!.StableId));
+ Assert.All(holes, h =>
+ {
+ Assert.Equal(25d, h.ResolvedCenter!.Z);
+ Assert.Equal(0d, h.ResolvedCenter.PlaneDistance);
+ Assert.Equal("Base.Top", h.ResolvedCenter.PlacementFace);
+ });
+
+ var air = FirmamentV2SemanticHoleLowering.LowerSemanticHoles(parse.Document);
+ Assert.Equal(2, air.Count);
+ Assert.All(air, feature =>
+ {
+ Assert.Equal(AirHoleStackKind.SimpleShaft, feature.Stack.Kind);
+ Assert.Equal(8.5d, feature.Shaft.Diameter);
+ Assert.NotNull(feature.Placement.ResolvedPoint3);
+ Assert.Equal("CONCEPT-MATERIALIZATION-M2", feature.Provenance.Milestone);
+ Assert.Contains(feature.Provenance.Notes, n => n.StartsWith("center-stable-id:concept:BracketConcept.MountPoints[", StringComparison.Ordinal));
+ });
+ }
+
+ [Fact]
+ public void ConceptPoint3_NotOnSelectedPlane_IsRejectedWithoutProjection()
+ {
+ var source = Source.Replace("Within: Bounds.Face(+Z).Inset(10mm)", "Within: Bounds.Face(-Z).Inset(10mm)", StringComparison.Ordinal);
+ var parse = FirmamentV2Parser.Parse(source);
+ Assert.False(parse.IsSuccess);
+ Assert.Contains(parse.Diagnostics, d => d.StartsWith(ConceptIrResolver.PointNotOnPlacementPlane + ":BracketConcept.MountPoints[0]", StringComparison.Ordinal));
+ }
+
+ internal const string Source = """
+ Concept MountingFrame {
+ Bounds: Box3
+ TopPlane: Plane
+ CenterAxis: Axis
+ MountPoints: Point3[]
+ }
+ Concept Struct BracketConcept: MountingFrame {
+ Bounds: Box3 { Size: [80mm, 50mm, 25mm] }
+ TopPlane: Bounds.Face(+Z)
+ CenterAxis: Bounds.Center.Axis(+Z)
+ MountPoints: Grid {
+ Within: Bounds.Face(+Z).Inset(10mm)
+ Columns: 2
+ Rows: 1
+ }
+ }
+ Struct Bracket: MountingFrame {
+ Box Base { Bounds: BracketConcept.Bounds }
+ Modify Base {
+ hole<shaft> LeftMount {
+ on: Base.Top
+ center: BracketConcept.MountPoints[0]
+ diameter: 8.5mm
+ end: throughAll
+ }
+ hole<shaft> RightMount {
+ on: Base.Top
+ center: BracketConcept.MountPoints[1]
+ diameter: 8.5mm
+ end: throughAll
+ }
+ }
+ Expose {
+ Bounds: BracketConcept.Bounds
+ TopPlane: Base.Top
+ CenterAxis: BracketConcept.CenterAxis
+ MountPoints: BracketConcept.MountPoints
+ }
+ }
+ """;
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index 5cb6446e..4b08d922 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -182,8 +182,11 @@ public static class FirmamentBuildAndExport
var top = plan.Vertices.Where(v => v.SectionIndex == 2).Select(v => v.Point).ToArray();
var sourceBounds = Bounds(compiled.Body);
var reimportedBounds = Bounds(reimported);
+ var featureProvenance = new Dictionary<string, string>(StringComparer.Ordinal);
+ if (solid.Provenance?.TryGetValue("Bounds", out var boundsProvenance) == true) featureProvenance["Bounds"] = boundsProvenance;
+ if (finish.Provenance?.TryGetValue("Face", out var faceProvenance) == true) featureProvenance["Selection"] = faceProvenance;
var report = new FirmamentAirChamferReport(
- new("Chamfer", compiled.Feature.BodyId, compiled.Feature.FeatureId, compiled.Feature.FeatureName, $"FaceBoundary({compiled.Feature.Selection.FaceAxis})", compiled.Feature.Rule.Distance, compiled.Feature.Rule.Unit, $"{compiled.Feature.SourceSpan.Start}:{compiled.Feature.SourceSpan.Length}", compiled.Feature.Admission.ToString(), compiled.Feature.AdmissionReason),
+ new("Chamfer", compiled.Feature.BodyId, compiled.Feature.FeatureId, compiled.Feature.FeatureName, $"FaceBoundary({compiled.Feature.Selection.FaceAxis})", compiled.Feature.Rule.Distance, compiled.Feature.Rule.Unit, $"{compiled.Feature.SourceSpan.Start}:{compiled.Feature.SourceSpan.Length}", compiled.Feature.Admission.ToString(), compiled.Feature.AdmissionReason, featureProvenance),
new("SectionTransition", compiled.Construction.Profiles.Count, compiled.Construction.Profiles.Select(p => p.Z).ToArray(), compiled.Construction.Transition.Correspondence, compiled.Construction.Transition.SplitPolicy),
new(compiled.BRepPlan.IsAuthoritative, plan.Vertices.Count, plan.Edges.Count, plan.Faces.Count, plan.ExpectedLoopCount, plan.ExpectedCoedgeCount, compiled.BRepPlan.Summary.ChamferFaceCount, plan.SplitPolicy, plan.DeterministicSignature),
new(AirTopFaceBoundaryChamferCompileResult.ProductionRoute, false, manifold, compiled.Topology.VertexCount, compiled.Topology.EdgeCount, compiled.Topology.FaceCount, sourceBounds,
@@ -192,7 +195,7 @@ public static class FirmamentBuildAndExport
reimported.Topology.Vertices.Count(), reimported.Topology.Edges.Count(), reimported.Topology.Faces.Count(), reimportedBounds, reimportedManifold));
return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(
- step.Value, compiled.Feature.FeatureId, 0, "air-chamfer", "top-face-boundary-chamfer", Air: report));
+ step.Value, compiled.Feature.FeatureId, 0, "air-chamfer", "top-face-boundary-chamfer", Air: report, ConceptIr: document.ConceptIr));
}
private static string Bounds(BrepBody body)
@@ -462,7 +465,11 @@ public static class FirmamentBuildAndExport
}
var feature = semanticHoles[0];
- var host = new AirHoleSimpleShaftHost(box.Size[0], box.Size[1], -box.Size[2] / 2d, box.Size[2] / 2d);
+ // Concept Box3 uses an XY-centered frame with Z in [0, height]. Preserve that frame for
+ // Concept-driven holes so the materialized face and resolved Point3 share coordinates.
+ var host = document.ConceptIr is null
+ ? new AirHoleSimpleShaftHost(box.Size[0], box.Size[1], -box.Size[2] / 2d, box.Size[2] / 2d)
+ : new AirHoleSimpleShaftHost(box.Size[0], box.Size[1], 0d, box.Size[2]);
Aetheris.Kernel.Core.Brep.BrepBody? body;
IReadOnlyList<string> diagnostics;
if (semanticHoles.Count == 1)
@@ -493,6 +500,20 @@ public static class FirmamentBuildAndExport
return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);
}
+ var featureReports = semanticHoles.Select(h => new FirmamentHoleFeatureReport(
+ h.Name,
+ "Hole",
+ h.FeatureId,
+ h.Shaft.Diameter,
+ h.Placement.U,
+ h.Placement.V,
+ h.Placement.ResolvedPoint3 is { } p ? new[] { p.X, p.Y, p.Z } : null,
+ h.Placement.ResolvedPoint3 is { } sourcePoint ? sourcePoint.Ordinal is { } ordinal ? $"{sourcePoint.SourceMember}[{ordinal}]" : sourcePoint.SourceMember : null,
+ h.Placement.ResolvedPoint3?.StableId,
+ h.Placement.ResolvedPoint3?.Ordinal,
+ h.Placement.ResolvedPoint3?.PlacementFace ?? h.Placement.EntryFaceName,
+ h.Placement.ResolvedPoint3?.SourceSpan,
+ semanticHoles.Count == 1 ? nameof(AirHoleSimpleShaftMaterializer) : nameof(AirHoleCompositeMaterializer))).ToArray();
return KernelResult<FirmamentStepExportResult>.Success(
new FirmamentStepExportResult(
step.Value,
@@ -501,7 +522,9 @@ public static class FirmamentBuildAndExport
semanticHoles.Count == 1 ? nameof(AirHoleSimpleShaftMaterializer) : nameof(AirHoleCompositeMaterializer),
semanticHoles.Count == 1 ? feature.Stack.Kind.ToString() : "CompositeSimpleShaft",
DatumInspection: document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.DatumPlane).Select(p => new FirmamentPmiInspectionDatum(p.Name, "planar", p.Target)).ToArray() ?? [],
- DimensionInspection: document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.HoleDiameter).Select(p => new FirmamentPmiInspectionDimension("Diameter", p.Target, null, p.Value ?? 0d, "explicit-v2-semantic-pmi", null)).ToArray() ?? []));
+ DimensionInspection: document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.HoleDiameter).Select(p => new FirmamentPmiInspectionDimension("Diameter", p.Target, null, p.Value ?? 0d, "explicit-v2-semantic-pmi", null)).ToArray() ?? [],
+ ConceptIr: document.ConceptIr,
+ Features: featureReports));
}
private static KernelResult<bool> ValidateV2PmiExportSupport(FirmamentV2Document document)
diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
index 75943866..f4b2f7a6 100644
--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs
@@ -12,7 +12,24 @@ public sealed record FirmamentStepExportResult(
IReadOnlyList<FirmamentPmiInspectionDimension>? DimensionInspection = null,
Aetheris.Kernel.Firmament.FirmamentV2.InlineStepMigrationReport? InlineStepMigration = null,
Aetheris.Kernel.Firmament.FirmamentV2.InlineStepReplacementAssistReport? InlineStepReplacementAssist = null,
- FirmamentAirChamferReport? Air = null);
+ FirmamentAirChamferReport? Air = null,
+ Aetheris.Kernel.Firmament.FirmamentV2.ConceptIrDocument? ConceptIr = null,
+ IReadOnlyList<FirmamentHoleFeatureReport>? Features = null);
+
+public sealed record FirmamentHoleFeatureReport(
+ string Name,
+ string Kind,
+ string FeatureId,
+ double Diameter,
+ double LocalU,
+ double LocalV,
+ IReadOnlyList<double>? ResolvedPoint3,
+ string? CenterSource,
+ string? CenterStableId,
+ int? PointOrdinal,
+ string PlacementFace,
+ string? SourceSpan,
+ string MaterializationRoute);
public sealed record FirmamentAirChamferReport(
FirmamentAirChamferFeatureReport Feature,
@@ -21,7 +38,7 @@ public sealed record FirmamentAirChamferReport(
FirmamentAirChamferMaterializationReport Materialization,
FirmamentAirChamferStepReport Step);
-public sealed record FirmamentAirChamferFeatureReport(string Kind, string Body, string FeatureId, string FeatureName, string Selection, double Distance, string Unit, string SourceSpan, string Admission, string AdmissionReason);
+public sealed record FirmamentAirChamferFeatureReport(string Kind, string Body, string FeatureId, string FeatureName, string Selection, double Distance, string Unit, string SourceSpan, string Admission, string AdmissionReason, IReadOnlyDictionary<string, string>? Provenance = null);
public sealed record FirmamentAirChamferConstructionReport(string Kind, int SectionCount, IReadOnlyList<double> SectionZ, string Correspondence, string SplitPolicy);
public sealed record FirmamentAirChamferBRepPlanReport(bool Authoritative, int ExpectedVertices, int ExpectedEdges, int ExpectedFaces, int ExpectedLoops, int ExpectedCoedges, int ChamferFaces, string SplitPolicy, string DeterministicSignature);
public sealed record FirmamentAirChamferMaterializationReport(string Route, bool LegacyFallback, bool EnclosedManifold, int Vertices, int Edges, int Faces, string Bounds, double MeasuredTopInsetX, double MeasuredTopInsetY);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
new file mode 100644
index 00000000..0834f962
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ConceptIr.cs
@@ -0,0 +1,583 @@
+using System.Globalization;
+using System.Text.Json.Serialization;
+using System.Text.RegularExpressions;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+public enum ConceptIrValueKind { Length, Point2, Point3, Vector3, Axis, Plane, Box2, Box3, Region2, PointSet }
+
+public sealed record ConceptIrType(string Name, bool IsCollection = false)
+{
+ public override string ToString() => Name + (IsCollection ? "[]" : string.Empty);
+}
+
+public sealed record ConceptIrMemberRequirement(string Name, ConceptIrType Type, FirmamentV2SourceSpan SourceSpan);
+public sealed record ConceptIrDefinition(string Name, IReadOnlyDictionary<string, ConceptIrMemberRequirement> Members, FirmamentV2SourceSpan SourceSpan);
+public sealed record ConceptIrPoint3(double X, double Y, double Z);
+public sealed record ConceptIrVector3(double X, double Y, double Z);
+
+[JsonPolymorphic(TypeDiscriminatorPropertyName = "$valueType")]
+[JsonDerivedType(typeof(ConceptIrBox3Value), "Box3")]
+[JsonDerivedType(typeof(ConceptIrPlaneValue), "Plane")]
+[JsonDerivedType(typeof(ConceptIrAxisValue), "Axis")]
+[JsonDerivedType(typeof(ConceptIrRegion2Value), "Region2")]
+[JsonDerivedType(typeof(ConceptIrPoint3Value), "Point3")]
+[JsonDerivedType(typeof(ConceptIrPointSetValue), "PointSet")]
+public abstract record ConceptIrValue(string StableId, ConceptIrValueKind Kind, string Provenance);
+public sealed record ConceptIrBox3Value(string StableId, ConceptIrPoint3 Min, ConceptIrPoint3 Max, string Provenance)
+ : ConceptIrValue(StableId, ConceptIrValueKind.Box3, Provenance)
+{
+ public IReadOnlyList<double> Size => [Max.X - Min.X, Max.Y - Min.Y, Max.Z - Min.Z];
+ public ConceptIrPoint3 Center => new((Min.X + Max.X) / 2d, (Min.Y + Max.Y) / 2d, (Min.Z + Max.Z) / 2d);
+}
+public sealed record ConceptIrPlaneValue(string StableId, ConceptIrPoint3 Origin, ConceptIrVector3 Normal, string Provenance)
+ : ConceptIrValue(StableId, ConceptIrValueKind.Plane, Provenance);
+public sealed record ConceptIrAxisValue(string StableId, ConceptIrPoint3 Origin, ConceptIrVector3 Direction, string Provenance)
+ : ConceptIrValue(StableId, ConceptIrValueKind.Axis, Provenance);
+public sealed record ConceptIrRegion2Value(string StableId, ConceptIrPoint3 Center, ConceptIrVector3 U, ConceptIrVector3 V, double MinU, double MaxU, double MinV, double MaxV, string FaceAxis, string Provenance)
+ : ConceptIrValue(StableId, ConceptIrValueKind.Region2, Provenance);
+public sealed record ConceptIrPoint3Value(string StableId, ConceptIrPoint3 Point, string Provenance, int? Ordinal = null)
+ : ConceptIrValue(StableId, ConceptIrValueKind.Point3, Provenance);
+public sealed record ConceptIrPointSetValue(string StableId, IReadOnlyList<ConceptIrPoint3Value> Points, string Provenance)
+ : ConceptIrValue(StableId, ConceptIrValueKind.PointSet, Provenance);
+
+public enum ConceptIrSemanticPhase { ConceptIr, FeatureAir }
+public enum ConceptIrMaterializationCategory { CompileTimeValue, MaterializedSemanticReference }
+
+public sealed record ConceptIrSemanticMember(
+ string Name,
+ ConceptIrType Type,
+ ConceptIrValue? Value,
+ string? SemanticReference,
+ ConceptIrSemanticPhase Phase,
+ ConceptIrMaterializationCategory MaterializationCategory,
+ string Provenance,
+ FirmamentV2SourceSpan SourceSpan,
+ string StableId);
+
+public sealed record ConceptIrStructInstance(
+ string Name,
+ IReadOnlyList<string> Satisfies,
+ IReadOnlyDictionary<string, ConceptIrValue> Members,
+ bool Materialized,
+ string ErasureStatus,
+ FirmamentV2SourceSpan SourceSpan);
+
+public sealed record ConceptIrMaterializedStruct(
+ string Name,
+ string SourceSpelling,
+ IReadOnlyList<string> Satisfies,
+ FirmamentV2SourceSpan SourceSpan,
+ IReadOnlyList<ConceptIrSemanticMember> ExposedMembers,
+ string Conformance);
+public sealed record ConceptIrBinding(string Consumer, string Input, string Provenance, string Kind);
+public sealed record ConceptIrDocument(
+ IReadOnlyList<ConceptIrDefinition> Concepts,
+ IReadOnlyList<ConceptIrStructInstance> Structs,
+ IReadOnlyList<ConceptIrValue> ResolvedValues,
+ ConceptIrMaterializedStruct MaterializedStruct,
+ IReadOnlyList<ConceptIrBinding> Bindings,
+ string ErasureStatus = "ErasedBeforeFeatureAir");
+
+internal sealed record ConceptPhase3Resolution(
+ string ModelName,
+ string SourceSpelling,
+ string Units,
+ string BoxName,
+ IReadOnlyList<double> BoxSize,
+ string BoxBoundsProvenance,
+ FirmamentV2ModifyBlock ModifyBlock,
+ ConceptIrDocument ConceptIr);
+
+internal static class ConceptIrResolver
+{
+ public const string MissingMember = "firmament-concept-missing-member";
+ public const string UnknownMember = "firmament-concept-unknown-member";
+ public const string TypeMismatch = "firmament-concept-type-mismatch";
+ public const string InvalidSpatialDerivation = "firmament-concept-invalid-spatial-derivation";
+ public const string IndexOutOfRange = "firmament-concept-index-out-of-range";
+ public const string CircularDependency = "firmament-concept-circular-dependency";
+ public const string MaterializedPhaseReference = "firmament-concept-materialized-value-in-compile-time-phase";
+ public const string DuplicateDeclaration = "firmament-concept-duplicate-declaration";
+ public const string DuplicateExposedMember = "firmament-concept-duplicate-exposed-member";
+ public const string InvalidMaterializedReference = "firmament-concept-invalid-materialized-reference";
+ public const string ExposedMemberUnrepresentable = "firmament-concept-exposed-member-cannot-be-represented-semantically";
+ public const string CircularExposureDependency = "firmament-concept-circular-exposure-dependency";
+ public const string PointNotOnPlacementPlane = "firmament-concept-point-not-on-placement-plane";
+ public const string PointOutsidePlacementFace = "firmament-concept-point-outside-placement-face";
+ public const string PointProjectionUnsupported = "firmament-concept-point-projection-unsupported";
+
+ private static readonly Regex ConceptHeader = new(@"\bConcept\s+(?!Struct\b)(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
+ private static readonly Regex ConceptStructHeader = new(@"\bConcept\s+Struct\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*(?::\s*(?<concept>[A-Za-z_][A-Za-z0-9_]*))?\s*\{", RegexOptions.CultureInvariant);
+ private static readonly Regex MaterializedHeader = new(@"\b(?<kind>Struct|Model)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*(?::\s*(?<concept>[A-Za-z_][A-Za-z0-9_]*))?\s*(?<units>mm\s*)?\{", RegexOptions.CultureInvariant);
+
+ public static ConceptPhase3Resolution? Resolve(string source, List<string> diagnostics)
+ {
+ var definitions = ParseDefinitions(source, diagnostics);
+ var materializedMatches = MaterializedHeader.Matches(source).Cast<Match>()
+ .Where(m => !IsPrecededByConcept(source, m.Index)).ToArray();
+ if (materializedMatches.Length != 1) { diagnostics.Add(FirmamentV2Parser.Phase3EdgeFinishSyntaxInvalid); return null; }
+ var materialized = materializedMatches[0];
+ var materializedOpen = source.IndexOf('{', materialized.Index);
+ var materializedClose = FindMatchingBrace(source, materializedOpen);
+ if (materializedClose < 0) { diagnostics.Add(FirmamentV2Parser.Phase3EdgeFinishSyntaxInvalid); return null; }
+
+ var instanceList = new List<ConceptIrStructInstance>();
+ var resolved = new List<ConceptIrValue>();
+ var instanceNames = new HashSet<string>(StringComparer.Ordinal);
+ foreach (Match match in ConceptStructHeader.Matches(source))
+ {
+ var name = match.Groups["name"].Value;
+ if (!instanceNames.Add(name)) { diagnostics.Add(DuplicateDeclaration); continue; }
+ var open = source.IndexOf('{', match.Index);
+ var close = FindMatchingBrace(source, open);
+ if (close < 0) { diagnostics.Add(InvalidSpatialDerivation); continue; }
+ var body = source[(open + 1)..close];
+ var members = ResolveMembers(name, body, open + 1, materialized.Groups["name"].Value, diagnostics);
+ var satisfies = match.Groups["concept"].Success ? new[] { match.Groups["concept"].Value } : [];
+ ValidateConformance(name, satisfies, members, definitions, diagnostics);
+ var instance = new ConceptIrStructInstance(name, satisfies, members, false, "CompileTimeOnlyErased", new(match.Index, close - match.Index + 1));
+ instanceList.Add(instance);
+ foreach (var value in members.Values)
+ {
+ resolved.Add(value);
+ if (value is ConceptIrPointSetValue set) resolved.AddRange(set.Points);
+ }
+ }
+
+ var bodyText = source[(materializedOpen + 1)..materializedClose];
+ ValidateIndexedReferences(bodyText, instanceList, diagnostics);
+ var box = Regex.Match(bodyText, @"\bBox\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
+ var modify = Regex.Match(bodyText, @"\bModify\s+(?<target>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
+ var edge = Regex.Match(bodyText, @"\bEdgeFinish\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
+ if (!box.Success || !modify.Success) { diagnostics.Add(FirmamentV2Parser.Phase3EdgeFinishSyntaxInvalid); return null; }
+ var boxOpen = materializedOpen + 1 + bodyText.IndexOf('{', box.Index);
+ var boxClose = FindMatchingBrace(source, boxOpen);
+ var modifyStart = materializedOpen + 1 + modify.Index;
+ var modifyOpen = source.IndexOf('{', modifyStart);
+ var modifyClose = FindMatchingBrace(source, modifyOpen);
+ if (boxClose < 0 || modifyClose < 0) { diagnostics.Add(FirmamentV2Parser.Phase3EdgeFinishSyntaxInvalid); return null; }
+
+ var allInstances = instanceList.ToDictionary(i => i.Name, StringComparer.Ordinal);
+ var boxBody = source[(boxOpen + 1)..boxClose];
+ IReadOnlyList<double>? size = null;
+ ConceptIrBox3Value? resolvedBounds = null;
+ string boundsProvenance;
+ var boundsRef = Regex.Match(boxBody, @"\bBounds\s*:\s*(?<instance>[A-Za-z_][A-Za-z0-9_]*)\.(?<member>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.CultureInvariant);
+ if (boundsRef.Success && TryMember(allInstances, boundsRef, out ConceptIrBox3Value? bounds, diagnostics))
+ {
+ size = bounds!.Size;
+ resolvedBounds = bounds;
+ boundsProvenance = bounds.Provenance;
+ }
+ else
+ {
+ var sizeMatch = Regex.Match(boxBody, @"\bSize\s*:\s*\[(?<values>[^\]]+)\]", RegexOptions.CultureInvariant);
+ var values = sizeMatch.Success ? sizeMatch.Groups["values"].Value.Split(',').Select(ParseLength).ToArray() : [];
+ size = values.Length == 3 && values.All(v => double.IsFinite(v) && v > 0) ? values : null;
+ boundsProvenance = $"{materialized.Groups["name"].Value}.{box.Groups["name"].Value}.Size";
+ }
+
+ if (size is null || box.Groups["name"].Value != modify.Groups["target"].Value)
+ {
+ diagnostics.Add(FirmamentV2Parser.Phase3EdgeFinishSyntaxInvalid);
+ return null;
+ }
+
+ var bindings = new List<ConceptIrBinding>
+ {
+ new($"{materialized.Groups["name"].Value}.{box.Groups["name"].Value}.Bounds", boundsRef.Success ? boundsRef.Value.Split(':', 2)[1].Trim() : "Size", boundsProvenance, "Box3")
+ };
+ var finishes = new List<FirmamentV2EdgeFinishDecl>();
+ if (edge.Success)
+ {
+ var edgeStart = materializedOpen + 1 + edge.Index;
+ var edgeOpen = source.IndexOf('{', edgeStart);
+ var edgeClose = FindMatchingBrace(source, edgeOpen);
+ if (edgeClose < 0) { diagnostics.Add(FirmamentV2Parser.Phase3EdgeFinishSyntaxInvalid); return null; }
+ var edgeBody = source[(edgeOpen + 1)..edgeClose];
+ var faceSource = FieldValue(edgeBody, "Face");
+ var faceAxis = faceSource;
+ var faceProvenance = $"{materialized.Groups["name"].Value}.{edge.Groups["name"].Value}.Face";
+ var faceRef = Regex.Match(faceSource, @"^(?<instance>[A-Za-z_][A-Za-z0-9_]*)\.(?<member>[A-Za-z_][A-Za-z0-9_]*)$", RegexOptions.CultureInvariant);
+ if (faceRef.Success && TryMember(allInstances, faceRef, out ConceptIrPlaneValue? plane, diagnostics))
+ {
+ faceAxis = AxisOf(plane!.Normal);
+ faceProvenance = plane.Provenance;
+ }
+ var target = FieldValue(edgeBody, "Target");
+ var kind = FieldValue(edgeBody, "Kind");
+ var distance = ParseLength(FieldValue(edgeBody, "Distance"));
+ if (!Regex.IsMatch(faceAxis, @"^[+-][XYZ]$", RegexOptions.CultureInvariant) || target.Length == 0 || kind.Length == 0 || !double.IsFinite(distance))
+ { diagnostics.Add(FirmamentV2Parser.Phase3EdgeFinishSyntaxInvalid); return null; }
+ finishes.Add(new(edge.Groups["name"].Value, faceAxis, target, kind, distance, new(edgeStart, edgeClose - edgeStart + 1),
+ new Dictionary<string, string>(StringComparer.Ordinal) { ["Face"] = faceProvenance }));
+ bindings.Add(new($"{materialized.Groups["name"].Value}.{edge.Groups["name"].Value}.Face", faceSource, faceProvenance, "Plane"));
+ }
+
+ var modifyBody = source[(modifyOpen + 1)..modifyClose];
+ var holes = ParseConceptHoles(modifyBody, modifyOpen + 1, box.Groups["name"].Value, resolvedBounds,
+ allInstances, materialized.Groups["name"].Value, bindings, diagnostics);
+ if (holes.Count == 0 && finishes.Count == 0) { diagnostics.Add(FirmamentV2Parser.Phase3EdgeFinishSyntaxInvalid); return null; }
+
+ var satisfiesMaterialized = materialized.Groups["concept"].Success ? new[] { materialized.Groups["concept"].Value } : [];
+ var exposed = ParseExposedMembers(bodyText, materializedOpen + 1, materialized.Groups["name"].Value, box.Groups["name"].Value, resolvedBounds,
+ allInstances, holes, diagnostics);
+ ValidateMaterializedConformance(materialized.Groups["name"].Value, satisfiesMaterialized, exposed, definitions, diagnostics);
+ var conformance = satisfiesMaterialized.Length == 0 ? "NotDeclared" : diagnostics.Any(d => IsConformanceDiagnostic(d)) ? "Invalid" : "Valid";
+ var ir = new ConceptIrDocument(definitions, instanceList, resolved,
+ new(materialized.Groups["name"].Value, materialized.Groups["kind"].Value, satisfiesMaterialized, new(materialized.Index, materializedClose - materialized.Index + 1), exposed, conformance), bindings);
+ var modifyBlock = new FirmamentV2ModifyBlock(modify.Groups["target"].Value, [], holes, finishes);
+ return new(materialized.Groups["name"].Value, materialized.Groups["kind"].Value, "mm", box.Groups["name"].Value, size, boundsProvenance,
+ modifyBlock, ir);
+ }
+
+ private static IReadOnlyList<FirmamentV2SemanticHoleDecl> ParseConceptHoles(
+ string body,
+ int bodyOffset,
+ string boxName,
+ ConceptIrBox3Value? bounds,
+ IReadOnlyDictionary<string, ConceptIrStructInstance> instances,
+ string materializedName,
+ List<ConceptIrBinding> bindings,
+ List<string> diagnostics)
+ {
+ const double tolerance = 1e-9;
+ var result = new List<FirmamentV2SemanticHoleDecl>();
+ var headers = Regex.Matches(body, @"\bhole\s*<\s*(?<variant>[A-Za-z_][A-Za-z0-9_]*)\s*>\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
+ foreach (Match header in headers)
+ {
+ if (!string.Equals(header.Groups["variant"].Value, "shaft", StringComparison.OrdinalIgnoreCase)) { diagnostics.Add(FirmamentV2Parser.HoleVariantUnknown); continue; }
+ var open = body.IndexOf('{', header.Index); var close = FindMatchingBrace(body, open);
+ if (close < 0) { diagnostics.Add(FirmamentV2Parser.RegionUnsupported); continue; }
+ var holeBody = body[(open + 1)..close];
+ var on = FieldValue(holeBody, "on");
+ var faceAxis = on switch
+ {
+ "face(+Z)" => "+Z",
+ _ when string.Equals(on, boxName + ".Top", StringComparison.Ordinal) => "+Z",
+ _ => ResolvePlaneAxis(on, instances, diagnostics)
+ };
+ if (faceAxis != "+Z") { diagnostics.Add(PointProjectionUnsupported + ":only-planar-+Z-placement-is-admitted"); continue; }
+ if (bounds is null) { diagnostics.Add(InvalidSpatialDerivation); continue; }
+
+ var centerMatch = Regex.Match(holeBody, @"\bcenter\s*:\s*(?<instance>[A-Za-z_][A-Za-z0-9_]*)\.(?<member>[A-Za-z_][A-Za-z0-9_]*)\[(?<index>[0-9]+)\]", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
+ if (!centerMatch.Success || !instances.TryGetValue(centerMatch.Groups["instance"].Value, out var instance)
+ || !instance.Members.TryGetValue(centerMatch.Groups["member"].Value, out var member) || member is not ConceptIrPointSetValue set)
+ { diagnostics.Add(InvalidSpatialDerivation); continue; }
+ var index = int.Parse(centerMatch.Groups["index"].Value, CultureInfo.InvariantCulture);
+ if (index >= set.Points.Count) { diagnostics.Add($"{IndexOutOfRange}:{centerMatch.Value}:count-{set.Points.Count}"); continue; }
+ var point = set.Points[index];
+ var planeZ = bounds.Max.Z;
+ var distance = point.Point.Z - planeZ;
+ if (Math.Abs(distance) > tolerance) { diagnostics.Add($"{PointNotOnPlacementPlane}:{point.Provenance}:distance-{distance.ToString("R", CultureInfo.InvariantCulture)}"); continue; }
+ if (point.Point.X < bounds.Min.X - tolerance || point.Point.X > bounds.Max.X + tolerance || point.Point.Y < bounds.Min.Y - tolerance || point.Point.Y > bounds.Max.Y + tolerance)
+ { diagnostics.Add($"{PointOutsidePlacementFace}:{point.Provenance}"); continue; }
+ var diameter = ParseLengthOrUnitless(FieldValue(holeBody, "diameter"));
+ if (!double.IsFinite(diameter) || diameter <= 0) { diagnostics.Add(FirmamentV2Parser.HoleDiameterInvalid); continue; }
+ var endSource = FieldValue(holeBody, "end");
+ if (!string.Equals(endSource, "throughAll", StringComparison.OrdinalIgnoreCase) && !string.Equals(endSource, "Through", StringComparison.OrdinalIgnoreCase))
+ { diagnostics.Add(FirmamentV2Parser.HoleEndMissing); continue; }
+
+ var absoluteCenterStart = bodyOffset + open + 1 + centerMatch.Index;
+ var resolved = new FirmamentV2ResolvedPoint3(point.Point.X, point.Point.Y, point.Point.Z, point.StableId, set.Provenance, point.Ordinal,
+ on, distance, new(absoluteCenterStart, centerMatch.Length));
+ var sourceSpan = new FirmamentV2SourceSpan(bodyOffset + header.Index, close - header.Index + 1);
+ var face = new FirmamentV2FaceTarget(on, on == "face(+Z)" ? "DirectSelector" : "SemanticReference", "+Z", "face(+Z)", "FaceRef");
+ result.Add(new(header.Groups["name"].Value, FirmamentV2SemanticHoleVariant.Shaft, face,
+ new(point.Point.X, point.Point.Y, FirmamentV2FaceLocalPoint2D.PlusZConvention), diameter,
+ new(FirmamentV2SemanticHoleEndKind.ThroughAll), ResolvedCenter: resolved, SourceSpan: sourceSpan));
+ bindings.Add(new($"{materializedName}.{header.Groups["name"].Value}.Center", point.Provenance, point.Provenance, "Point3"));
+ }
+ return result;
+ }
+
+ private static IReadOnlyList<ConceptIrSemanticMember> ParseExposedMembers(
+ string body,
+ int bodyOffset,
+ string materializedName,
+ string boxName,
+ ConceptIrBox3Value? bounds,
+ IReadOnlyDictionary<string, ConceptIrStructInstance> instances,
+ IReadOnlyList<FirmamentV2SemanticHoleDecl> holes,
+ List<string> diagnostics)
+ {
+ var expose = Regex.Match(body, @"\bExpose\s*\{(?<body>.*?)\}", RegexOptions.Singleline | RegexOptions.CultureInvariant);
+ if (!expose.Success) return [];
+ var result = new List<ConceptIrSemanticMember>();
+ var names = new HashSet<string>(StringComparer.Ordinal);
+ var fields = Regex.Matches(expose.Groups["body"].Value, @"(?m)^\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<value>[^\r\n}]+?)\s*$", RegexOptions.CultureInvariant).Cast<Match>().ToArray();
+ var fieldNames = fields.Select(f => f.Groups["name"].Value).ToHashSet(StringComparer.Ordinal);
+ var dependencies = new Dictionary<string, string>(StringComparer.Ordinal);
+ foreach (var field in fields) dependencies.TryAdd(field.Groups["name"].Value, field.Groups["value"].Value.Trim());
+ var cycleMembers = new HashSet<string>(StringComparer.Ordinal);
+ foreach (var start in dependencies.Keys)
+ {
+ var path = new HashSet<string>(StringComparer.Ordinal); var current = start;
+ while (fieldNames.Contains(current) && path.Add(current) && dependencies.TryGetValue(current, out current!)) { }
+ if (path.Contains(current)) foreach (var member in path) cycleMembers.Add(member);
+ }
+ foreach (var field in fields)
+ {
+ var name = field.Groups["name"].Value; var reference = field.Groups["value"].Value.Trim();
+ if (!names.Add(name)) { diagnostics.Add($"{DuplicateExposedMember}:{name}"); continue; }
+ if (cycleMembers.Contains(name)) { diagnostics.Add($"{CircularExposureDependency}:{name}->{reference}"); continue; }
+ var span = new FirmamentV2SourceSpan(bodyOffset + expose.Groups["body"].Index + field.Index, field.Length);
+ ConceptIrValue? value = null; string? semanticReference = null; ConceptIrSemanticPhase phase; ConceptIrMaterializationCategory category;
+ var dotted = Regex.Match(reference, @"^(?<instance>[A-Za-z_][A-Za-z0-9_]*)\.(?<member>[A-Za-z_][A-Za-z0-9_]*)$", RegexOptions.CultureInvariant);
+ if (dotted.Success && instances.TryGetValue(dotted.Groups["instance"].Value, out var instance) && instance.Members.TryGetValue(dotted.Groups["member"].Value, out value))
+ { phase = ConceptIrSemanticPhase.ConceptIr; category = ConceptIrMaterializationCategory.CompileTimeValue; }
+ else if (string.Equals(reference, boxName + ".Top", StringComparison.Ordinal) && bounds is not null)
+ {
+ value = new ConceptIrPlaneValue("materialized:" + reference, FaceCenter(bounds, "+Z"), Vector("+Z"), reference);
+ semanticReference = reference; phase = ConceptIrSemanticPhase.FeatureAir; category = ConceptIrMaterializationCategory.MaterializedSemanticReference;
+ }
+ else
+ {
+ var holeCenter = holes.FirstOrDefault(h => string.Equals(reference, h.Name + ".Center", StringComparison.Ordinal));
+ if (holeCenter?.ResolvedCenter is { } center)
+ {
+ value = new ConceptIrPoint3Value(center.StableId, new(center.X, center.Y, center.Z), center.SourceMember, center.Ordinal);
+ semanticReference = reference; phase = ConceptIrSemanticPhase.FeatureAir; category = ConceptIrMaterializationCategory.MaterializedSemanticReference;
+ }
+ else if ((reference.StartsWith(boxName + ".", StringComparison.Ordinal) || holes.Any(h => reference.StartsWith(h.Name + ".", StringComparison.Ordinal)))
+ && (reference.Contains("BRep", StringComparison.Ordinal) || reference.Contains("Topology", StringComparison.Ordinal) || reference.EndsWith("FaceId", StringComparison.Ordinal)))
+ { diagnostics.Add($"{ExposedMemberUnrepresentable}:{name}:{reference}"); continue; }
+ else { diagnostics.Add($"{InvalidMaterializedReference}:{name}:{reference}"); continue; }
+ }
+ result.Add(new(name, TypeOf(value), value, semanticReference, phase, category, value.Provenance, span, $"materialized:{materializedName}.exposed:{name}"));
+ }
+ return result;
+ }
+
+ private static void ValidateMaterializedConformance(string instance, IReadOnlyList<string> satisfies, IReadOnlyList<ConceptIrSemanticMember> members, IReadOnlyList<ConceptIrDefinition> definitions, List<string> diagnostics)
+ {
+ var byName = members.ToDictionary(m => m.Name, StringComparer.Ordinal);
+ foreach (var conceptName in satisfies)
+ {
+ var definition = definitions.SingleOrDefault(d => d.Name == conceptName);
+ if (definition is null) { diagnostics.Add(FirmamentV2Parser.ConceptUnknownConcept); continue; }
+ foreach (var required in definition.Members.Values)
+ {
+ if (!byName.TryGetValue(required.Name, out var member)) { diagnostics.Add($"{MissingMember}:{instance}.{required.Name}"); continue; }
+ if (member.Type != required.Type) diagnostics.Add($"{TypeMismatch}:{instance}.{required.Name}:expected-{required.Type}:actual-{member.Type}");
+ }
+ foreach (var member in members.Where(m => !definition.Members.ContainsKey(m.Name))) diagnostics.Add($"{UnknownMember}:{instance}.{member.Name}");
+ }
+ }
+
+ private static bool IsConformanceDiagnostic(string diagnostic) => diagnostic.StartsWith(MissingMember, StringComparison.Ordinal)
+ || diagnostic.StartsWith(UnknownMember, StringComparison.Ordinal) || diagnostic.StartsWith(TypeMismatch, StringComparison.Ordinal)
+ || diagnostic.StartsWith(DuplicateExposedMember, StringComparison.Ordinal) || diagnostic.StartsWith(InvalidMaterializedReference, StringComparison.Ordinal)
+ || diagnostic.StartsWith(CircularExposureDependency, StringComparison.Ordinal) || diagnostic.StartsWith(ExposedMemberUnrepresentable, StringComparison.Ordinal);
+
+ private static ConceptIrType TypeOf(ConceptIrValue value) => value is ConceptIrPointSetValue ? new("Point3", true) : new(value.Kind.ToString());
+
+ private static string ResolvePlaneAxis(string source, IReadOnlyDictionary<string, ConceptIrStructInstance> instances, List<string> diagnostics)
+ {
+ var match = Regex.Match(source, @"^(?<instance>[A-Za-z_][A-Za-z0-9_]*)\.(?<member>[A-Za-z_][A-Za-z0-9_]*)$", RegexOptions.CultureInvariant);
+ if (match.Success && TryMember(instances, match, out ConceptIrPlaneValue? plane, diagnostics)) return AxisOf(plane!.Normal);
+ return string.Empty;
+ }
+
+ private static IReadOnlyList<ConceptIrDefinition> ParseDefinitions(string source, List<string> diagnostics)
+ {
+ var result = new List<ConceptIrDefinition>();
+ var names = new HashSet<string>(StringComparer.Ordinal);
+ foreach (Match match in ConceptHeader.Matches(source))
+ {
+ var open = source.IndexOf('{', match.Index); var close = FindMatchingBrace(source, open);
+ if (close < 0) { diagnostics.Add(InvalidSpatialDerivation); continue; }
+ var name = match.Groups["name"].Value;
+ if (!names.Add(name)) { diagnostics.Add(DuplicateDeclaration); continue; }
+ var members = new Dictionary<string, ConceptIrMemberRequirement>(StringComparer.Ordinal);
+ var body = source[(open + 1)..close];
+ foreach (Match field in Regex.Matches(body, @"(?m)^\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<type>[A-Za-z_][A-Za-z0-9_]*)(?<array>\[\])?\s*$", RegexOptions.CultureInvariant))
+ {
+ var memberName = field.Groups["name"].Value;
+ if (!members.TryAdd(memberName, new(memberName, new(field.Groups["type"].Value, field.Groups["array"].Success), new(open + 1 + field.Index, field.Length)))) diagnostics.Add(DuplicateDeclaration);
+ }
+ result.Add(new(name, members, new(match.Index, close - match.Index + 1)));
+ }
+ return result;
+ }
+
+ private static IReadOnlyDictionary<string, ConceptIrValue> ResolveMembers(string instanceName, string body, int bodyOffset, string materializedName, List<string> diagnostics)
+ {
+ var result = new Dictionary<string, ConceptIrValue>(StringComparer.Ordinal);
+ DetectCircularDependencies(body, diagnostics);
+ var boundsMatch = Regex.Match(body, @"\b(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*Box3\s*\{", RegexOptions.CultureInvariant);
+ if (boundsMatch.Success)
+ {
+ var open = body.IndexOf('{', boundsMatch.Index); var close = FindMatchingBrace(body, open);
+ var sizeMatch = close > open ? Regex.Match(body[(open + 1)..close], @"\bSize\s*:\s*\[(?<values>[^\]]+)\]", RegexOptions.CultureInvariant) : Match.Empty;
+ var size = sizeMatch.Success ? sizeMatch.Groups["values"].Value.Split(',').Select(ParseLength).ToArray() : [];
+ if (size.Length == 3 && size.All(v => double.IsFinite(v) && v > 0))
+ {
+ var name = boundsMatch.Groups["name"].Value; var provenance = $"{instanceName}.{name}";
+ result[name] = new ConceptIrBox3Value(Id(provenance), new(-size[0] / 2d, -size[1] / 2d, 0), new(size[0] / 2d, size[1] / 2d, size[2]), provenance);
+ }
+ else diagnostics.Add(InvalidSpatialDerivation);
+ }
+
+ foreach (var field in TopLevelFields(body))
+ {
+ if (result.ContainsKey(field.Name) || field.Value.StartsWith("Box3", StringComparison.Ordinal) || field.Value.StartsWith("Grid", StringComparison.Ordinal)) continue;
+ if (field.Value.StartsWith(materializedName + ".", StringComparison.Ordinal)) { diagnostics.Add(MaterializedPhaseReference); continue; }
+ var face = Regex.Match(field.Value, @"^(?<box>[A-Za-z_][A-Za-z0-9_]*)\.Face\((?<axis>[+-][XYZ])\)$", RegexOptions.CultureInvariant);
+ var axis = Regex.Match(field.Value, @"^(?<box>[A-Za-z_][A-Za-z0-9_]*)\.Center\.Axis\((?<axis>[+-][XYZ])\)$", RegexOptions.CultureInvariant);
+ if (face.Success && result.TryGetValue(face.Groups["box"].Value, out var boxValue) && boxValue is ConceptIrBox3Value box)
+ {
+ var provenance = $"{instanceName}.{field.Name}"; var a = face.Groups["axis"].Value;
+ result[field.Name] = new ConceptIrPlaneValue(Id(provenance), FaceCenter(box, a), Vector(a), provenance);
+ }
+ else if (axis.Success && result.TryGetValue(axis.Groups["box"].Value, out boxValue) && boxValue is ConceptIrBox3Value axisBox)
+ {
+ var provenance = $"{instanceName}.{field.Name}";
+ result[field.Name] = new ConceptIrAxisValue(Id(provenance), axisBox.Center, Vector(axis.Groups["axis"].Value), provenance);
+ }
+ else diagnostics.Add(InvalidSpatialDerivation);
+ }
+
+ foreach (var grid in Regex.Matches(body, @"\b(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*Grid\s*\{", RegexOptions.CultureInvariant).Cast<Match>())
+ {
+ var open = body.IndexOf('{', grid.Index); var close = FindMatchingBrace(body, open);
+ if (close < 0) { diagnostics.Add(InvalidSpatialDerivation); continue; }
+ var gridBody = body[(open + 1)..close];
+ var within = Regex.Match(gridBody, @"\bWithin\s*:\s*(?<box>[A-Za-z_][A-Za-z0-9_]*)\.Face\((?<axis>[+-][XYZ])\)\.Inset\((?<inset>[^)]+)\)", RegexOptions.CultureInvariant);
+ var columns = IntField(gridBody, "Columns"); var rows = IntField(gridBody, "Rows");
+ if (!within.Success || columns < 1 || rows < 1 || !result.TryGetValue(within.Groups["box"].Value, out var value) || value is not ConceptIrBox3Value box) { diagnostics.Add(InvalidSpatialDerivation); continue; }
+ var inset = ParseLength(within.Groups["inset"].Value); var region = Region(box, within.Groups["axis"].Value, inset, $"{instanceName}.{grid.Groups["name"].Value}.Within");
+ if (region is null) { diagnostics.Add(InvalidSpatialDerivation); continue; }
+ var points = new List<ConceptIrPoint3Value>();
+ for (var row = 0; row < rows; row++) for (var column = 0; column < columns; column++)
+ {
+ var u = columns == 1 ? (region.MinU + region.MaxU) / 2d : region.MinU + column * (region.MaxU - region.MinU) / (columns - 1);
+ var v = rows == 1 ? (region.MinV + region.MaxV) / 2d : region.MinV + row * (region.MaxV - region.MinV) / (rows - 1);
+ var point = new ConceptIrPoint3(region.Center.X + region.U.X * u + region.V.X * v, region.Center.Y + region.U.Y * u + region.V.Y * v, region.Center.Z + region.U.Z * u + region.V.Z * v);
+ var ordinal = points.Count; var provenance = $"{instanceName}.{grid.Groups["name"].Value}[{ordinal}]";
+ points.Add(new(Id(provenance), point, provenance, ordinal));
+ }
+ var memberName = grid.Groups["name"].Value; var setProvenance = $"{instanceName}.{memberName}";
+ result[memberName] = new ConceptIrPointSetValue(Id(setProvenance), points, setProvenance);
+ }
+ return result;
+ }
+
+ private static void ValidateIndexedReferences(string body, IReadOnlyList<ConceptIrStructInstance> instances, List<string> diagnostics)
+ {
+ var byName = instances.ToDictionary(i => i.Name, StringComparer.Ordinal);
+ foreach (Match reference in Regex.Matches(body, @"(?<instance>[A-Za-z_][A-Za-z0-9_]*)\.(?<member>[A-Za-z_][A-Za-z0-9_]*)\[(?<index>[0-9]+)\]", RegexOptions.CultureInvariant))
+ {
+ if (!byName.TryGetValue(reference.Groups["instance"].Value, out var instance)
+ || !instance.Members.TryGetValue(reference.Groups["member"].Value, out var value)
+ || value is not ConceptIrPointSetValue points)
+ {
+ diagnostics.Add(InvalidSpatialDerivation);
+ continue;
+ }
+ var index = int.Parse(reference.Groups["index"].Value, CultureInfo.InvariantCulture);
+ if (index >= points.Points.Count) diagnostics.Add($"{IndexOutOfRange}:{reference.Value}:count-{points.Points.Count}");
+ }
+ }
+
+ private static void DetectCircularDependencies(string body, List<string> diagnostics)
+ {
+ var fields = TopLevelFields(body).ToArray();
+ var names = fields.Select(f => f.Name).ToHashSet(StringComparer.Ordinal);
+ var dependencies = fields.ToDictionary(
+ f => f.Name,
+ f => Regex.Matches(f.Value, @"\b[A-Za-z_][A-Za-z0-9_]*\b", RegexOptions.CultureInvariant).Cast<Match>().Select(m => m.Value).Where(names.Contains).Distinct(StringComparer.Ordinal).ToArray(),
+ StringComparer.Ordinal);
+ var visited = new HashSet<string>(StringComparer.Ordinal);
+ var visiting = new HashSet<string>(StringComparer.Ordinal);
+ bool Visit(string name)
+ {
+ if (visiting.Contains(name)) return true;
+ if (!visited.Add(name)) return false;
+ visiting.Add(name);
+ foreach (var dependency in dependencies[name]) if (Visit(dependency)) return true;
+ visiting.Remove(name);
+ return false;
+ }
+ if (dependencies.Keys.Any(Visit)) diagnostics.Add(CircularDependency);
+ }
+
+ private static void ValidateConformance(string instance, IReadOnlyList<string> satisfies, IReadOnlyDictionary<string, ConceptIrValue> members, IReadOnlyList<ConceptIrDefinition> definitions, List<string> diagnostics)
+ {
+ foreach (var conceptName in satisfies)
+ {
+ var definition = definitions.SingleOrDefault(d => d.Name == conceptName);
+ if (definition is null) { diagnostics.Add(FirmamentV2Parser.ConceptUnknownConcept); continue; }
+ foreach (var required in definition.Members.Values)
+ {
+ if (!members.TryGetValue(required.Name, out var value)) { diagnostics.Add($"{MissingMember}:{instance}.{required.Name}"); continue; }
+ if (!Compatible(required.Type, value)) diagnostics.Add($"{TypeMismatch}:{instance}.{required.Name}:expected-{required.Type}:actual-{value.Kind}");
+ }
+ foreach (var member in members.Keys.Where(k => !definition.Members.ContainsKey(k))) diagnostics.Add($"{UnknownMember}:{instance}.{member}");
+ }
+ }
+
+ private static bool Compatible(ConceptIrType type, ConceptIrValue value) =>
+ type.IsCollection ? type.Name == "Point3" && value is ConceptIrPointSetValue : string.Equals(type.Name, value.Kind.ToString(), StringComparison.Ordinal);
+
+ private static bool TryMember<T>(IReadOnlyDictionary<string, ConceptIrStructInstance> instances, Match reference, out T? value, List<string> diagnostics) where T : ConceptIrValue
+ {
+ value = null;
+ if (!instances.TryGetValue(reference.Groups["instance"].Value, out var instance) || !instance.Members.TryGetValue(reference.Groups["member"].Value, out var raw)) { diagnostics.Add(InvalidSpatialDerivation); return false; }
+ if (raw is not T typed) { diagnostics.Add(TypeMismatch); return false; }
+ value = typed; return true;
+ }
+
+ private static IEnumerable<(string Name, string Value)> TopLevelFields(string body)
+ {
+ var depth = 0;
+ foreach (var raw in body.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries))
+ {
+ var line = raw.Trim();
+ if (depth == 0)
+ {
+ var match = Regex.Match(line, @"^(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<value>.+?)\s*$", RegexOptions.CultureInvariant);
+ if (match.Success) yield return (match.Groups["name"].Value, match.Groups["value"].Value);
+ }
+ depth += line.Count(c => c == '{') - line.Count(c => c == '}');
+ }
+ }
+
+ private static ConceptIrRegion2Value? Region(ConceptIrBox3Value box, string axis, double inset, string provenance)
+ {
+ if (!double.IsFinite(inset) || inset < 0) return null;
+ var center = FaceCenter(box, axis);
+ (ConceptIrVector3 U, ConceptIrVector3 V, double HalfU, double HalfV) frame = axis switch
+ {
+ "+Z" or "-Z" => (new(1, 0, 0), new(0, 1, 0), box.Size[0] / 2d, box.Size[1] / 2d),
+ "+X" or "-X" => (new(0, 1, 0), new(0, 0, 1), box.Size[1] / 2d, box.Size[2] / 2d),
+ "+Y" or "-Y" => (new(1, 0, 0), new(0, 0, 1), box.Size[0] / 2d, box.Size[2] / 2d),
+ _ => default
+ };
+ if (frame.U is null || inset > frame.HalfU || inset > frame.HalfV) return null;
+ return new(Id(provenance), center, frame.U, frame.V, -frame.HalfU + inset, frame.HalfU - inset, -frame.HalfV + inset, frame.HalfV - inset, axis, provenance);
+ }
+
+ private static ConceptIrPoint3 FaceCenter(ConceptIrBox3Value box, string axis) => axis switch
+ {
+ "+X" => box.Center with { X = box.Max.X }, "-X" => box.Center with { X = box.Min.X },
+ "+Y" => box.Center with { Y = box.Max.Y }, "-Y" => box.Center with { Y = box.Min.Y },
+ "+Z" => box.Center with { Z = box.Max.Z }, "-Z" => box.Center with { Z = box.Min.Z },
+ _ => box.Center
+ };
+ private static ConceptIrVector3 Vector(string axis) => axis switch { "+X" => new(1, 0, 0), "-X" => new(-1, 0, 0), "+Y" => new(0, 1, 0), "-Y" => new(0, -1, 0), "+Z" => new(0, 0, 1), "-Z" => new(0, 0, -1), _ => new(0, 0, 0) };
+ private static string AxisOf(ConceptIrVector3 v) => (v.X, v.Y, v.Z) switch { (1, 0, 0) => "+X", (-1, 0, 0) => "-X", (0, 1, 0) => "+Y", (0, -1, 0) => "-Y", (0, 0, 1) => "+Z", (0, 0, -1) => "-Z", _ => string.Empty };
+ private static string FieldValue(string body, string name) { var m = Regex.Match(body, $@"\b{Regex.Escape(name)}\s*:\s*(?<value>[^\r\n}}]+)", RegexOptions.CultureInvariant); return m.Success ? m.Groups["value"].Value.Trim() : string.Empty; }
+ private static int IntField(string body, string name) => int.TryParse(FieldValue(body, name), NumberStyles.None, CultureInfo.InvariantCulture, out var value) ? value : -1;
+ private static double ParseLength(string source) { source = source.Trim(); return source.EndsWith("mm", StringComparison.Ordinal) && double.TryParse(source[..^2], NumberStyles.Float, CultureInfo.InvariantCulture, out var value) ? value : double.NaN; }
+ private static double ParseLengthOrUnitless(string source)
+ {
+ source = source.Trim();
+ if (source.EndsWith("mm", StringComparison.Ordinal)) source = source[..^2];
+ return double.TryParse(source, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) ? value : double.NaN;
+ }
+ private static string Id(string provenance) => "concept:" + provenance;
+ private static bool IsPrecededByConcept(string source, int index) { var start = Math.Max(0, index - 10); return Regex.IsMatch(source[start..index], @"Concept\s+$", RegexOptions.CultureInvariant); }
+ private static int FindMatchingBrace(string source, int open) { if (open < 0 || open >= source.Length || source[open] != '{') return -1; var depth = 0; for (var i = open; i < source.Length; i++) { if (source[i] == '{') depth++; else if (source[i] == '}' && --depth == 0) return i; } return -1; }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
index 82a2516e..730f8c55 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Ast.cs
@@ -1,6 +1,6 @@
namespace Aetheris.Kernel.Firmament.FirmamentV2;
-public sealed record FirmamentV2Document(string ModelName, string Units, IReadOnlyList<FirmamentV2SolidBinding> Solids, IReadOnlyList<FirmamentV2ModifyBlock>? ModifyBlocks = null, IReadOnlyList<FirmamentV2TemplateDecl>? Templates = null, IReadOnlyList<FirmamentV2PmiDecl>? Pmi = null, IReadOnlyList<FirmamentV2RecognizedRegion>? RecognizedRegions = null, IReadOnlyList<FirmamentV2ReplacementDecl>? Replacements = null, IReadOnlyList<FirmamentV2LetDeclaration>? Lets = null, IReadOnlyList<FirmamentV2BoundLet>? BoundLets = null, IReadOnlyList<FirmamentV2LetRecordDeclaration>? LetRecords = null, IReadOnlyList<FirmamentV2BoundLetRecord>? BoundLetRecords = null, IReadOnlyList<FirmamentV2ManufacturingConceptDeclaration>? ManufacturingConcepts = null, IReadOnlyList<FirmamentV2FeatureConceptDeclaration>? FeatureConcepts = null, FirmamentV2PmiBlock? PmiBlock = null, FirmamentV2BoundPmiBlock? BoundPmi = null)
+public sealed record FirmamentV2Document(string ModelName, string Units, IReadOnlyList<FirmamentV2SolidBinding> Solids, IReadOnlyList<FirmamentV2ModifyBlock>? ModifyBlocks = null, IReadOnlyList<FirmamentV2TemplateDecl>? Templates = null, IReadOnlyList<FirmamentV2PmiDecl>? Pmi = null, IReadOnlyList<FirmamentV2RecognizedRegion>? RecognizedRegions = null, IReadOnlyList<FirmamentV2ReplacementDecl>? Replacements = null, IReadOnlyList<FirmamentV2LetDeclaration>? Lets = null, IReadOnlyList<FirmamentV2BoundLet>? BoundLets = null, IReadOnlyList<FirmamentV2LetRecordDeclaration>? LetRecords = null, IReadOnlyList<FirmamentV2BoundLetRecord>? BoundLetRecords = null, IReadOnlyList<FirmamentV2ManufacturingConceptDeclaration>? ManufacturingConcepts = null, IReadOnlyList<FirmamentV2FeatureConceptDeclaration>? FeatureConcepts = null, FirmamentV2PmiBlock? PmiBlock = null, FirmamentV2BoundPmiBlock? BoundPmi = null, ConceptIrDocument? ConceptIr = null)
{
public FirmamentV2SolidBinding Solid => Solids[^1];
public FirmamentV2SideHoleIntent? SideHoleIntent => ModifyBlocks?.SelectMany(m => m.Regions.Select(r =>
@@ -40,7 +40,7 @@ public sealed record FirmamentV2BoundConceptField(string Name, FirmamentV2Concep
public sealed record FirmamentV2ManufacturingConceptDeclaration(FirmamentV2ConceptApplication Application, IReadOnlyList<FirmamentV2ConceptField> Fields, FirmamentV2SourceSpan SourceSpan, IReadOnlyList<FirmamentV2BoundConceptField>? BoundFields = null);
public sealed record FirmamentV2FeatureConceptDeclaration(string Name, FirmamentV2ConceptApplication Application, IReadOnlyList<FirmamentV2ConceptField> Fields, FirmamentV2SourceSpan SourceSpan, IReadOnlyList<FirmamentV2BoundConceptField>? BoundFields = null);
-public sealed record FirmamentV2SolidBinding(string Name, string RecordType, FirmamentV2PrimitiveRecord Primitive, string? DerivedFrom = null, IReadOnlyDictionary<string, IReadOnlyList<double>>? Overrides = null)
+public sealed record FirmamentV2SolidBinding(string Name, string RecordType, FirmamentV2PrimitiveRecord Primitive, string? DerivedFrom = null, IReadOnlyDictionary<string, IReadOnlyList<double>>? Overrides = null, IReadOnlyDictionary<string, string>? Provenance = null)
{
public bool IsDerived => !string.IsNullOrWhiteSpace(DerivedFrom);
public FirmamentV2BoxRecord? Box => Primitive as FirmamentV2BoxRecord;
@@ -104,7 +104,8 @@ public sealed record FirmamentV2EdgeFinishDecl(
string Target,
string Kind,
double Distance,
- FirmamentV2SourceSpan SourceSpan);
+ FirmamentV2SourceSpan SourceSpan,
+ IReadOnlyDictionary<string, string>? Provenance = null);
public sealed record FirmamentV2RegionDecl(string Name, string Kind, FirmamentV2FaceTarget Attachment, FirmamentV2CutOperation Cut);
public sealed record FirmamentV2CutOperation(string OperationKind, FirmamentV2CylinderTool Tool);
public sealed record FirmamentV2CylinderTool(string ToolType, double Radius, FirmamentV2FaceLocalPoint2D? Center, FirmamentV2FaceTarget Through);
@@ -134,6 +135,16 @@ public sealed record FirmamentV2SideHoleIntent(string TargetSolid, string Region
public enum FirmamentV2SemanticHoleVariant { Shaft, Counterbore, Countersink }
public enum FirmamentV2SemanticHoleEndKind { ThroughAll, Depth }
public sealed record FirmamentV2SemanticHoleEnd(FirmamentV2SemanticHoleEndKind Kind, double? Depth = null);
+public sealed record FirmamentV2ResolvedPoint3(
+ double X,
+ double Y,
+ double Z,
+ string StableId,
+ string SourceMember,
+ int? Ordinal,
+ string PlacementFace,
+ double PlaneDistance,
+ FirmamentV2SourceSpan SourceSpan);
public sealed record FirmamentV2SemanticHoleDecl(
string Name,
FirmamentV2SemanticHoleVariant Variant,
@@ -144,7 +155,9 @@ public sealed record FirmamentV2SemanticHoleDecl(
double? CounterboreDiameter = null,
double? CounterboreDepth = null,
double? CountersinkDiameter = null,
- double? CountersinkAngleDegrees = null);
+ double? CountersinkAngleDegrees = null,
+ FirmamentV2ResolvedPoint3? ResolvedCenter = null,
+ FirmamentV2SourceSpan? SourceSpan = null);
public enum FirmamentV2PmiKind { HoleDiameter, DatumPlane, Distance, Flatness, Parallel, Perpendicular, Coplanar }
public sealed record FirmamentV2PmiDecl(string Name, FirmamentV2PmiKind Kind, string Target, double? Value = null);
public sealed record FirmamentV2PmiBlock(IReadOnlyList<FirmamentV2PmiRecord> Records, FirmamentV2SourceSpan SourceSpan);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index 1e19df83..5c8fff4e 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -226,6 +226,10 @@ public static class FirmamentV2Parser
var source = StripLineComments(sourceText);
conceptCatalog ??= FirmamentV2ForgeConceptRegistry.Catalog;
+ if (Regex.IsMatch(source, @"\bConcept\s+(?:Struct\s+)?[A-Za-z_]", RegexOptions.CultureInvariant)
+ || Regex.IsMatch(source, @"\b(?:Struct|Model)\s+[A-Za-z_][A-Za-z0-9_]*\s*(?::\s*[A-Za-z_][A-Za-z0-9_]*)?\s*\{", RegexOptions.CultureInvariant))
+ return ParseConceptModelingDocument(source, diagnostics);
+
if (Regex.IsMatch(source, @"^\s*Model\b", RegexOptions.CultureInvariant))
return ParsePhase3ModelingDocument(source, diagnostics);
@@ -754,6 +758,36 @@ public static class FirmamentV2Parser
return FirmamentV2ParseResult.Success(document, diagnostics);
}
+ private static FirmamentV2ParseResult ParseConceptModelingDocument(string source, List<string> diagnostics)
+ {
+ var resolution = ConceptIrResolver.Resolve(source, diagnostics);
+ if (resolution is null || diagnostics.Any(IsConceptFatalDiagnostic))
+ {
+ diagnostics.Add("firmament-v2-parse-failed");
+ diagnostics.Sort(StringComparer.Ordinal);
+ return FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).ToArray());
+ }
+
+ var solid = new FirmamentV2SolidBinding(
+ resolution.BoxName,
+ "Box",
+ new FirmamentV2BoxRecord(resolution.BoxSize, []),
+ Provenance: new Dictionary<string, string>(StringComparer.Ordinal) { ["Bounds"] = resolution.BoxBoundsProvenance });
+ var document = new FirmamentV2Document(
+ resolution.ModelName,
+ resolution.Units,
+ [solid],
+ [resolution.ModifyBlock],
+ ConceptIr: resolution.ConceptIr);
+ diagnostics.Add("firmament-concept-ir-resolved");
+ diagnostics.Add("firmament-concept-struct-erased-before-feature-air");
+ if (resolution.ModifyBlock.EdgeFinishes?.Count > 0) diagnostics.Add("firmament-v2-phase3-edge-finish-parsed");
+ if (resolution.ModifyBlock.SemanticHoles.Count > 0) diagnostics.Add("firmament-concept-point3-semantic-holes-parsed");
+ diagnostics.Add("firmament-v2-parse-succeeded");
+ diagnostics.Sort(StringComparer.Ordinal);
+ return FirmamentV2ParseResult.Success(document, diagnostics.Distinct(StringComparer.Ordinal).ToArray());
+ }
+
private static double ParsePhase3Length(string source)
{
source = source.Trim();
@@ -761,7 +795,24 @@ public static class FirmamentV2Parser
return double.TryParse(source[..^2], NumberStyles.Float, CultureInfo.InvariantCulture, out var value) ? value : double.NaN;
}
- public static bool IsFatalDiagnosticCode(string code) => code is Phase3EdgeFinishSyntaxInvalid or PrimitiveFieldMissing or PrimitiveFieldUnknown or PrimitiveFieldInvalid or MissingModel or MissingUnits or MissingSolid or UnsupportedConstruct or UnknownRecordType or BoxMissingSize or BoxSizeArity or DegenerateDimension or NameUnresolved or DuplicateName or WithRequiresRecord or WithRequiresBoxRecord or WithFieldNotFound or WithFieldTypeMismatch or WithForwardReference or WithDerivedRecordInvalid or ExposeBlockUnsupported or ExposeRequiresBoxRecord or ExposeAliasDuplicate or ExposeAliasInvalid or SelectorUnsupported or SelectorAxisInvalid or SelectorSubselectorUnsupported or FatArrowOutsideExpose or RawBackendIdReferenceForbidden or ModifyTargetUnresolved or ModifyTargetNotSolid or RegionUnsupported or RegionAttachmentSelectorUnsupported or CutUnsupported or CutToolUnsupported or CylinderRadiusMissing or CylinderRadiusInvalid or CylinderRadiusNotFinite or ThroughSelectorUnsupported or AliasUnresolved or AliasRefTypeUnsupported or SideHoleAliasMustResolveToFace or SideHoleAliasResolvesToUnsupportedFace or SideHoleOnlyPlusXMinusXSupported or SideHoleRouteUnsupported or SideHoleSameFaceUnsupported or SideHoleAxisNotYetSupported or SideHoleRadiusExceedsClearance or CylinderCenterInvalid or CylinderCenterArityInvalid or CylinderCenterNotFinite or SideHoleCenterExceedsClearance or HoleVariantUnknown or HoleEntryFaceMissing or HoleCenterMissing or HoleShaftMissing or HoleEndMissing or HoleDiameterInvalid or HoleDepthInvalid or HoleCounterboreInvalid or HoleCountersinkInvalid or PmiKindUnknown or PmiTargetMissing or PmiTargetUnresolved or PmiDiameterInvalid or PmiDuplicateName or InlineStepUnknownBody or InlineStepUnknownFace or PmiImportedTargetNotFace or PmiImportedTargetRequiresCanonicalStep or PmiInvalidImportedTarget or InlineStepPathMissing or InlineStepPathInvalid or InlineStepFileMissing or InlineStepRequiresCanonical or UnknownRecognitionBody or UnknownRecognitionFace or DuplicateRegion or UnknownRecognitionRegion or InvalidRecognitionKind or InvalidRecognitionConfidence or PmiRecognizedRegionKindMismatch or UnknownReplacementBody or UnknownReplacementRegion or ReplacementKindMismatch or ReplacementFaceUnresolved or ReplacementUnsupportedKind or ReplacementVerificationFailed or ReplacementRadiusInvalid or ReplacementEndUnsupported or LetDuplicateName or LetUnknownType or LetTypeMismatch or LetInvalidLiteral or LetUnitMismatch or LetLiteralOnly or LetRecordDuplicateName or LetRecordDuplicateField or LetReferenceUnknownRecord or LetReferenceUnknownField or LetReferenceNonRecord or LetReferenceRecordUsedAsValue or ExpressionUnknownSymbol or ExpressionUnknownRecord or ExpressionUnknownField or ExpressionRecordUsedAsValue or ExpressionScalarUsedAsRecord or ExpressionTypeMismatch or ExpressionInvalidOperator or ExpressionDivisionByZero or ExpressionCycle or ExpressionUnsupported or ToleranceInvalidType or ToleranceUnitMismatch or ToleranceInvalidLiteral or ToleranceNegativeBilateral or ToleranceMissingMinus or ToleranceMissingPlus or ToleranceUnsupported or RecognitionEvidenceRadiusInvalid or RecognitionEvidenceSurfaceFamilyUnknown or RecognitionEvidenceAxisInvalid or SemanticProposalKindMismatch or SemanticProposalRadiusInvalid or SemanticProposalTargetUnresolved or SemanticProposalEndUnsupported or ConceptUnknownFamily or ConceptUnknownConcept or ConceptMissingRequiredField or ConceptUnknownField or ConceptDuplicateField or ConceptFieldTypeMismatch or ConceptInvalidTarget or ConceptDescriptorUnavailable or PmiDuplicateBlock or PmiDuplicateRecord or PmiDuplicateDatum or PmiUnknownRecordKind or PmiMissingRequiredField or PmiUnknownField or PmiDuplicateField or PmiInvalidTarget or PmiUnknownDatum or PmiDimensionTypeMismatch or PmiDimensionMissingTolerance or PmiToleranceTypeMismatch;
+ private static bool IsConceptFatalDiagnostic(string code) =>
+ code.StartsWith(ConceptIrResolver.MissingMember, StringComparison.Ordinal)
+ || code.StartsWith(ConceptIrResolver.UnknownMember, StringComparison.Ordinal)
+ || code.StartsWith(ConceptIrResolver.TypeMismatch, StringComparison.Ordinal)
+ || code.StartsWith(ConceptIrResolver.InvalidSpatialDerivation, StringComparison.Ordinal)
+ || code.StartsWith(ConceptIrResolver.IndexOutOfRange, StringComparison.Ordinal)
+ || code.StartsWith(ConceptIrResolver.CircularDependency, StringComparison.Ordinal)
+ || code.StartsWith(ConceptIrResolver.MaterializedPhaseReference, StringComparison.Ordinal)
+ || code.StartsWith(ConceptIrResolver.DuplicateDeclaration, StringComparison.Ordinal)
+ || code.StartsWith(ConceptIrResolver.DuplicateExposedMember, StringComparison.Ordinal)
+ || code.StartsWith(ConceptIrResolver.InvalidMaterializedReference, StringComparison.Ordinal)
+ || code.StartsWith(ConceptIrResolver.ExposedMemberUnrepresentable, StringComparison.Ordinal)
+ || code.StartsWith(ConceptIrResolver.CircularExposureDependency, StringComparison.Ordinal)
+ || code.StartsWith(ConceptIrResolver.PointNotOnPlacementPlane, StringComparison.Ordinal)
+ || code.StartsWith(ConceptIrResolver.PointOutsidePlacementFace, StringComparison.Ordinal)
+ || code.StartsWith(ConceptIrResolver.PointProjectionUnsupported, StringComparison.Ordinal);
+
+ public static bool IsFatalDiagnosticCode(string code) => IsConceptFatalDiagnostic(code) || code is Phase3EdgeFinishSyntaxInvalid or PrimitiveFieldMissing or PrimitiveFieldUnknown or PrimitiveFieldInvalid or MissingModel or MissingUnits or MissingSolid or UnsupportedConstruct or UnknownRecordType or BoxMissingSize or BoxSizeArity or DegenerateDimension or NameUnresolved or DuplicateName or WithRequiresRecord or WithRequiresBoxRecord or WithFieldNotFound or WithFieldTypeMismatch or WithForwardReference or WithDerivedRecordInvalid or ExposeBlockUnsupported or ExposeRequiresBoxRecord or ExposeAliasDuplicate or ExposeAliasInvalid or SelectorUnsupported or SelectorAxisInvalid or SelectorSubselectorUnsupported or FatArrowOutsideExpose or RawBackendIdReferenceForbidden or ModifyTargetUnresolved or ModifyTargetNotSolid or RegionUnsupported or RegionAttachmentSelectorUnsupported or CutUnsupported or CutToolUnsupported or CylinderRadiusMissing or CylinderRadiusInvalid or CylinderRadiusNotFinite or ThroughSelectorUnsupported or AliasUnresolved or AliasRefTypeUnsupported or SideHoleAliasMustResolveToFace or SideHoleAliasResolvesToUnsupportedFace or SideHoleOnlyPlusXMinusXSupported or SideHoleRouteUnsupported or SideHoleSameFaceUnsupported or SideHoleAxisNotYetSupported or SideHoleRadiusExceedsClearance or CylinderCenterInvalid or CylinderCenterArityInvalid or CylinderCenterNotFinite or SideHoleCenterExceedsClearance or HoleVariantUnknown or HoleEntryFaceMissing or HoleCenterMissing or HoleShaftMissing or HoleEndMissing or HoleDiameterInvalid or HoleDepthInvalid or HoleCounterboreInvalid or HoleCountersinkInvalid or PmiKindUnknown or PmiTargetMissing or PmiTargetUnresolved or PmiDiameterInvalid or PmiDuplicateName or InlineStepUnknownBody or InlineStepUnknownFace or PmiImportedTargetNotFace or PmiImportedTargetRequiresCanonicalStep or PmiInvalidImportedTarget or InlineStepPathMissing or InlineStepPathInvalid or InlineStepFileMissing or InlineStepRequiresCanonical or UnknownRecognitionBody or UnknownRecognitionFace or DuplicateRegion or UnknownRecognitionRegion or InvalidRecognitionKind or InvalidRecognitionConfidence or PmiRecognizedRegionKindMismatch or UnknownReplacementBody or UnknownReplacementRegion or ReplacementKindMismatch or ReplacementFaceUnresolved or ReplacementUnsupportedKind or ReplacementVerificationFailed or ReplacementRadiusInvalid or ReplacementEndUnsupported or LetDuplicateName or LetUnknownType or LetTypeMismatch or LetInvalidLiteral or LetUnitMismatch or LetLiteralOnly or LetRecordDuplicateName or LetRecordDuplicateField or LetReferenceUnknownRecord or LetReferenceUnknownField or LetReferenceNonRecord or LetReferenceRecordUsedAsValue or ExpressionUnknownSymbol or ExpressionUnknownRecord or ExpressionUnknownField or ExpressionRecordUsedAsValue or ExpressionScalarUsedAsRecord or ExpressionTypeMismatch or ExpressionInvalidOperator or ExpressionDivisionByZero or ExpressionCycle or ExpressionUnsupported or ToleranceInvalidType or ToleranceUnitMismatch or ToleranceInvalidLiteral or ToleranceNegativeBilateral or ToleranceMissingMinus or ToleranceMissingPlus or ToleranceUnsupported or RecognitionEvidenceRadiusInvalid or RecognitionEvidenceSurfaceFamilyUnknown or RecognitionEvidenceAxisInvalid or SemanticProposalKindMismatch or SemanticProposalRadiusInvalid or SemanticProposalTargetUnresolved or SemanticProposalEndUnsupported or ConceptUnknownFamily or ConceptUnknownConcept or ConceptMissingRequiredField or ConceptUnknownField or ConceptDuplicateField or ConceptFieldTypeMismatch or ConceptInvalidTarget or ConceptDescriptorUnavailable or PmiDuplicateBlock or PmiDuplicateRecord or PmiDuplicateDatum or PmiUnknownRecordKind or PmiMissingRequiredField or PmiUnknownField or PmiDuplicateField or PmiInvalidTarget or PmiUnknownDatum or PmiDimensionTypeMismatch or PmiDimensionMissingTolerance or PmiToleranceTypeMismatch;
private static IReadOnlyList<FirmamentV2Exposure> ParseExposures(string body, List<string> diagnostics)
{
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2SemanticHoleLowering.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2SemanticHoleLowering.cs
index 0b8153c6..30fd17f5 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2SemanticHoleLowering.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2SemanticHoleLowering.cs
@@ -7,11 +7,23 @@ internal static class FirmamentV2SemanticHoleLowering
{
public static AirHoleFeature Lower(FirmamentV2Document document, FirmamentV2ModifyBlock modify, FirmamentV2SemanticHoleDecl hole)
{
- var placement = new AirFaceLocalHolePlacement(hole.EntryFace.Axis switch { "+Z" => "top", "-Z" => "bottom", _ => hole.EntryFace.Source }, hole.Center.U, hole.Center.V, FirmamentV2FaceLocalPoint2D.ConventionFor(hole.EntryFace.Axis), hole.EntryFace.ResolvedSelector);
+ var pointSource = hole.ResolvedCenter is null ? null : new AirResolvedPoint3PlacementSource(
+ hole.ResolvedCenter.X, hole.ResolvedCenter.Y, hole.ResolvedCenter.Z, hole.ResolvedCenter.StableId,
+ hole.ResolvedCenter.SourceMember, hole.ResolvedCenter.Ordinal, hole.ResolvedCenter.PlacementFace,
+ hole.ResolvedCenter.PlaneDistance, $"{hole.ResolvedCenter.SourceSpan.Start}:{hole.ResolvedCenter.SourceSpan.Length}");
+ var placement = new AirFaceLocalHolePlacement(hole.EntryFace.Axis switch { "+Z" => "top", "-Z" => "bottom", _ => hole.EntryFace.Source }, hole.Center.U, hole.Center.V, FirmamentV2FaceLocalPoint2D.ConventionFor(hole.EntryFace.Axis), hole.EntryFace.ResolvedSelector, pointSource);
var axis = new AirHoleAxis(Direction3D.Create(hole.EntryFace.Axis switch { "-Z" => new Vector3D(0,0,-1), "+Z" => new Vector3D(0,0,1), "+X" => new Vector3D(1,0,0), "-X" => new Vector3D(-1,0,0), "+Y" => new Vector3D(0,1,0), _ => new Vector3D(0,-1,0) }), true);
var shaft = new AirHoleShaft(hole.ShaftDiameter);
AirHoleEndCondition endCondition = hole.EndCondition.Kind == FirmamentV2SemanticHoleEndKind.ThroughAll ? new AirHoleEndCondition.ThroughAll() : new AirHoleEndCondition.Depth(hole.EndCondition.Depth!.Value);
- var provenance = new AirProvenance("HOLE-X4", "Firmament V2 semantic hole source hook", hole.Name, $"{modify.TargetSolid}.{hole.Name}", nameof(AirHoleFeature), AirSelectionClass.None, AirRuleKind.None, $"FirmamentV2 hole<{hole.Variant}>", true, [$"source-variant:{hole.Variant}", $"target-solid:{modify.TargetSolid}", $"entry-face:{hole.EntryFace.Source}"]);
+ var notes = new List<string> { $"source-variant:{hole.Variant}", $"target-solid:{modify.TargetSolid}", $"entry-face:{hole.EntryFace.Source}" };
+ if (hole.ResolvedCenter is { } center)
+ {
+ notes.Add($"center-source:{center.SourceMember}[{center.Ordinal}]");
+ notes.Add($"center-stable-id:{center.StableId}");
+ notes.Add($"center-point3:[{center.X:R},{center.Y:R},{center.Z:R}]");
+ notes.Add($"center-plane-distance:{center.PlaneDistance:R}");
+ }
+ var provenance = new AirProvenance("CONCEPT-MATERIALIZATION-M2", "Typed Concept Point3 semantic hole source", hole.Name, $"{modify.TargetSolid}.{hole.Name}", nameof(AirHoleFeature), AirSelectionClass.None, AirRuleKind.None, $"FirmamentV2 hole<{hole.Variant}>", true, notes);
return hole.Variant switch
{
FirmamentV2SemanticHoleVariant.Counterbore => AirHoleFeature.CreateCounterbore(hole.Name, $"{modify.TargetSolid}.{hole.Name}", modify.TargetSolid, placement, axis, shaft, endCondition, new AirHoleCounterboreComponent(hole.CounterboreDiameter!.Value, hole.CounterboreDepth!.Value), provenance),
diff --git a/demos/concept-expansion-m1.firmament b/demos/concept-expansion-m1.firmament
new file mode 100644
index 00000000..66fc1575
--- /dev/null
+++ b/demos/concept-expansion-m1.firmament
@@ -0,0 +1,39 @@
+Concept MountingFrame {
+ Bounds: Box3
+ TopPlane: Plane
+ CenterAxis: Axis
+ MountPoints: Point3[]
+}
+
+Concept Struct BracketConcept: MountingFrame {
+ Bounds: Box3 {
+ Size: [80mm, 50mm, 25mm]
+ }
+ TopPlane: Bounds.Face(+Z)
+ CenterAxis: Bounds.Center.Axis(+Z)
+ MountPoints: Grid {
+ Within: Bounds.Face(+Z).Inset(10mm)
+ Columns: 2
+ Rows: 1
+ }
+}
+
+Struct Bracket: MountingFrame {
+ Box Base {
+ Bounds: BracketConcept.Bounds
+ }
+ Modify Base {
+ EdgeFinish TopBreak {
+ Face: BracketConcept.TopPlane
+ Target: Boundary
+ Kind: Chamfer
+ Distance: 1.5mm
+ }
+ }
+ Expose {
+ Bounds: BracketConcept.Bounds
+ TopPlane: Base.Top
+ CenterAxis: BracketConcept.CenterAxis
+ MountPoints: BracketConcept.MountPoints
+ }
+}
diff --git a/demos/concept-materialization-m2.firmament b/demos/concept-materialization-m2.firmament
new file mode 100644
index 00000000..129e65da
--- /dev/null
+++ b/demos/concept-materialization-m2.firmament
@@ -0,0 +1,45 @@
+Concept MountingFrame {
+ Bounds: Box3
+ TopPlane: Plane
+ CenterAxis: Axis
+ MountPoints: Point3[]
+}
+
+Concept Struct BracketConcept: MountingFrame {
+ Bounds: Box3 {
+ Size: [80mm, 50mm, 25mm]
+ }
+ TopPlane: Bounds.Face(+Z)
+ CenterAxis: Bounds.Center.Axis(+Z)
+ MountPoints: Grid {
+ Within: Bounds.Face(+Z).Inset(10mm)
+ Columns: 2
+ Rows: 1
+ }
+}
+
+Struct Bracket: MountingFrame {
+ Box Base {
+ Bounds: BracketConcept.Bounds
+ }
+ Modify Base {
+ hole<shaft> LeftMount {
+ on: Base.Top
+ center: BracketConcept.MountPoints[0]
+ diameter: 8.5mm
+ end: throughAll
+ }
+ hole<shaft> RightMount {
+ on: Base.Top
+ center: BracketConcept.MountPoints[1]
+ diameter: 8.5mm
+ end: throughAll
+ }
+ }
+ Expose {
+ Bounds: BracketConcept.Bounds
+ TopPlane: Base.Top
+ CenterAxis: BracketConcept.CenterAxis
+ MountPoints: BracketConcept.MountPoints
+ }
+}
diff --git a/docs/concept-expansion-m1.md b/docs/concept-expansion-m1.md
new file mode 100644
index 00000000..27fc002e
--- /dev/null
+++ b/docs/concept-expansion-m1.md
@@ -0,0 +1,122 @@
+# CONCEPT-EXPANSION-M1: conceptual front end
+
+The conceptual front end lets Firmament authors structure a design before constructing geometry. Its bounded M1 pipeline is:
+
+```text
+Firmament V2 source
+ -> authoritative Concept IR (compile-time only)
+ -> Feature AIR
+ -> Construction AIR
+ -> authoritative BRepPlan
+ -> BRep
+ -> STEP AP242
+```
+
+## Language constructs
+
+`Concept` declares a structural contract. It has named members and spatial types, but no values and no geometry:
+
+```firmament
+Concept MountingFrame {
+ Bounds: Box3
+ TopPlane: Plane
+ CenterAxis: Axis
+ MountPoints: Point3[]
+}
+```
+
+`Concept Struct` creates a statically resolved semantic/spatial value. It is compile-time-only and cannot emit a body, face, edge, vertex, coedge, or STEP entity:
+
+```firmament
+Concept Struct BracketConcept: MountingFrame {
+ Bounds: Box3 { Size: [80mm, 50mm, 25mm] }
+ TopPlane: Bounds.Face(+Z)
+ CenterAxis: Bounds.Center.Axis(+Z)
+ MountPoints: Grid {
+ Within: Bounds.Face(+Z).Inset(10mm)
+ Columns: 2
+ Rows: 1
+ }
+}
+```
+
+`Struct` and `Model` are source aliases for the same materialized declaration. The parser normalizes both to `FirmamentV2Document`; Concept IR retains `SourceSpelling` for diagnostics and formatting:
+
+```firmament
+Struct Bracket: MountingFrame {
+ Box Base { Bounds: BracketConcept.Bounds }
+ Modify Base {
+ EdgeFinish TopBreak {
+ Face: BracketConcept.TopPlane
+ Target: Boundary
+ Kind: Chamfer
+ Distance: 1.5mm
+ }
+ }
+}
+```
+
+The equivalent header `Model Bracket: MountingFrame { ... }` has identical compiler meaning. The older, already-supported `Model Name mm` chamfer syntax remains accepted and was not globally rewritten.
+
+## Authoritative Concept IR
+
+`ConceptIrDocument` is attached to the parser-owned Firmament V2 document. It contains:
+
+- `ConceptIrDefinition` structural requirements;
+- non-materialized `ConceptIrStructInstance` values and declared concept membership;
+- typed resolved values with deterministic stable IDs;
+- the normalized materialized declaration and its original `Struct`/`Model` spelling;
+- explicit consumer/input/provenance bindings;
+- the erasure state `ErasedBeforeFeatureAir`.
+
+This is the compiler representation used to bind materialized inputs, not an after-the-fact report assembled from geometry. Build JSON serializes this same IR under `conceptIr`.
+
+Concept IR contains no BRep topology IDs and no raw dictionary-shaped spatial values. The M1 typed value set used by resolution is `Box3`, `Plane`, `Axis`, `Region2`, `Point3`, and ordered `PointSet`; type names reserve the adjacent `Length`, `Point2`, `Vector3`, `Box2`, and spatial collection vocabulary for compatible expansion. Lengths retain their dimensional meaning at parsing boundaries and are resolved in the document unit (`mm`); they are not accepted as unitless dimensions.
+
+## Spatial resolution and static expansion
+
+M1 implements these typed operations:
+
+- `Box3 { Size: [x, y, z] }` with a centered XY frame and Z extent from `0` to `z`;
+- `Bounds.Center` as the box center;
+- `Bounds.Face(+X|-X|+Y|-Y|+Z|-Z)` as a plane;
+- `Bounds.Center.Axis(direction)` as an axis;
+- rectangular face `.Inset(length)` as a bounded `Region2`;
+- `Grid` over such a region with positive integer `Columns` and `Rows`;
+- deterministic row-major point expansion and compile-time index validation.
+
+A one-column or one-row grid is centered on that dimension. Multi-element dimensions include both inset boundaries. Every generated point has a stable path identity such as `concept:BracketConcept.MountPoints[0]`, an ordinal, resolved coordinates, and source provenance. No loop or runtime pattern remains after resolution, and Firmament gains no mutable state or general control flow.
+
+## Structural conformance and diagnostics
+
+Concept Struct conformance is compiler-owned, deterministic, and structural. Required names must exist and their types must match; `PointSet` conforms to `Point3[]`. M1 uses strict member checking for a Concept Struct that explicitly declares `: ConceptName`.
+
+The front end reports stable diagnostics for missing and unknown members, type mismatches, invalid spatial derivations, out-of-range point indices, circular compile-time dependencies, and illegal references from the compile-time phase to the materialized declaration. It also rejects materialized `Hole` syntax on this new path rather than silently discarding it, because holes combined with the production chamfer route are outside the currently admitted modification network.
+
+A materialized `Struct: ConceptName` now uses the M2 `Expose` block shown in the checked-in demo. M1's spatial values and chamfer proof are unchanged; materialized structural conformance is documented in [`concept-materialization-m2.md`](concept-materialization-m2.md).
+
+## Erasure and provenance
+
+Erasure means “not materialized,” not “forgotten.” Concept Struct instances are absent from `FirmamentV2Document.Solids`, so the executor cannot create a body for them. Their values are copied into typed materialized bindings:
+
+```text
+BracketConcept.Bounds -> Bracket.Base.Bounds
+BracketConcept.TopPlane -> Bracket.TopBreak.Face selection
+```
+
+The existing AIR chamfer compiler then receives resolved dimensions and `+Z`, without any Concept-IR topology. Build JSON retains both provenance paths in `air.feature.provenance`, alongside the authoritative BRepPlan and STEP reimport report.
+
+## Relationship to Forge concepts
+
+The two uses of “concept” are deliberately distinct:
+
+- A language `Concept` is a compile-time structural type contract owned by the Firmament compiler.
+- A Forge C# concept is executable schema, validation, DFM, or PMI behavior supplied by a runtime concept pack.
+
+Basic member/type conformance does not execute C# and does not depend on a Forge validator. A future bridge may let Forge behavioral rules target language-conforming values, but it must preserve this ownership boundary.
+
+## Production proof and M1 limits
+
+The checked-in proof is [`demos/concept-expansion-m1.firmament`](../demos/concept-expansion-m1.firmament). It resolves bounds, a top plane, a center axis, and two mounting points; materializes one box from the bounds; selects the chamfer face from the resolved plane; follows `AirPrismaticTopFaceBoundaryChamfer`; exports AP242; and successfully reimports a closed manifold.
+
+M1 is intentionally not a parametric constraint solver or arbitrary compile-time programming system. It has no general functions, loops, mutable values, constraint propagation, cross-instance dependency graph, or materialized member-surface inference. M2 adds typed `Point3` hole consumption and explicit materialized exposure without changing those boundaries or widening the chamfer modification network.
diff --git a/docs/concept-materialization-m2.md b/docs/concept-materialization-m2.md
new file mode 100644
index 00000000..099a3961
--- /dev/null
+++ b/docs/concept-materialization-m2.md
@@ -0,0 +1,91 @@
+# CONCEPT-MATERIALIZATION-M2: typed points and materialized conformance
+
+M2 is the first bridge from resolved compile-time Concept IR points into materialized semantic Feature AIR. It also makes a materialized `Struct` or `Model` satisfy a language `Concept` through an explicit semantic surface rather than inferred BRep topology.
+
+## Source form
+
+M2 reuses the existing semantic-hole syntax. A Concept point replaces the previously literal face-local `center`:
+
+```firmament
+Modify Base {
+ hole<shaft> LeftMount {
+ on: Base.Top
+ center: BracketConcept.MountPoints[0]
+ diameter: 8.5mm
+ end: throughAll
+ }
+}
+```
+
+The bounded materialization lane accepts a history-known rectangular `Box`, a planar `+Z` entry face (`Base.Top`, `face(+Z)`, or a compatible Concept `Plane`), a positive shaft diameter, `throughAll`, and a resolved Concept IR `Point3`. M2 does not add a second hole compiler: it creates the same `FirmamentV2SemanticHoleDecl`, lowers to the existing `AirHoleFeature`, and uses `AirHoleSimpleShaftMaterializer` or `AirHoleCompositeMaterializer`.
+
+Materialized conformance is declared with:
+
+```firmament
+Struct Bracket: MountingFrame {
+ // materialized features
+ Expose {
+ Bounds: BracketConcept.Bounds
+ TopPlane: Base.Top
+ CenterAxis: BracketConcept.CenterAxis
+ MountPoints: BracketConcept.MountPoints
+ }
+}
+```
+
+`Expose` is a structural semantic-member declaration. It is not the older box-record `expose { face(+Z) => top }` alias syntax, and it does not enumerate or infer topology.
+
+## Typed Point3 conversion
+
+The Concept resolver keeps each grid point as `ConceptIrPoint3Value`, including its coordinates, stable ID, ordinal, source member, and provenance. For a hole center it resolves the indexed value and performs this explicit conversion:
+
+```text
+ConceptIrPoint3Value + selected planar face
+ -> plane-distance check (1e-9 model-unit tolerance)
+ -> bounded rectangular face check
+ -> +Z local frame (u = X, v = Y)
+ -> FirmamentV2ResolvedPoint3 + FirmamentV2FaceLocalPoint2D
+ -> AirResolvedPoint3PlacementSource + AirFaceLocalHolePlacement
+```
+
+The 3D value remains attached to AIR; only the materializer consumes `U` and `V`. No arbitrary projection is performed. An off-plane point reports `firmament-concept-point-not-on-placement-plane`; a point outside the bounded face reports `firmament-concept-point-outside-placement-face`; an unsupported face or projection rule reports `firmament-concept-point-projection-unsupported`. Invalid static indices and materialized values requested during Concept IR resolution retain their existing dedicated diagnostics.
+
+Grid expansion remains deterministic row-major. Stable IDs are path based (`concept:BracketConcept.MountPoints[0]`) and do not depend on unrelated declarations.
+
+## Semantic members and conformance
+
+`ConceptIrSemanticMember` is the typed shared representation for a materialized exposure. It retains the member name and `ConceptIrType`, typed value where available, semantic reference where applicable, compiler phase (`ConceptIr` or `FeatureAir`), materialization category, provenance, source span, and stable identity.
+
+M2 exposure sources are deliberately bounded:
+
+- a typed Concept IR member such as `BracketConcept.Bounds` or `BracketConcept.MountPoints`;
+- the history-known box top plane such as `Base.Top`;
+- a semantic hole center such as `LeftMount.Center` when its source is a resolved Concept point.
+
+Conformance checks the exposed surface only. It reports missing and unknown members, type mismatches, duplicate exposure names, invalid materialized references, unrepresentable semantic exposure, and circular exposure dependencies. `Concept Struct` remains compile-time-only and is checked against its directly resolved members; `Struct` and `Model` remain materialized and are checked against `Expose`. No Forge execution is required for either language-level check.
+
+## Provenance and reports
+
+Build JSON exposes the authoritative chain in two places:
+
+```text
+conceptIr.resolvedValues Point3
+ -> conceptIr.bindings Bracket.LeftMount.Center
+ -> features[].resolvedPoint3 / centerSource / centerStableId / pointOrdinal
+ -> AirHoleFeature placement provenance
+ -> AirHoleCompositeMaterializer
+```
+
+`conceptIr.materializedStruct` reports `satisfies`, `conformance`, and typed `exposedMembers`. Concept Struct instances remain marked `materialized: false` and `CompileTimeOnlyErased`; the build document contains only the materialized box solid.
+
+## Geometry proof
+
+[`demos/concept-materialization-m2.firmament`](../demos/concept-materialization-m2.firmament) resolves points `(-30,0,25)` and `(30,0,25)`, creates two 8.5 mm through holes, exports AP242, and reimports it. Concept-driven boxes preserve the Concept `Box3` frame (`Z=0..height`) rather than the legacy centered-Z semantic-hole frame. Independent `aetheris analyze` evidence is one body and one shell, `enclosed-manifold`, six planes, two cylinders, and materialized bounds `[-40,-25,0]..[40,25,25]`. Cylinder axes are `+Z`, top circular centers match the resolved Point3 coordinates, radii are `4.25`, and exact volume is `97162.74913472672 mm^3` (`80*50*25 - 2*pi*4.25^2*25`).
+
+The M1 AIR top-boundary chamfer demo remains separate. The current production chamfer route admits exactly one edge finish and no semantic holes; combining it with holes fails with `air-chamfer-production-route-requires-one-box-and-one-edge-finish` rather than dropping a feature.
+
+## Limits and next step
+
+M2 does not infer Concept members from BRep topology, expose BRep IDs, implement arbitrary projection, broaden hole orientations, or add a constraint solver. It does not unify the current independent modification materializers.
+
+The recommended next step is a typed evidence/matching layer that compares a `ConceptIrSemanticMember` or exposed materialized member against STEP-derived analytic evidence (plane, cylinder, bounds, point/axis and tolerance) while keeping STEP entity IDs out of the language Concept contract.
diff --git a/docs/firmament-overview.md b/docs/firmament-overview.md
index 7746cbc9..cea8a64d 100644
--- a/docs/firmament-overview.md
+++ b/docs/firmament-overview.md
@@ -1,5 +1,9 @@
# Firmament Overview
+The current language Concept implementation is documented by [CONCEPT-EXPANSION-M1](concept-expansion-m1.md) and [CONCEPT-MATERIALIZATION-M2](concept-materialization-m2.md). M2 adds typed Concept `Point3` consumption by semantic holes and explicit `Expose`-based structural conformance for materialized `Struct`/`Model` declarations; neither path performs automatic BRep semantic inference.
+
+The production PascalCase front end now includes compile-time `Concept` contracts, non-materialized `Concept Struct` spatial values, and interchangeable materialized `Struct` / `Model` aliases. See [CONCEPT-EXPANSION-M1](concept-expansion-m1.md) for syntax, Concept IR, static expansion, conformance, erasure, provenance, and the distinction from Forge C# concepts.
+
Firmament is the Aetheris DSL for defining a small, ordered 3D feature program in `.firmament` files.
In v1 today, the implemented golden path is: