Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Normalize semantic regions before FEA analysis
Yuechen Li764032544a31
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex bd5a9e6a..c60091bc 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -15,6 +15,7 @@ using Aetheris.Firmament.FrictionLab.CIRLab;using Aetheris.FEA.Abaqus;using Aetheris.FEA.Firmament;using Aetheris.FEA.Mechanics;+using Aetheris.Semantics;namespace Aetheris.CLI;@@ -656,6 +657,19 @@ public static class CliRunnervar features = document?.ModifyBlocks?.SelectMany(block =>block.SemanticHoles.Select(hole => $"Hole<{hole.Variant}> {hole.Name}").Concat((block.EdgeFinishes ?? []).Select(finish => $"{finish.Kind} {finish.Name}"))) ?? [];+ var semanticValues = FirmamentSemanticValues.FromProfilesAndConceptPaths(source, fullPath).ToList();+ if (PrismaticProfileCompositionParser.IsCompositionSource(source))+ {+ var composition = PrismaticProfileCompositionParser.Parse(source);+ semanticValues.AddRange(composition.Profiles.Values.OrderBy(profile => profile.Name, StringComparer.Ordinal).Select(profile =>+ FirmamentSemanticValues.FromProfile(profile, SemanticSourceSpan.Generated(fullPath),+ [new("firmament-profile", profile.Name, "named Profile normalized before consumer")])));+ }+ else if (ProfileAuthoringParser.IsProfileSource(source) && ProfileAuthoringParser.Parse(source).Profile is { } directProfile)+ semanticValues.Add(FirmamentSemanticValues.FromProfile(directProfile, SemanticSourceSpan.Generated(fullPath),+ [new("firmament-profile", directProfile.Name, "named Profile normalized before consumer")]));+ if (document?.ConceptIr is { } conceptIr) semanticValues.AddRange(FirmamentSemanticValues.FromConceptIr(conceptIr, fullPath));+ if (document?.RecognizedRegions?.Count > 0) semanticValues.AddRange(FirmamentSemanticValues.FromRecognizedRegions(document, fullPath, source));var report = new{command = "inspect",@@ -678,9 +692,16 @@ public static class CliRunnerinstance.Template,instance.Instance,instance.SpecializationIdentity,- records = instance.RecordArguments?.ToDictionary(pair => pair.Key, pair => new { pair.Value.RecordType, pair.Value.StaticValue, pair.Value.Provenance, members = pair.Value.Members })+ records = instance.RecordArguments?.OrderBy(pair => pair.Key, StringComparer.Ordinal).ToDictionary(pair => pair.Key, pair => new+ {+ pair.Value.RecordType,+ pair.Value.StaticValue,+ pair.Value.Provenance,+ members = pair.Value.Members.OrderBy(member => member.Key, StringComparer.Ordinal).ToDictionary(member => member.Key, member => member.Value, StringComparer.Ordinal)+ }, StringComparer.Ordinal)}).ToArray() ?? [],conceptPaths = ProfileAuthoringParser.InspectConceptPaths(source),+ semanticValues = semanticValues.OrderBy(value => value.StableIdentity, StringComparer.Ordinal).Select(SemanticValueDescriptor.From).ToArray(),recognizedRegions = document?.RecognizedRegions?.Select(region => new{region.BodyName,diff --git a/Aetheris.FEA.Tests/LinearElasticM5Tests.cs b/Aetheris.FEA.Tests/LinearElasticM5Tests.csindex 1ab1fc85..72ec2c92 100644--- a/Aetheris.FEA.Tests/LinearElasticM5Tests.cs+++ b/Aetheris.FEA.Tests/LinearElasticM5Tests.cs@@ -140,6 +140,44 @@ public sealed class LinearElasticM5TestsAssert.Equal("InlineStep",result.AnalysisIr!.Body.SourceKind);Assert.Equal(resource.ContentHash,result.AnalysisIr.Body.ResourceHash);Assert.NotNull(result.NativeResult!.BoundaryLoads!.Single().ExactBrepFaceId);Assert.True(result.Abaqus!.ElementCount>0);}+ [Fact]+ public void InlineStepRecognizeMemberPath_NormalizesToBoundarySemanticValueBeforeAnalysisIr()+ {+ var root=FindRoot();var fixtureDirectory=Path.Combine(root,"fixtures","FirmamentV2","Canonical","valid");+ const string source="""+ Model ImportedRecognizedAnalysis {+ Units: mm+ InlineStep imported {+ Path: "../../InlineStep/testdata/canonical-box-10x8x6.step"+ }+ Recognize imported {+ Region MountFace {+ Kind: DatumPlane+ Confidence: High+ Faces: [1]+ }+ }+ analysis LinearElastic Pull {+ body: imported+ material Steel { youngsModulus: 200GPa+ poissonRatio: 0.3 }+ fixed Clamp { region: imported.MountFace+ components: [X, Y, Z] }+ force Pull { region: imported.face(+X)+ vector: [100N, 0N, 0N] }+ lattice: [6, 5, 4]+ }+ }+ """;+ var compiled=FirmamentAnalysisCompiler.Compile(source,"recognized-analysis.firmament",fixtureDirectory);+ Assert.True(compiled.IsSuccess,string.Join("; ",compiled.Diagnostics.Select(item=>item.Code+":"+item.Message)));+ var region=Assert.Single(compiled.Analysis!.Constraints).Region;+ Assert.StartsWith("recognize:",region.SemanticStableId,StringComparison.Ordinal);+ Assert.Contains("BoundaryRegionCapable",region.CapabilityEvidence!);+ Assert.Equal("ExactBrepFace",region.ExactBindingKind);+ Assert.NotNull(region.ExactBrepFaceId);+ }+private static string FindRoot(){var d=new DirectoryInfo(AppContext.BaseDirectory);while(d is not null&&!File.Exists(Path.Combine(d.FullName,"Aetheris.slnx")))d=d.Parent;return d?.FullName??throw new DirectoryNotFoundException();}[Fact]diff --git a/Aetheris.FEA/Aetheris.FEA.csproj b/Aetheris.FEA/Aetheris.FEA.csprojindex f8956b44..e9ab0f7a 100644--- a/Aetheris.FEA/Aetheris.FEA.csproj+++ b/Aetheris.FEA/Aetheris.FEA.csproj@@ -7,6 +7,7 @@<ItemGroup><ProjectReference Include="..\Aetheris.Continuum\Aetheris.Continuum.csproj" /><ProjectReference Include="..\Aetheris.Kernel.Core\Aetheris.Kernel.Core.csproj" />+ <ProjectReference Include="..\Aetheris.Semantics\Aetheris.Semantics.csproj" /><ProjectReference Include="..\Aetheris.Kernel.Firmament\Aetheris.Kernel.Firmament.csproj" /></ItemGroup></Project>diff --git a/Aetheris.FEA/Analysis/AnalysisIr.cs b/Aetheris.FEA/Analysis/AnalysisIr.csindex 44bebacc..c446321d 100644--- a/Aetheris.FEA/Analysis/AnalysisIr.cs+++ b/Aetheris.FEA/Analysis/AnalysisIr.cs@@ -24,7 +24,10 @@ public sealed record SemanticRegionBinding(string Path,string? ExactBrepFaceId = null,IReadOnlyList<string>? RecognizedFaceIds = null,- AnalysisProvenance? Provenance = null);+ AnalysisProvenance? Provenance = null,+ string? SemanticStableId = null,+ IReadOnlyList<string>? CapabilityEvidence = null,+ string? ExactBindingKind = null);public sealed record LinearElasticMaterialIr(string Id,diff --git a/Aetheris.FEA/Analysis/AnalysisSemanticRegionNormalizer.cs b/Aetheris.FEA/Analysis/AnalysisSemanticRegionNormalizer.csnew file mode 100644index 00000000..50ceba83--- /dev/null+++ b/Aetheris.FEA/Analysis/AnalysisSemanticRegionNormalizer.cs@@ -0,0 +1,36 @@+using Aetheris.Semantics;++namespace Aetheris.FEA.Analysis;++/// <summary>Erases the producer after checking the common boundary capability.</summary>+public static class AnalysisSemanticRegionNormalizer+{+ public static (SemanticRegionBinding? Region, SemanticDiagnostic? Diagnostic) Normalize(SemanticReference reference)+ {+ var missing = SemanticValueValidator.Require<BoundaryRegionCapability>(reference);+ if (missing is not null) return (null, missing);+ if (reference.Value.TryBinding<ExactAnalysisRegionBinding>(out var analysis))+ return (new(analysis.BodyStableId, analysis.RegionPath, analysis.ExactBrepFaceId, Provenance: Provenance(reference),+ SemanticStableId: reference.Value.StableIdentity,+ CapabilityEvidence: reference.Value.Capabilities.Values.Select(capability => capability.Name).ToArray(),+ ExactBindingKind: analysis.Kind), null);+ if (reference.Value.TryBinding<ExactBrepFaceBinding>(out var face))+ return (new(face.Body.Topology.Bodies.Single().Id.Value.ToString(), reference.Value.ExposedName ?? reference.Value.StableIdentity,+ face.Face.Value.ToString(), Provenance: Provenance(reference), SemanticStableId: reference.Value.StableIdentity,+ CapabilityEvidence: reference.Value.Capabilities.Values.Select(capability => capability.Name).ToArray(), ExactBindingKind: face.Kind), null);+ if (reference.Value.TryBinding<ExactBrepRegionBinding>(out var region))+ return (new(region.Body.Topology.Bodies.Single().Id.Value.ToString(), reference.Value.ExposedName ?? reference.Value.StableIdentity,+ RecognizedFaceIds: region.Faces.OrderBy(face => face.Value).Select(face => face.Value.ToString()).ToArray(), Provenance: Provenance(reference),+ SemanticStableId: reference.Value.StableIdentity,+ CapabilityEvidence: reference.Value.Capabilities.Values.Select(capability => capability.Name).ToArray(), ExactBindingKind: region.Kind), null);+ return (null, new(SemanticValueValidator.NoExactBinding,+ $"BoundaryRegionCapable value '{reference.Value.StableIdentity}' has no exact analysis/BRep region binding.", reference.ConsumerSourceSpan));+ }++ private static AnalysisProvenance Provenance(SemanticReference reference)+ {+ var span = reference.Value.AuthoredSourceSpan ?? reference.ConsumerSourceSpan;+ return new(span.Source, span.Start, span.Length,+ string.Join(" -> ", reference.Value.Provenance.Select(item => item.Stage + ":" + item.Identity)));+ }+}diff --git a/Aetheris.FEA/Firmament/FirmamentAnalysisCompiler.cs b/Aetheris.FEA/Firmament/FirmamentAnalysisCompiler.csindex 8e531b90..431a7684 100644--- a/Aetheris.FEA/Firmament/FirmamentAnalysisCompiler.cs+++ b/Aetheris.FEA/Firmament/FirmamentAnalysisCompiler.cs@@ -8,6 +8,9 @@ using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Math;using Aetheris.Kernel.Core.Geometry;using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Core.Topology;+using Aetheris.Semantics;namespace Aetheris.FEA.Firmament;@@ -29,11 +32,29 @@ public static class FirmamentAnalysisCompilervar block=source[(open+1)..close];var analysisSpan=new AnalysisProvenance(sourcePath??"<memory>",match.Index,close-match.Index+1,match.Value);var stripped=source.Remove(match.Index,close-match.Index+1);var bodyName=Scalar(block,"body")??string.Empty;var resourceName=(Scalar(block,"bodyResource")??string.Empty).TrimStart('$');- IContinuumRegion? region=null;string sourceKind;string? resourceHash=null;string? brepBodyId=null;string bodyId;- if(resourceName.Length>0)+ IContinuumRegion? region=null;string sourceKind;string? resourceHash=null;string? brepBodyId=null;string bodyId;IReadOnlyDictionary<string,string> semanticFaceIds=new Dictionary<string,string>();var namedRegions=new Dictionary<string,SemanticValue>(StringComparer.Ordinal);+ var sourceParse=FirmamentV2Parser.Parse(stripped,sourceDirectory);var directInline=sourceParse.Document?.Solids.SingleOrDefault(item=>item.Name==bodyName)?.InlineStep;+ if(resourceName.Length>0||directInline is not null){bodyId=bodyName.Length>0?bodyName:resourceName;sourceKind="InlineStep";- if(resources is null||!resources.TryGetValue(resourceName,out var resource)){diagnostics.Add(Error("firmament-analysis-resource-missing",$"InlineStep analysis resource '${resourceName}' is not bound.",sourcePath));return Done(null,diagnostics,started);}+ FirmamentAnalysisResource resource;+ if(resourceName.Length>0)+ {+ if(resources is null||!resources.TryGetValue(resourceName,out resource!)){diagnostics.Add(Error("firmament-analysis-resource-missing",$"InlineStep analysis resource '${resourceName}' is not bound.",sourcePath));return Done(null,diagnostics,started);}+ }+ else+ {+ var imported=Step242Importer.ImportBody(File.ReadAllText(directInline!.NormalizedPath));+ if(!imported.IsSuccess||imported.Value is null){diagnostics.Add(Error("firmament-analysis-inline-step-import-failed",string.Join("; ",imported.Diagnostics.Select(item=>item.Message)),sourcePath));return Done(null,diagnostics,started);}+ resource=new(bodyId,directInline.ContentHash,imported.Value);+ if(sourceParse.Document!.RecognizedRegions?.Count>0)+ {+ var faceMap=new Dictionary<string,FaceId>(StringComparer.Ordinal);+ foreach(var pair in directInline.TopologyMap.FaceEntityToFaceId){var token=pair.Value.StartsWith("face-",StringComparison.Ordinal)?pair.Value[5..]:pair.Value;if(int.TryParse(token,out var id))faceMap[pair.Key]=new(id);}+ var semanticRoot=FirmamentSemanticValues.FromRecognizedRegions(sourceParse.Document,resource.Body,faceMap,directInline.ContentHash,new(sourcePath??"<memory>",0,stripped.Length)).Single(value=>value.Type.Name=="ImportedBody");+ foreach(var member in semanticRoot.ExposedMembers)namedRegions[bodyId+"."+member.Key]=member.Value;+ }+ }var points=resource.Body.Topology.Vertices.Select(v=>resource.Body.TryGetVertexPoint(v.Id,out var point)?point:(Point3D?)null).Where(p=>p.HasValue).Select(p=>p!.Value).ToArray();if(points.Length==0){diagnostics.Add(Error("firmament-analysis-inline-step-bounds-unavailable","Imported STEP has no exact vertex positions for bounded M5 CIR recognition.",sourcePath));return Done(null,diagnostics,started);}var rawMin=new Point3D(points.Min(p=>p.X),points.Min(p=>p.Y),points.Min(p=>p.Z));var rawMax=new Point3D(points.Max(p=>p.X),points.Max(p=>p.Y),points.Max(p=>p.Z));const double stepMeters=0.001;var size=(rawMax-rawMin)*stepMeters;var center=new Vector3D((rawMin.X+rawMax.X)*stepMeters/2,(rawMin.Y+rawMax.Y)*stepMeters/2,(rawMin.Z+rawMax.Z)*stepMeters/2);@@ -45,7 +66,7 @@ public static class FirmamentAnalysisCompilervar surface=resource.Body.Geometry.GetSurface(binding.SurfaceGeometryId);if(surface.Kind!=SurfaceGeometryKind.Plane||surface.Plane is not { } plane)continue;var n=plane.Normal.ToVector();string token=double.Abs(n.X)>0.9?(double.Abs(plane.Origin.X-rawMin.X)<double.Abs(plane.Origin.X-rawMax.X)?"x-min":"x-max"):double.Abs(n.Y)>0.9?(double.Abs(plane.Origin.Y-rawMin.Y)<double.Abs(plane.Origin.Y-rawMax.Y)?"y-min":"y-max"):(double.Abs(plane.Origin.Z-rawMin.Z)<double.Abs(plane.Origin.Z-rawMax.Z)?"z-min":"z-max");faceIds[token]=binding.FaceId.Value.ToString(CultureInfo.InvariantCulture);}- region=new ExactBrepBoxContinuumRegion(new RegionId(bodyId+":inline-cir"),size.X,size.Y,size.Z,Transform3D.CreateTranslation(center),faceIds);resourceHash=resource.ContentHash;brepBodyId=resource.Body.Topology.Bodies.Single().Id.Value.ToString(CultureInfo.InvariantCulture);+ region=new ExactBrepBoxContinuumRegion(new RegionId(bodyId+":inline-cir"),size.X,size.Y,size.Z,Transform3D.CreateTranslation(center),faceIds);semanticFaceIds=faceIds;resourceHash=resource.ContentHash;brepBodyId=resource.Body.Topology.Bodies.Single().Id.Value.ToString(CultureInfo.InvariantCulture);}else{@@ -66,17 +87,28 @@ public static class FirmamentAnalysisCompilervar young=Stress(Scalar(materialBlock,"youngsModulus"));var poisson=Number(Scalar(materialBlock,"poissonRatio"));var density=Density(Scalar(materialBlock,"density"));var materialProv=new AnalysisProvenance(sourcePath??"<memory>",open+materialStart,materialBlock.Length,"material "+materialName);var material=new LinearElasticMaterialIr(materialName,young,poisson,density,bodyId,materialProv);+ (SemanticRegionBinding? Region,AnalysisDiagnostic? Diagnostic) NormalizeRegion(string path,AnalysisProvenance provenance)+ {+ if(namedRegions.TryGetValue(path,out var semantic))+ {+ var span=new SemanticSourceSpan(provenance.Source,provenance.Start,provenance.Length);var normalized=AnalysisSemanticRegionNormalizer.Normalize(new(semantic,[new(path,span)],span));+ return normalized.Diagnostic is null?(normalized.Region,null):(null,new(normalized.Diagnostic.Code,AnalysisDiagnosticSeverity.Error,normalized.Diagnostic.Message,provenance));+ }+ return FirmamentAnalysisSemanticProducer.Normalize(path,bodyId,semanticFaceIds,provenance,sourceKind);+ }var constraints=new List<DisplacementConstraintIr>();foreach(var nested in NestedAll(block,"fixed")){var path=Scalar(nested.Body,"region")??"";var components=Components(Scalar(nested.Body,"components"));if(components.Count==0)components=[DisplacementComponent.X,DisplacementComponent.Y,DisplacementComponent.Z];var prov=new AnalysisProvenance(sourcePath??"<memory>",open+nested.Start,nested.Length,"fixed "+nested.Name);- constraints.Add(new(nested.Name,new(bodyId,path,Provenance:prov),components,new(0,0,0),prov));+ var normalized=NormalizeRegion(path,prov);if(normalized.Diagnostic is not null){diagnostics.Add(normalized.Diagnostic);continue;}+ constraints.Add(new(nested.Name,normalized.Region!,components,new(0,0,0),prov));}var loads=new List<BoundaryLoadIr>();foreach(var keyword in new[]{("traction",BoundaryLoadKind.Traction),("force",BoundaryLoadKind.ResultantForce),("pressure",BoundaryLoadKind.Pressure)})foreach(var nested in NestedAll(block,keyword.Item1)){var path=Scalar(nested.Body,"region")??"";var prov=new AnalysisProvenance(sourcePath??"<memory>",open+nested.Start,nested.Length,keyword.Item1+" "+nested.Name);var vector=Vector(Scalar(nested.Body,"vector"),keyword.Item2==BoundaryLoadKind.ResultantForce);var pressure=keyword.Item2==BoundaryLoadKind.Pressure?Stress(Scalar(nested.Body,"value")):0;- loads.Add(new(nested.Name,keyword.Item2,new(bodyId,path,Provenance:prov),vector,pressure,prov));+ var normalized=NormalizeRegion(path,prov);if(normalized.Diagnostic is not null){diagnostics.Add(normalized.Diagnostic);continue;}+ loads.Add(new(nested.Name,keyword.Item2,normalized.Region!,vector,pressure,prov));}var latticeValues=Numbers(Scalar(block,"lattice"));var lattice=latticeValues.Length==3?new LatticeSpec(region.Bounds,(int)latticeValues[0],(int)latticeValues[1],(int)latticeValues[2]):new LatticeSpec(region.Bounds,12,6,2);var requested=(Scalar(block,"results")??"Displacement,Strain,Stress,ReactionForce").Trim('[',']').Split(',',StringSplitOptions.RemoveEmptyEntries|StringSplitOptions.TrimEntries).Select(Enum.Parse<AnalysisResultField>).ToHashSet();diff --git a/Aetheris.FEA/Firmament/FirmamentAnalysisSemanticProducer.cs b/Aetheris.FEA/Firmament/FirmamentAnalysisSemanticProducer.csnew file mode 100644index 00000000..5f49ed02--- /dev/null+++ b/Aetheris.FEA/Firmament/FirmamentAnalysisSemanticProducer.cs@@ -0,0 +1,55 @@+using System.Text.RegularExpressions;+using Aetheris.FEA.Analysis;+using Aetheris.Semantics;++namespace Aetheris.FEA.Firmament;++internal static partial class FirmamentAnalysisSemanticProducer+{+ [GeneratedRegex(@"^(?<body>[A-Za-z_][A-Za-z0-9_]*)\.face\((?<side>[+-][XYZ])\)$", RegexOptions.CultureInvariant)]+ private static partial Regex FacePath();++ public static (SemanticValue? Value, SemanticDiagnostic? Diagnostic) Bind(+ string authoredPath,+ string expectedBody,+ IReadOnlyDictionary<string, string> exactFaceIds,+ SemanticSourceSpan sourceSpan,+ string origin)+ {+ var match = FacePath().Match(authoredPath);+ if (!match.Success || !string.Equals(match.Groups["body"].Value, expectedBody, StringComparison.Ordinal))+ return (null, new(SemanticValueValidator.PathMemberMissing,+ $"Boundary region '{authoredPath}' is not an exposed face of semantic body '{expectedBody}'.", sourceSpan));+ var side = match.Groups["side"].Value;+ var token = side switch { "-X" => "x-min", "+X" => "x-max", "-Y" => "y-min", "+Y" => "y-max", "-Z" => "z-min", "+Z" => "z-max", _ => string.Empty };+ exactFaceIds.TryGetValue(token, out var faceId);+ var stableId = $"analysis-region:{origin}:{expectedBody}:face({side})" + (faceId is null ? string.Empty : ":" + faceId);+ return (new SemanticValue(stableId, new("BoundaryRegion"),+ [new BoundaryRegionCapability(), new AnalysisRegionCapability(), new ExactGeometryCapability()],+ [new ExactAnalysisRegionBinding(expectedBody, authoredPath, faceId)],+ provenance:+ [+ new(origin, expectedBody, faceId is null ? "exact analytic boundary" : "exact imported BRep face", sourceSpan),+ new("semantic-path", authoredPath, "structurally bound face selector", sourceSpan),+ ],+ authoredSourceSpan: sourceSpan,+ exposedName: $"face({side})"), null);+ }++ public static (SemanticRegionBinding? Region, AnalysisDiagnostic? Diagnostic) Normalize(+ string authoredPath,+ string body,+ IReadOnlyDictionary<string, string> exactFaceIds,+ AnalysisProvenance consumerProvenance,+ string origin)+ {+ var span = new SemanticSourceSpan(consumerProvenance.Source, consumerProvenance.Start, consumerProvenance.Length);+ var (value, bindDiagnostic) = Bind(authoredPath, body, exactFaceIds, span, origin);+ if (bindDiagnostic is not null)+ return (null, new(bindDiagnostic.Code, AnalysisDiagnosticSeverity.Error, bindDiagnostic.Message, consumerProvenance));+ var (region, normalizeDiagnostic) = AnalysisSemanticRegionNormalizer.Normalize(new(value!, [new(authoredPath, span)], span));+ return normalizeDiagnostic is null+ ? (region, null)+ : (null, new(normalizeDiagnostic.Code, AnalysisDiagnosticSeverity.Error, normalizeDiagnostic.Message, consumerProvenance));+ }+}diff --git a/Aetheris.Forge.SampleExtension/SecretGeometryExtension.cs b/Aetheris.Forge.SampleExtension/SecretGeometryExtension.csindex b16c2454..cb227939 100644--- a/Aetheris.Forge.SampleExtension/SecretGeometryExtension.cs+++ b/Aetheris.Forge.SampleExtension/SecretGeometryExtension.cs@@ -2,6 +2,8 @@ using System.Globalization;using Aetheris.Forge.Extensions;using Aetheris.Kernel.Core.Construction;using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Semantics;namespace MyCompany.SecretGeometry;@@ -57,8 +59,29 @@ public sealed class SecretCouponCapability : IForgeCapability[0, 1, 2, 3],["PrismaticExtrude"],[context.SourceIdentity, context.TemplateIdentity, CapabilityId.Value, SecretGeometryExtension.ExtensionId + "@1.0.0"]);+ var body = ForgeCapabilityExecutor.MaterializeConstruction(descriptor);+ var planarFaces = body.Bindings.FaceBindings.Select(binding =>+ (binding.FaceId, Plane: body.Geometry.GetSurface(binding.SurfaceGeometryId).Plane)).Where(item => item.Plane is not null).ToArray();+ var topFace = planarFaces.Single(item => item.Plane!.Value.Normal.ToVector().Z > 0.9d).FaceId;+ var loadFace = planarFaces.Single(item => item.Plane!.Value.Normal.ToVector().X > 0.9d).FaceId;+ var semanticSpan = SemanticSourceSpan.Generated(context.SourceIdentity);+ var semanticProvenance = new[]+ {+ new SemanticProvenance("template-specialization", context.TemplateIdentity, context.InvocationIdentity, semanticSpan),+ new SemanticProvenance("forge-capability", CapabilityId.Value + "@1.0.0", SecretGeometryExtension.ExtensionId + "@1.0.0", semanticSpan),+ };+ SemanticValue Face(string name, Aetheris.Kernel.Core.Topology.FaceId face) => new(+ $"forge:{sourceIdentity}.{name}", new("BoundaryRegion"),+ [new BoundaryRegionCapability(), new SelectableCapability(), new ExactGeometryCapability(), new AnalysisRegionCapability(), new ModifyTargetCapability()],+ [new ExactBrepFaceBinding(body, face, $"forge:{sourceIdentity}.{name}"), new ConstructionIdentityBinding(sourceIdentity)],+ provenance: semanticProvenance, generatedSourceSpan: semanticSpan, exposedName: name);+ var semanticRoot = new SemanticValue($"forge:{sourceIdentity}", new("Body"),+ [new BodyCapability(), new SelectableCapability(), new ExactGeometryCapability(), new ModifyTargetCapability()],+ [new ExactBrepBodyBinding(body, $"forge:{sourceIdentity}"), new ConstructionIdentityBinding(sourceIdentity)],+ [Face("TopFace", topFace), Face("LoadRegion", loadFace)], semanticProvenance, generatedSourceSpan: semanticSpan);return ForgeCapabilityExecutionResult.Success(new ForgeCapabilityOutput(descriptor,+ ExactBrep: body,ContinuumConstruction: descriptor,Provenance: new Dictionary<string, string>(StringComparer.Ordinal){@@ -67,7 +90,8 @@ public sealed class SecretCouponCapability : IForgeCapability["source"] = context.SourceIdentity,["template"] = context.TemplateIdentity,["construction"] = sourceIdentity,- }));+ },+ SemanticRoot: semanticRoot));}private static double Positive(double value, string name)diff --git a/Aetheris.Forge.Sdk.Tests/ForgeSdkM1Tests.cs b/Aetheris.Forge.Sdk.Tests/ForgeSdkM1Tests.csindex 53c034cb..86ce33c9 100644--- a/Aetheris.Forge.Sdk.Tests/ForgeSdkM1Tests.cs+++ b/Aetheris.Forge.Sdk.Tests/ForgeSdkM1Tests.cs@@ -38,6 +38,17 @@ public sealed class ForgeSdkM1TestsAssert.Equal(SecretCouponCapability.CapabilityId.Value, first.Artifact.Capabilities[0].CapabilityId);Assert.Contains("record-arguments=Spec", first.Artifact.Provenance[1].Evidence, StringComparison.Ordinal);Assert.True(first.Artifact.Body!.Topology.Faces.Count() >= 6);+ var semantic = Assert.IsType<Aetheris.Semantics.SemanticValueDescriptor>(first.Artifact.SemanticOutput);+ Assert.Equal("Body", semantic.SemanticType);+ Assert.Contains("BodyCapable", semantic.Capabilities);+ Assert.Equal(new[] { "LoadRegion", "TopFace" }, semantic.Members.Select(member => member.StableId.Split('.').Last()).Order(StringComparer.Ordinal));+ Assert.All(semantic.Members, member =>+ {+ Assert.Contains("BoundaryRegionCapable", member.Capabilities);+ Assert.Contains("ExactBrepFace", member.BindingKinds);+ Assert.Contains(member.Provenance, item => item.Stage == "forge-capability");+ });+ Assert.Equal(semantic.StableId, second.Artifact!.SemanticOutput!.StableId);}[Fact]diff --git a/Aetheris.Forge.Sdk/ForgeHost.cs b/Aetheris.Forge.Sdk/ForgeHost.csindex a3d6049a..c9dbed7a 100644--- a/Aetheris.Forge.Sdk/ForgeHost.cs+++ b/Aetheris.Forge.Sdk/ForgeHost.cs@@ -205,7 +205,8 @@ public sealed class ForgeHost};var hash = ArtifactHash(exported.Value, expansion.SpecializationIdentity, [capabilityEvidence], provenance);return new ForgeCompilationResult(- new ForgeCompilationArtifact(exported.Value, hash, body, cir, [capabilityEvidence], provenance),+ new ForgeCompilationArtifact(exported.Value, hash, body, cir, [capabilityEvidence], provenance,+ execution.Output.SemanticRoot is null ? null : Aetheris.Semantics.SemanticValueDescriptor.From(execution.Output.SemanticRoot)),diagnostics,registrationTime,resolutionTime,diff --git a/Aetheris.Forge.Sdk/ForgeSdkModels.cs b/Aetheris.Forge.Sdk/ForgeSdkModels.csindex 90f8efd9..404ce25b 100644--- a/Aetheris.Forge.Sdk/ForgeSdkModels.cs+++ b/Aetheris.Forge.Sdk/ForgeSdkModels.cs@@ -5,6 +5,7 @@ using Aetheris.Kernel.Core.Brep;using Aetheris.FEA.Abaqus;using Aetheris.FEA.Analysis;using Aetheris.FEA.Mechanics;+using Aetheris.Semantics;namespace Aetheris.Forge.Sdk;@@ -49,7 +50,8 @@ public sealed record ForgeCompilationArtifact(BrepBody? Body,ForgeCirEvidence? Cir,IReadOnlyList<ForgeCapabilityEvidence> Capabilities,- IReadOnlyList<ForgeProvenanceEntry> Provenance);+ IReadOnlyList<ForgeProvenanceEntry> Provenance,+ SemanticValueDescriptor? SemanticOutput = null);public sealed record ForgeCompilationResult(ForgeCompilationArtifact? Artifact,diff --git a/Aetheris.Forge/Aetheris.Forge.csproj b/Aetheris.Forge/Aetheris.Forge.csprojindex c4134034..ee2ec0b7 100644--- a/Aetheris.Forge/Aetheris.Forge.csproj+++ b/Aetheris.Forge/Aetheris.Forge.csproj@@ -7,5 +7,6 @@<ItemGroup><ProjectReference Include="..\Aetheris.Kernel.Core\Aetheris.Kernel.Core.csproj" />+ <ProjectReference Include="..\Aetheris.Semantics\Aetheris.Semantics.csproj" /></ItemGroup></Project>diff --git a/Aetheris.Forge/Extensions/ForgeCapabilityExecutor.cs b/Aetheris.Forge/Extensions/ForgeCapabilityExecutor.csindex a14d4d5c..db4973b8 100644--- a/Aetheris.Forge/Extensions/ForgeCapabilityExecutor.cs+++ b/Aetheris.Forge/Extensions/ForgeCapabilityExecutor.cs@@ -4,6 +4,7 @@ using Aetheris.Kernel.Core.Brep.Features;using Aetheris.Kernel.Core.Construction;using Aetheris.Kernel.Core.Geometry;using Aetheris.Kernel.Core.Math;+using Aetheris.Semantics;namespace Aetheris.Forge.Extensions;@@ -44,6 +45,22 @@ public static class ForgeCapabilityExecutor}if (result.Output?.Provenance is null || !result.Output.Provenance.ContainsKey("capability"))return ForgeCapabilityExecutionResult.Failure(Error("forge-capability-provenance-missing", $"Capability '{id}' did not emit required capability provenance.", id, context));+ if (result.Output.SemanticRoot is { } semanticRoot)+ {+ var semanticDiagnostics = SemanticValueValidator.Validate(semanticRoot);+ if (semanticDiagnostics.Count > 0)+ return ForgeCapabilityExecutionResult.Failure(Error(SemanticValueValidator.ForgeOutputInvalid,+ string.Join("; ", semanticDiagnostics.Select(item => item.Code + ": " + item.Message)), id, context));+ if (!semanticRoot.Provenance.Any(item => item.Stage == "forge-capability" && item.Identity.Contains(id.Value, StringComparison.Ordinal)))+ return ForgeCapabilityExecutionResult.Failure(Error(SemanticValueValidator.ForgeOutputInvalid,+ $"Forge semantic root '{semanticRoot.StableIdentity}' lacks capability/version provenance.", id, context));+ var semanticBindings = Flatten(semanticRoot).SelectMany(value => value.Bindings).ToArray();+ if (semanticBindings.OfType<ExactBrepBodyBinding>().Any(binding => result.Output.ExactBrep is null || !ReferenceEquals(binding.Body, result.Output.ExactBrep))+ || semanticBindings.OfType<ExactBrepFaceBinding>().Any(binding => result.Output.ExactBrep is null || !ReferenceEquals(binding.Body, result.Output.ExactBrep) || !binding.Body.Topology.TryGetFace(binding.Face, out _))+ || semanticBindings.OfType<ExactBrepRegionBinding>().Any(binding => result.Output.ExactBrep is null || !ReferenceEquals(binding.Body, result.Output.ExactBrep) || binding.Faces.Any(face => !binding.Body.Topology.TryGetFace(face, out _))))+ return ForgeCapabilityExecutionResult.Failure(Error(SemanticValueValidator.ForgeOutputInvalid,+ "Forge exact semantic BRep binding does not match the capability ExactBrep output/association.", id, context));+ }return result;}catch (ForgeCapabilityAdmissionException exception)@@ -113,4 +130,11 @@ public static class ForgeCapabilityExecutorprivate static ForgeExtensionDiagnostic Error(string code, string message, ForgeCapabilityId id, ForgeCapabilityInvocationContext context) =>new(code, ForgeDiagnosticSeverity.Error, message, id.Value, context.SourceIdentity);++ private static IEnumerable<SemanticValue> Flatten(SemanticValue value)+ {+ yield return value;+ foreach (var member in value.ExposedMembers.Values)+ foreach (var nested in Flatten(member)) yield return nested;+ }}diff --git a/Aetheris.Forge/Extensions/ForgeExtensionContracts.cs b/Aetheris.Forge/Extensions/ForgeExtensionContracts.csindex b7310db7..a333d626 100644--- a/Aetheris.Forge/Extensions/ForgeExtensionContracts.cs+++ b/Aetheris.Forge/Extensions/ForgeExtensionContracts.cs@@ -2,6 +2,7 @@ using System.Collections.ObjectModel;using Aetheris.Forge.Abstractions;using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Construction;+using Aetheris.Semantics;namespace Aetheris.Forge.Extensions;@@ -110,7 +111,8 @@ public sealed record ForgeCapabilityOutput(ContinuumConstructionDescriptor? Construction,BrepBody? ExactBrep = null,ContinuumConstructionDescriptor? ContinuumConstruction = null,- IReadOnlyDictionary<string, string>? Provenance = null);+ IReadOnlyDictionary<string, string>? Provenance = null,+ SemanticValue? SemanticRoot = null);public sealed record ForgeExtensionDiagnostic(string Code,diff --git a/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj b/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csprojindex 61e4a4e3..a189b948 100644--- a/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj+++ b/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj@@ -8,6 +8,7 @@<ItemGroup><ProjectReference Include="..\Aetheris.Continuum\Aetheris.Continuum.csproj" /><ProjectReference Include="..\Aetheris.Kernel.Core\Aetheris.Kernel.Core.csproj" />+ <ProjectReference Include="..\Aetheris.Semantics\Aetheris.Semantics.csproj" /><ProjectReference Include="..\Aetheris.Kernel.StandardLibrary\Aetheris.Kernel.StandardLibrary.csproj" /><ProjectReference Include="..\Aetheris.Forge\Aetheris.Forge.csproj" /></ItemGroup>diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSemanticValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSemanticValues.csnew file mode 100644index 00000000..e2046be6--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSemanticValues.cs@@ -0,0 +1,169 @@+using System.Text.RegularExpressions;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Topology;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.Materializer;+using Aetheris.Semantics;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++public sealed record ResolvedProfileSemanticBinding(ResolvedProfile2D Profile)+ : ExactProfileBinding("profile:" + Profile.Name)+{+ public override IReadOnlyList<string> ValidateExactProfile() =>+ ResolvedProfile2DValidator.Validate(Profile).Diagnostics;+}++/// <summary>Normalizes native, template-expanded, Concept Path, and Recognize producers.</summary>+public static class FirmamentSemanticValues+{+ public static IReadOnlyList<SemanticValue> FromRecognizedRegions(FirmamentV2Document document, string sourceIdentity, string source)+ {+ var output = new List<SemanticValue>();+ foreach (var bodyName in (document.RecognizedRegions ?? []).Select(region => region.BodyName).Distinct(StringComparer.Ordinal))+ {+ var solid = document.Solids.Single(item => item.Name == bodyName);+ var inline = solid.InlineStep ?? throw new ArgumentException($"Recognized body '{bodyName}' is not InlineStep.");+ var imported = Step242Importer.ImportBody(File.ReadAllText(inline.NormalizedPath));+ if (!imported.IsSuccess || imported.Value is null)+ throw new InvalidDataException($"Recognized body '{bodyName}' could not be re-imported through the exact STEP path: {string.Join("; ", imported.Diagnostics.Select(item => item.Message))}");+ var map = new Dictionary<string, FaceId>(StringComparer.Ordinal);+ foreach (var pair in inline.TopologyMap.FaceEntityToFaceId)+ {+ var token = pair.Value.StartsWith("face-", StringComparison.Ordinal) ? pair.Value[5..] : pair.Value;+ if (!int.TryParse(token, out var faceValue)) throw new InvalidDataException($"Imported face association '{pair.Value}' is not a stable FaceId.");+ var face = new FaceId(faceValue);+ if (!imported.Value.Topology.TryGetFace(face, out _)) throw new InvalidDataException($"Imported face association '{pair.Key}' -> '{pair.Value}' is stale.");+ map[pair.Key] = face;+ }+ var match = Regex.Match(source, $@"\bRecognize\s+{Regex.Escape(bodyName)}\s*\{{", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);+ var span = new SemanticSourceSpan(sourceIdentity, match.Success ? match.Index : 0, match.Success ? DeclarationLength(source, match.Index) : 0);+ var subset = document with { RecognizedRegions = document.RecognizedRegions!.Where(region => region.BodyName == bodyName).ToArray() };+ output.AddRange(FromRecognizedRegions(subset, imported.Value, map, inline.ContentHash, span));+ }+ return output;+ }++ public static IReadOnlyList<SemanticValue> FromProfilesAndConceptPaths(string source, string sourceIdentity = "<memory>", ICollection<string>? reportedDiagnostics = null)+ {+ var expansionDiagnostics = new List<string>();+ var expansion = FirmamentV2TemplateExpansion.Expand(source, expansionDiagnostics);+ foreach (var diagnostic in expansionDiagnostics) reportedDiagnostics?.Add(diagnostic);+ var expanded = expansion?.Source ?? source;+ var bindDiagnostics = new List<string>();+ var profiles = ProfileAuthoringParser.BindPathDerivedProfiles(expanded, bindDiagnostics);+ foreach (var diagnostic in bindDiagnostics) reportedDiagnostics?.Add(diagnostic);+ var inspections = ProfileAuthoringParser.InspectConceptPaths(source);+ var values = new List<SemanticValue>();+ foreach (var inspection in inspections.OrderBy(item => item.Name, StringComparer.Ordinal))+ {+ var match = Regex.Match(expanded, $@"\bConcept\s+Path\s+{Regex.Escape(inspection.Name)}\s*\{{", RegexOptions.CultureInvariant);+ var span = new SemanticSourceSpan(sourceIdentity, match.Success ? match.Index : 0, match.Success ? DeclarationLength(expanded, match.Index) : 0);+ var authoredSpan = expansion?.Instantiations.FirstOrDefault() is { } instantiation+ ? new SemanticSourceSpan(sourceIdentity, instantiation.ApplicationSourceSpan.Start, instantiation.ApplicationSourceSpan.Length)+ : span;+ var members = new List<SemanticValue>+ {+ new($"concept-path:{inspection.Name}.Start", new("Point2"), provenance: [new("concept-path", inspection.Name, "validated start", authoredSpan)], authoredSourceSpan: authoredSpan, generatedSourceSpan: expansion is null ? null : span, exposedName: "Start")+ };+ foreach (var entry in inspection.Entries)+ {+ var stepMatch = Regex.Match(expanded, $@"\b(?:Line|Arc|Close)\s+{Regex.Escape(entry.Name)}\b", RegexOptions.CultureInvariant);+ var stepSpan = new SemanticSourceSpan(sourceIdentity, stepMatch.Success ? stepMatch.Index : span.Start, stepMatch.Success ? DeclarationLength(expanded, stepMatch.Index) : span.Length);+ var memberAuthoredSpan = expansion is null ? stepSpan : authoredSpan;+ var end = new SemanticValue(entry.EndpointId, new("Point2"), provenance: [new("concept-path-segment", entry.Name, "validated endpoint", memberAuthoredSpan)], authoredSourceSpan: memberAuthoredSpan, generatedSourceSpan: expansion is null ? null : stepSpan, exposedName: "End");+ members.Add(new SemanticValue(entry.GuideId, new(entry.Kind + "2"), exposedMembers: [end], provenance: [new("concept-path-segment", entry.Name, "validated ordered planar guide", memberAuthoredSpan)], authoredSourceSpan: memberAuthoredSpan, generatedSourceSpan: expansion is null ? null : stepSpan, exposedName: entry.Name));+ }+ var capabilities = new List<ISemanticCapability>();+ var bindings = new List<SemanticBinding>();+ if (profiles.Values.FirstOrDefault(profile => inspection.Consumers?.Any(consumer => consumer.Kind == "Profile" && consumer.Name == profile.Name) == true) is { } profile)+ {+ capabilities.AddRange([new ProfileCapability(), new SelectableCapability(), new ExactGeometryCapability(), new ComposeOperandCapability()]);+ bindings.Add(new ResolvedProfileSemanticBinding(profile));+ }+ var provenance = new List<SemanticProvenance> { new("authored", inspection.Name, "Concept Path", authoredSpan) };+ if (expansion is not null)+ provenance.AddRange(expansion.Instantiations.Select(item => new SemanticProvenance("template-specialization", item.SpecializationIdentity, "expanded before semantic normalization", new(sourceIdentity, item.ApplicationSourceSpan.Start, item.ApplicationSourceSpan.Length))));+ values.Add(new SemanticValue(inspection.Provenance ?? "concept-path:" + inspection.Name, new("ConceptPath"), capabilities, bindings, members, provenance, authoredSpan, expansion is null ? null : span));+ }+ return values;+ }++ public static SemanticValue FromProfile(ResolvedProfile2D profile, SemanticSourceSpan span, IEnumerable<SemanticProvenance>? provenance = null, string? exposedName = null) =>+ new("profile:" + profile.Name, new("Profile2D"),+ [new ProfileCapability(), new SelectableCapability(), new ExactGeometryCapability(), new ComposeOperandCapability(), new ModifyTargetCapability()],+ [new ResolvedProfileSemanticBinding(profile)], provenance: provenance, authoredSourceSpan: span, exposedName: exposedName);++ public static IReadOnlyList<SemanticValue> FromConceptIr(ConceptIrDocument document, string sourceIdentity = "<memory>")+ {+ SemanticValue Scalar(ConceptIrValue value, string? exposedName = null) => new(+ value.StableId, new(value.Kind.ToString()), provenance: [new("concept-ir", value.StableId, value.Provenance)], exposedName: exposedName);+ var values = document.ResolvedValues.Select(value => Scalar(value)).ToList();+ foreach (var item in document.Structs)+ {+ var span = new SemanticSourceSpan(sourceIdentity, item.SourceSpan.Start, item.SourceSpan.Length);+ var members = item.Members.OrderBy(pair => pair.Key, StringComparer.Ordinal).Select(pair => Scalar(pair.Value, pair.Key)).ToArray();+ values.Add(new SemanticValue("concept-struct:" + item.Name, new("ConceptStruct"), exposedMembers: members,+ provenance: [new("authored", item.Name, string.Join(",", item.Satisfies), span)], authoredSourceSpan: span));+ }+ return values;+ }++ public static IReadOnlyList<SemanticValue> FromRecognizedRegions(+ FirmamentV2Document document,+ BrepBody body,+ IReadOnlyDictionary<string, FaceId> importedFaceMap,+ string importedSourceIdentity,+ SemanticSourceSpan recognizeSpan)+ {+ var output = new List<SemanticValue>();+ foreach (var bodyGroup in (document.RecognizedRegions ?? []).GroupBy(region => region.BodyName, StringComparer.Ordinal))+ {+ var members = new List<SemanticValue>();+ foreach (var region in bodyGroup.OrderBy(item => item.RegionName, StringComparer.Ordinal))+ {+ var faceIds = region.FaceRefs.Distinct(StringComparer.Ordinal).Select(reference =>+ importedFaceMap.TryGetValue(reference, out var face) ? face : throw new ArgumentException($"Recognized face '{reference}' has no exact imported BRep association.")).ToArray();+ if (faceIds.Length == 0) continue;+ var stableId = $"recognize:{importedSourceIdentity}:{bodyGroup.Key}.{region.RegionName}:{string.Join(",", region.FaceRefs.Order(StringComparer.Ordinal))}";+ var exact = faceIds.Length == 1+ ? (SemanticBinding)new ExactBrepFaceBinding(body, faceIds[0], stableId)+ : new ExactBrepRegionBinding(body, faceIds, stableId);+ members.Add(new SemanticValue(stableId, new("RecognizedRegion"),+ [new BoundaryRegionCapability(), new SelectableCapability(), new ExactGeometryCapability(), new AnalysisRegionCapability(), new ModifyTargetCapability()],+ [exact, new ImportedEntityBinding(importedSourceIdentity, region.FaceRefs)],+ provenance:+ [+ new("inline-step", importedSourceIdentity, "canonical imported source"),+ new("recognize", bodyGroup.Key + "." + region.RegionName, $"kind={region.Kind};confidence={region.Confidence}", recognizeSpan),+ ],+ authoredSourceSpan: recognizeSpan,+ exposedName: region.RegionName));+ }+ var rootId = $"inline-step:{importedSourceIdentity}:{bodyGroup.Key}";+ output.Add(new SemanticValue(rootId, new("ImportedBody"),+ [new BodyCapability(), new ExactGeometryCapability(), new SelectableCapability(), new ModifyTargetCapability()],+ [new ExactBrepBodyBinding(body, rootId), new ImportedEntityBinding(importedSourceIdentity, [])],+ members,+ [new("inline-step", importedSourceIdentity, "exact canonical BRep import", recognizeSpan)], recognizeSpan));+ }+ return output;+ }++ private static int DeclarationLength(string source, int start)+ {+ var open = source.IndexOf('{', start);+ if (open < 0)+ {+ var end = source.IndexOfAny(['\r', '\n'], start);+ return Math.Max(0, end >= 0 ? end - start : source.Length - start);+ }+ var depth = 0;+ for (var index = open; index < source.Length; index++)+ {+ if (source[index] == '{') depth++;+ else if (source[index] == '}' && --depth == 0) return index - start + 1;+ }+ return 0;+ }+}diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.csindex 84e4090a..aadbbc99 100644--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs@@ -2,6 +2,7 @@ using System.Globalization;using System.Text.RegularExpressions;using Aetheris.Kernel.Core.Math;using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Semantics;namespace Aetheris.Kernel.Firmament.Materializer;@@ -183,10 +184,13 @@ public static class PrismaticProfileCompositionParser// Profile is the capability boundary. Concept Path is normalized by the// canonical profile binder before Compose resolves its operands, so the// section-stack compiler never needs a path-specific lowering branch.- foreach (var pathProfile in ProfileAuthoringParser.BindPathDerivedProfiles(source, diagnostics))+ foreach (var semantic in FirmamentSemanticValues.FromProfilesAndConceptPaths(source, reportedDiagnostics: diagnostics)){- if (!profiles.TryAdd(pathProfile.Key, pathProfile.Value))- diagnostics.Add($"compose-profile-duplicate:{pathProfile.Key}");+ if (!semantic.Capabilities.Supports<ComposeOperandCapability>()) continue;+ var consumed = ProfileSemanticConsumer.RequireProfile(new(semantic, [], SemanticSourceSpan.Generated("Compose")), "Compose");+ if (!consumed.IsSuccess) { diagnostics.AddRange(consumed.Diagnostics.Select(item => item.Code + ":" + item.Message)); continue; }+ if (!profiles.TryAdd(consumed.Value!.Name, consumed.Value))+ diagnostics.Add($"compose-profile-duplicate:{consumed.Value.Name}");}var compose = ComposeHead.Match(source);diff --git a/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs b/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.csindex d83a4942..e6d4ae83 100644--- a/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs+++ b/Aetheris.Kernel.Firmament/Materializer/SemanticTopologySelections.cs@@ -1,6 +1,8 @@using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Topology;using System.Text.RegularExpressions;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Semantics;namespace Aetheris.Kernel.Firmament.Materializer;@@ -134,8 +136,16 @@ public static class SemanticSelectionSourceParserprivate static readonly Regex Require = new(@"\bRequire\s*:\s*(?<shape>ExactlyOne|OneOrMore|ConnectedChain|ClosedLoop|NonEmptyFaceSet)", RegexOptions.CultureInvariant);public static IReadOnlyList<SemanticSelectionRequest> Parse(string source, ResolvedProfile2D profile, string bodyStableId, out IReadOnlyList<string> diagnostics)+ {+ var span = SemanticSourceSpan.Generated("Selection");+ return Parse(source, new SemanticReference(FirmamentSemanticValues.FromProfile(profile, span), [], span), bodyStableId, out diagnostics);+ }++ public static IReadOnlyList<SemanticSelectionRequest> Parse(string source, SemanticReference semanticSource, string bodyStableId, out IReadOnlyList<string> diagnostics){var output = new List<SemanticSelectionRequest>(); var errors = new List<string>();+ var capability = SemanticValueValidator.Require<SelectableCapability>(semanticSource);+ if (capability is not null) { diagnostics = [capability.Code + ":" + capability.Message]; return []; }foreach (Match header in Header.Matches(source)){var body = Block(source, header.Index + header.Length - 1);diff --git a/Aetheris.Kernel.Firmament/Materializer/SemanticValueConsumers.cs b/Aetheris.Kernel.Firmament/Materializer/SemanticValueConsumers.csnew file mode 100644index 00000000..44d23b43--- /dev/null+++ b/Aetheris.Kernel.Firmament/Materializer/SemanticValueConsumers.cs@@ -0,0 +1,93 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Topology;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Semantics;++namespace Aetheris.Kernel.Firmament.Materializer;++public sealed record FirmamentTopologySelectionBinding(+ BrepBody Body,+ SemanticTopologyCorrespondence Correspondence,+ IReadOnlyList<string> SourceStableIds)+ : ExactSelectionBinding("selection-source:" + Correspondence.BodyStableId + ":" + string.Join(",", SourceStableIds.Order(StringComparer.Ordinal)));++public sealed record SemanticConsumerResult<T>(T? Value, IReadOnlyList<SemanticDiagnostic> Diagnostics) where T : class+{+ public bool IsSuccess => Value is not null && Diagnostics.Count == 0;+}++/// <summary>One profile contract shared by Profile, Compose, and admitted Modify consumers.</summary>+public static class ProfileSemanticConsumer+{+ public static SemanticConsumerResult<ResolvedProfile2D> RequireProfile(SemanticReference reference, string consumer)+ {+ var missing = SemanticValueValidator.Require<ProfileCapability>(reference);+ if (missing is not null) return new(null, [missing]);+ if (!reference.Value.TryBinding<ExactProfileBinding>(out var binding) || binding is not ResolvedProfileSemanticBinding firmament)+ return new(null, [new(SemanticValueValidator.NoExactBinding, $"{consumer} requires a validated ResolvedProfile2D binding.", reference.ConsumerSourceSpan)]);+ var validation = firmament.ValidateExactProfile();+ return validation.Count == 0+ ? new(firmament.Profile, [])+ : new(null, validation.Select(message => new SemanticDiagnostic(SemanticValueValidator.NoExactBinding, message, reference.ConsumerSourceSpan)).ToArray());+ }+}++public static class SemanticValueSelectionConsumer+{+ public static SemanticSelectionResolution Resolve(+ SemanticReference reference,+ string label,+ SemanticTopologyRole? role,+ SemanticSelectionRequirement requirement)+ {+ var request = new SemanticSelectionRequest("selection:" + label, label, BodyId(reference.Value), [reference.Value.StableIdentity], role, requirement,+ $"{reference.ConsumerSourceSpan.Source}:{reference.ConsumerSourceSpan.Start}", "SemanticValue");+ var missing = SemanticValueValidator.Require<SelectableCapability>(reference);+ if (missing is not null) return Failure(request, SemanticSelectionFailure.SelectionConsumerMismatch, missing);+ if (reference.Value.TryBinding<FirmamentTopologySelectionBinding>(out var topology))+ {+ request = request with { BodyStableId = topology.Correspondence.BodyStableId, SourceStableIds = topology.SourceStableIds };+ return SemanticTopologySelectionResolver.Resolve(topology.Body, topology.Correspondence, request);+ }+ if (reference.Value.TryBinding<ExactBrepFaceBinding>(out var face))+ return ExactFaces(request, face.Body, [face.Face]);+ if (reference.Value.TryBinding<ExactBrepRegionBinding>(out var region))+ return ExactFaces(request, region.Body, region.Faces);+ return Failure(request, SemanticSelectionFailure.SelectionConsumerMismatch,+ new(SemanticValueValidator.NoExactBinding, $"Selectable value '{reference.Value.StableIdentity}' has no exact selection binding.", reference.ConsumerSourceSpan));+ }++ private static SemanticSelectionResolution ExactFaces(SemanticSelectionRequest request, BrepBody body, IReadOnlyList<FaceId> faces)+ {+ if (request.Require is not (SemanticSelectionRequirement.ExactlyOne or SemanticSelectionRequirement.OneOrMore or SemanticSelectionRequirement.NonEmptyFaceSet))+ return Failure(request, SemanticSelectionFailure.SelectionConsumerMismatch,+ new(SemanticValueValidator.MissingCapability, "An exact face region does not prove an edge chain or loop contract."));+ if (request.Require == SemanticSelectionRequirement.ExactlyOne && faces.Count != 1)+ return Failure(request, SemanticSelectionFailure.SelectionCardinalityMismatch,+ new("semantic-selection-cardinality-mismatch", $"Expected one face; found {faces.Count}."));+ var descendants = faces.OrderBy(face => face.Value).Select(face => new SemanticTopologyDescendant(+ $"semantic-face:{face.Value}", "Face", SemanticTopologyRole.Unknown, request.SourceStableIds.Single(), Face: face)).ToArray();+ return new(true, SemanticSelectionFailure.None, request, descendants, [], false, false, []);+ }++ private static string BodyId(SemanticValue value) => value.TryBinding<ExactBrepBodyBinding>(out var body) ? body.BodyStableId+ : value.TryBinding<ExactBrepFaceBinding>(out var face) ? face.Body.Topology.Bodies.Single().Id.Value.ToString()+ : value.TryBinding<ExactBrepRegionBinding>(out var region) ? region.Body.Topology.Bodies.Single().Id.Value.ToString()+ : value.StableIdentity;++ private static SemanticSelectionResolution Failure(SemanticSelectionRequest request, SemanticSelectionFailure failure, SemanticDiagnostic diagnostic) =>+ new(false, failure, request, [], [], false, false,+ [new(diagnostic.Code, diagnostic.Message, request.SourceSpan, [])]);+}++public static class ModifySemanticConsumer+{+ public static SemanticDiagnostic? Admit(SemanticReference reference)+ {+ var missing = SemanticValueValidator.Require<ModifyTargetCapability>(reference);+ if (missing is not null) return missing;+ return reference.Value.Bindings.Any(binding => binding is ExactBrepBodyBinding or ExactBrepFaceBinding or ExactBrepRegionBinding or ExactProfileBinding)+ ? null+ : new(SemanticValueValidator.NoExactBinding, "Modify requires an exact body, face/region, or validated profile binding.", reference.ConsumerSourceSpan);+ }+}diff --git a/Aetheris.Semantics.Tests/Aetheris.Semantics.Tests.csproj b/Aetheris.Semantics.Tests/Aetheris.Semantics.Tests.csprojnew file mode 100644index 00000000..305539ed--- /dev/null+++ b/Aetheris.Semantics.Tests/Aetheris.Semantics.Tests.csproj@@ -0,0 +1,19 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <TargetFramework>net10.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ <IsPackable>false</IsPackable>+ </PropertyGroup>+ <ItemGroup>+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />+ <PackageReference Include="xunit" Version="2.9.2" />+ <PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />+ <ProjectReference Include="..\Aetheris.Semantics\Aetheris.Semantics.csproj" />+ <ProjectReference Include="..\Aetheris.Kernel.Firmament\Aetheris.Kernel.Firmament.csproj" />+ <ProjectReference Include="..\Aetheris.Forge\Aetheris.Forge.csproj" />+ <ProjectReference Include="..\Aetheris.Forge.SampleExtension\Aetheris.Forge.SampleExtension.csproj" />+ <ProjectReference Include="..\Aetheris.FEA\Aetheris.FEA.csproj" />+ </ItemGroup>+ <ItemGroup><Using Include="Xunit" /></ItemGroup>+</Project>diff --git a/Aetheris.Semantics.Tests/SemanticValueM1Tests.cs b/Aetheris.Semantics.Tests/SemanticValueM1Tests.csnew file mode 100644index 00000000..20dbec1e--- /dev/null+++ b/Aetheris.Semantics.Tests/SemanticValueM1Tests.cs@@ -0,0 +1,151 @@+using Aetheris.Forge.Extensions;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Materializer;+using Aetheris.Semantics;+using Aetheris.FEA.Analysis;+using MyCompany.SecretGeometry;++namespace Aetheris.Semantics.Tests;++public sealed class SemanticValueM1Tests+{+ private static readonly SemanticSourceSpan Span = new("fixture.firmament", 10, 4);++ [Fact]+ public void ConceptPath_NormalizesToDeterministicProfileCapableSemanticValue()+ {+ const string source = """+ Concept Path Outline {+ Start: Point2(0mm, 0mm)+ Heading: 0deg+ Line Bottom { Length: 10mm }+ Line Right { Turn: 90deg Length: 5mm }+ Line Top { Turn: 90deg Length: 10mm }+ Close Left+ }+ Profile Plate From Outline+ Extrude Solid { Profile: Plate From: 0mm To: 2mm }+ """;+ var first = Assert.Single(FirmamentSemanticValues.FromProfilesAndConceptPaths(source));+ var second = Assert.Single(FirmamentSemanticValues.FromProfilesAndConceptPaths(source));++ Assert.Equal(first.StableIdentity, second.StableIdentity);+ Assert.True(first.Capabilities.Supports<ProfileCapability>());+ Assert.True(first.Capabilities.Supports<ComposeOperandCapability>());+ Assert.Empty(SemanticValueValidator.Validate(first));+ var consumed = ProfileSemanticConsumer.RequireProfile(new(first, [], Span), "Compose");+ Assert.True(consumed.IsSuccess, string.Join("; ", consumed.Diagnostics.Select(item => item.Message)));+ }++ [Fact]+ public void ScalarPassedToProfileConsumerGetsCapabilityDiagnostic()+ {+ var scalar = new SemanticValue("scalar:1", new("Length"));+ var result = ProfileSemanticConsumer.RequireProfile(new(scalar, [], Span), "Profile");+ Assert.Equal(SemanticValueValidator.MissingCapability, Assert.Single(result.Diagnostics).Code);+ }++ [Fact]+ public void ClaimedProfileWithoutExactBindingIsRejected()+ {+ var falseClaim = new SemanticValue("bad:profile", new("Profile2D"), [new ProfileCapability()]);+ var diagnostic = Assert.Single(SemanticValueValidator.Validate(falseClaim));+ Assert.Equal(SemanticValueValidator.NoExactBinding, diagnostic.Code);+ }++ [Fact]+ public void BodyPassedToBoundaryConsumerGetsCapabilityDiagnostic()+ {+ var body = new SemanticValue("body:analytic", new("Body"));+ var diagnostic = SemanticValueValidator.Require<BoundaryRegionCapability>(new(body, [], Span));+ Assert.Equal(SemanticValueValidator.MissingCapability, diagnostic!.Code);+ }++ [Fact]+ public void MissingPrivateAndRawTopologyMembersUseSegmentSpan()+ {+ var root = new SemanticValue("root", new("Struct"), exposedMembers:+ [new SemanticValue("root.public", new("Point2"), exposedName: "Public")]);+ var reference = new SemanticReference(root, [], Span);+ var segmentSpan = new SemanticSourceSpan("fixture.firmament", 42, 7);++ Assert.False(SemanticValueValidator.TryResolveMember(reference, new("Private", segmentSpan), out _, out var privateDiagnostic));+ Assert.Equal(SemanticValueValidator.PathMemberMissing, privateDiagnostic!.Code);+ Assert.Equal(segmentSpan, privateDiagnostic.SourceSpan);+ Assert.False(SemanticValueValidator.TryResolveMember(reference, new("Face37", segmentSpan), out _, out var rawDiagnostic));+ Assert.Equal(SemanticValueValidator.PathMemberMissing, rawDiagnostic!.Code);+ }++ [Fact]+ public void MeshIdCannotMasqueradeAsAnalysisRegion()+ {+ var meshElement = new SemanticValue("mesh:element:7", new("MeshElement"));+ var diagnostic = SemanticValueValidator.Require<BoundaryRegionCapability>(new(meshElement, [], Span));+ Assert.Equal(SemanticValueValidator.MissingCapability, diagnostic!.Code);+ }++ [Fact]+ public void StableIdentityCollisionsAreRejected()+ {+ var root = new SemanticValue("root", new("Struct"), exposedMembers:+ [+ new SemanticValue("duplicate", new("Point2"), exposedName: "A"),+ new SemanticValue("duplicate", new("Point2"), exposedName: "B"),+ ]);+ Assert.Contains(SemanticValueValidator.Validate(root), diagnostic => diagnostic.Code == "semantic-value-stable-identity-collision");+ }++ [Fact]+ public void ForgeFalseProfileClaimIsRejectedByOrdinarySemanticValidation()+ {+ var registry = new ForgeExtensionRegistry();+ registry.RegisterExtension(new InvalidSemanticExtension());+ var result = ForgeCapabilityExecutor.Execute(registry, InvalidSemanticCapability.Id,+ new("invocation", "source", "template", new HashSet<ForgeLoweringTarget>()), new(new Dictionary<string, ForgeCapabilityValue>()));+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == SemanticValueValidator.ForgeOutputInvalid);+ }++ [Fact]+ public void ForgeSemanticMemberUsesOrdinaryPathSelectionAndFeaConsumers()+ {+ var registry = new ForgeExtensionRegistry();registry.RegisterExtension(new SecretGeometryExtension());+ var arguments = new ForgeCapabilityArguments(new Dictionary<string, ForgeCapabilityValue>+ {+ ["Width"] = new(ForgeCapabilityParameterType.Length, 24d, "24mm"),+ ["Depth"] = new(ForgeCapabilityParameterType.Length, 16d, "16mm"),+ ["Height"] = new(ForgeCapabilityParameterType.Length, 6d, "6mm"),+ });+ var execution=ForgeCapabilityExecutor.Execute(registry,SecretCouponCapability.CapabilityId,+ new("Coupon","fixture.firmament","template:coupon",new HashSet<ForgeLoweringTarget>{ForgeLoweringTarget.Brep}),arguments);+ Assert.True(execution.IsSuccess,string.Join("; ",execution.Diagnostics.Select(item=>item.Message)));+ var root=execution.Output!.SemanticRoot!;var rootRef=new SemanticReference(root,[],Span);+ Assert.True(SemanticValueValidator.TryResolveMember(rootRef,new("TopFace",Span),out var topFace,out var pathDiagnostic),pathDiagnostic?.Message);++ var selection=SemanticValueSelectionConsumer.Resolve(topFace!,"ForgeTop",null,SemanticSelectionRequirement.ExactlyOne);+ Assert.True(selection.Succeeded,string.Join("; ",selection.Diagnostics.Select(item=>item.Message)));+ var analysis=AnalysisSemanticRegionNormalizer.Normalize(topFace!);+ Assert.Null(analysis.Diagnostic);+ Assert.Equal("ExactBrepFace",analysis.Region!.ExactBindingKind);+ Assert.StartsWith("forge:",analysis.Region.SemanticStableId,StringComparison.Ordinal);+ }++ private sealed class InvalidSemanticExtension : IForgeExtension+ {+ public string Id => "tests.invalid-semantic";+ public Version Version => new(1, 0, 0);+ public void Register(ForgeExtensionRegistry registry) => registry.RegisterCapability(new InvalidSemanticCapability());+ }++ private sealed class InvalidSemanticCapability : IForgeCapability+ {+ public static readonly ForgeCapabilityId Id = new("tests.invalid-semantic.profile");+ public ForgeCapabilityDescriptorV1 Descriptor { get; } = new(Id, new(1, 0, 0), "tests.invalid-semantic", new(1, 0, 0),+ "negative fixture", [], ForgeOutputClassification.SemanticOnly, new HashSet<ForgeLoweringTarget>(), ForgeCapabilityDeterminism.Deterministic,+ "none", "bounded negative test", "tests.invalid-semantic/profile/v1");+ public ForgeCapabilityExecutionResult Execute(ForgeCapabilityInvocationContext context, ForgeCapabilityArguments arguments) =>+ ForgeCapabilityExecutionResult.Success(new(null, Provenance: new Dictionary<string, string> { ["capability"] = Id.Value },+ SemanticRoot: new SemanticValue("forge:invalid", new("Profile2D"), [new ProfileCapability()],+ provenance: [new("forge-capability", Id.Value + "@1.0.0", "[email protected]")])));+ }+}diff --git a/Aetheris.Semantics/Aetheris.Semantics.csproj b/Aetheris.Semantics/Aetheris.Semantics.csprojnew file mode 100644index 00000000..77fdc68a--- /dev/null+++ b/Aetheris.Semantics/Aetheris.Semantics.csproj@@ -0,0 +1,10 @@+<Project Sdk="Microsoft.NET.Sdk">+ <PropertyGroup>+ <TargetFramework>net10.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ </PropertyGroup>+ <ItemGroup>+ <ProjectReference Include="..\Aetheris.Kernel.Core\Aetheris.Kernel.Core.csproj" />+ </ItemGroup>+</Project>diff --git a/Aetheris.Semantics/SemanticModel.cs b/Aetheris.Semantics/SemanticModel.csnew file mode 100644index 00000000..5b03f30b--- /dev/null+++ b/Aetheris.Semantics/SemanticModel.cs@@ -0,0 +1,232 @@+using System.Collections.ObjectModel;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Semantics;++/// <summary>Authored or generated compiler location. Offsets are zero-based.</summary>+public sealed record SemanticSourceSpan(string Source, int Start, int Length)+{+ public static SemanticSourceSpan Generated(string source) => new(source, 0, 0);+}++/// <summary>One acyclic, ordered step in the history of a semantic value.</summary>+public sealed record SemanticProvenance(string Stage, string Identity, string Evidence, SemanticSourceSpan? SourceSpan = null);++public sealed record SemanticType(string Name, bool IsCollection = false)+{+ public override string ToString() => Name + (IsCollection ? "[]" : string.Empty);+}++// Capabilities are structural contracts, rather than one exclusive kind enum.+public interface ISemanticCapability { string Name { get; } }+public sealed record ProfileCapability : ISemanticCapability { public string Name => "ProfileCapable"; }+public sealed record SelectableCapability : ISemanticCapability { public string Name => "Selectable"; }+public sealed record ExactGeometryCapability : ISemanticCapability { public string Name => "ExactGeometryCapable"; }+public sealed record BoundaryRegionCapability : ISemanticCapability { public string Name => "BoundaryRegionCapable"; }+public sealed record ModifyTargetCapability : ISemanticCapability { public string Name => "ModifyTargetCapable"; }+public sealed record ComposeOperandCapability : ISemanticCapability { public string Name => "ComposeOperandCapable"; }+public sealed record BodyCapability : ISemanticCapability { public string Name => "BodyCapable"; }+public sealed record MaterialRegionCapability : ISemanticCapability { public string Name => "MaterialRegionCapable"; }+public sealed record AnalysisRegionCapability : ISemanticCapability { public string Name => "AnalysisRegionCapable"; }++public sealed class SemanticCapabilitySet+{+ private readonly IReadOnlyDictionary<Type, ISemanticCapability> values;+ public SemanticCapabilitySet(IEnumerable<ISemanticCapability>? capabilities = null)+ {+ values = new ReadOnlyDictionary<Type, ISemanticCapability>((capabilities ?? [])+ .GroupBy(capability => capability.GetType())+ .ToDictionary(group => group.Key, group => group.Single()));+ }+ public IReadOnlyList<ISemanticCapability> Values => values.Values.OrderBy(value => value.Name, StringComparer.Ordinal).ToArray();+ public bool Supports<T>() where T : class, ISemanticCapability => values.ContainsKey(typeof(T));+ public bool Supports(Type capabilityType) => values.ContainsKey(capabilityType);+}++/// <summary>A bounded exact downstream representation. It is not a service locator.</summary>+public abstract record SemanticBinding(string Kind, string StableBindingIdentity);++public sealed record ExactBrepBodyBinding(BrepBody Body, string BodyStableId)+ : SemanticBinding("ExactBrepBody", BodyStableId);++public sealed record ExactBrepFaceBinding(BrepBody Body, FaceId Face, string RegionStableId)+ : SemanticBinding("ExactBrepFace", RegionStableId);++public sealed record ExactBrepRegionBinding(BrepBody Body, IReadOnlyList<FaceId> Faces, string RegionStableId)+ : SemanticBinding("ExactBrepRegion", RegionStableId);++/// <summary>Implemented by a producer that owns an exact, validated profile representation.</summary>+public abstract record ExactProfileBinding(string ProfileStableId)+ : SemanticBinding("ResolvedProfile2D", ProfileStableId)+{+ public abstract IReadOnlyList<string> ValidateExactProfile();+}++/// <summary>Source-grounded selection evidence; implementations remain producer-owned.</summary>+public abstract record ExactSelectionBinding(string SelectionStableId)+ : SemanticBinding("ExactSelection", SelectionStableId);++public sealed record ConstructionIdentityBinding(string ConstructionStableId)+ : SemanticBinding("ConstructionIdentity", ConstructionStableId);++public sealed record ImportedEntityBinding(string ResourceIdentity, IReadOnlyList<string> EntityIds)+ : SemanticBinding("ImportedEntities", ResourceIdentity + ":" + string.Join(",", EntityIds.Order(StringComparer.Ordinal)));++/// <summary>Exact analytic/BRep boundary identity normalized before AnalysisIR; never a mesh identifier.</summary>+public sealed record ExactAnalysisRegionBinding(string BodyStableId, string RegionPath, string? ExactBrepFaceId = null)+ : SemanticBinding("ExactAnalysisRegion", BodyStableId + ":" + RegionPath + ":" + (ExactBrepFaceId ?? "analytic"));++public sealed class SemanticValue+{+ private readonly IReadOnlyDictionary<string, SemanticValue> members;+ private readonly IReadOnlyDictionary<Type, SemanticBinding> bindings;++ public SemanticValue(+ string stableIdentity,+ SemanticType type,+ IEnumerable<ISemanticCapability>? capabilities = null,+ IEnumerable<SemanticBinding>? bindings = null,+ IEnumerable<SemanticValue>? exposedMembers = null,+ IEnumerable<SemanticProvenance>? provenance = null,+ SemanticSourceSpan? authoredSourceSpan = null,+ SemanticSourceSpan? generatedSourceSpan = null,+ string? exposedName = null)+ {+ if (string.IsNullOrWhiteSpace(stableIdentity)) throw new ArgumentException("Stable semantic identity is required.", nameof(stableIdentity));+ StableIdentity = stableIdentity;+ Type = type ?? throw new ArgumentNullException(nameof(type));+ Capabilities = new SemanticCapabilitySet(capabilities);+ this.bindings = new ReadOnlyDictionary<Type, SemanticBinding>((bindings ?? [])+ .GroupBy(binding => binding.GetType())+ .ToDictionary(group => group.Key, group => group.Single()));+ this.members = new ReadOnlyDictionary<string, SemanticValue>((exposedMembers ?? [])+ .ToDictionary(member => member.ExposedName ?? throw new ArgumentException("An exposed member requires ExposedName."), StringComparer.Ordinal));+ Provenance = (provenance ?? []).ToArray();+ AuthoredSourceSpan = authoredSourceSpan;+ GeneratedSourceSpan = generatedSourceSpan;+ ExposedName = exposedName;+ }++ public string StableIdentity { get; }+ public SemanticType Type { get; }+ public SemanticCapabilitySet Capabilities { get; }+ public IReadOnlyList<SemanticBinding> Bindings => bindings.Values.OrderBy(binding => binding.Kind, StringComparer.Ordinal).ToArray();+ public IReadOnlyDictionary<string, SemanticValue> ExposedMembers => members;+ public IReadOnlyList<SemanticProvenance> Provenance { get; }+ public SemanticSourceSpan? AuthoredSourceSpan { get; }+ public SemanticSourceSpan? GeneratedSourceSpan { get; }+ public string? ExposedName { get; }+ public bool TryBinding<T>(out T binding) where T : SemanticBinding+ {+ if (bindings.TryGetValue(typeof(T), out var value)) { binding = (T)value; return true; }+ var assignable = bindings.Values.OfType<T>().FirstOrDefault();+ if (assignable is not null) { binding = assignable; return true; }+ binding = null!; return false;+ }+}++public sealed record SemanticPathSegment(string Name, SemanticSourceSpan SourceSpan);++/// <summary>Resolution context for one stable value. Path syntax never becomes a string lookup API.</summary>+public sealed record SemanticReference(+ SemanticValue Value,+ IReadOnlyList<SemanticPathSegment> ResolvedSegments,+ SemanticSourceSpan ConsumerSourceSpan);++public sealed record SemanticDiagnostic(string Code, string Message, SemanticSourceSpan? SourceSpan = null);++public static class SemanticValueValidator+{+ public const string MissingCapability = "semantic-value-missing-capability";+ public const string NoExactBinding = "semantic-value-no-exact-binding";+ public const string PathMemberMissing = "semantic-path-member-missing";+ public const string PathMemberNotExposed = "semantic-path-member-not-exposed";+ public const string ForgeOutputInvalid = "forge-semantic-output-invalid";++ public static IReadOnlyList<SemanticDiagnostic> Validate(SemanticValue root)+ {+ var diagnostics = new List<SemanticDiagnostic>();+ var identities = new HashSet<string>(StringComparer.Ordinal);+ Visit(root, diagnostics, identities);+ return diagnostics;+ }++ public static SemanticDiagnostic? Require<T>(SemanticReference reference) where T : class, ISemanticCapability =>+ reference.Value.Capabilities.Supports<T>() ? null : new(MissingCapability,+ $"Semantic value '{reference.Value.StableIdentity}' of type '{reference.Value.Type}' lacks {newCapabilityName<T>()}.", reference.ConsumerSourceSpan);++ public static bool TryResolveMember(SemanticReference parent, SemanticPathSegment segment, out SemanticReference? resolved, out SemanticDiagnostic? diagnostic)+ {+ if (!parent.Value.ExposedMembers.TryGetValue(segment.Name, out var member))+ {+ resolved = null;+ diagnostic = new(PathMemberMissing, $"'{parent.Value.StableIdentity}' exists, but does not expose '{segment.Name}'.", segment.SourceSpan);+ return false;+ }+ resolved = new(member, [.. parent.ResolvedSegments, segment], parent.ConsumerSourceSpan);+ diagnostic = null;+ return true;+ }++ private static void Visit(SemanticValue value, List<SemanticDiagnostic> diagnostics, HashSet<string> identities)+ {+ if (!identities.Add(value.StableIdentity))+ diagnostics.Add(new("semantic-value-stable-identity-collision", $"Stable semantic identity '{value.StableIdentity}' occurs more than once.", value.AuthoredSourceSpan));+ RequireBinding<ProfileCapability, ExactProfileBinding>(value, diagnostics);+ if (value.Capabilities.Supports<BoundaryRegionCapability>()+ && !value.TryBinding<ExactBrepFaceBinding>(out _)+ && !value.TryBinding<ExactBrepRegionBinding>(out _)+ && !value.TryBinding<ExactAnalysisRegionBinding>(out _))+ diagnostics.Add(new(NoExactBinding, $"BoundaryRegionCapable on '{value.StableIdentity}' requires an exact BRep face or region binding.", value.AuthoredSourceSpan));+ RequireBinding<BodyCapability, ExactBrepBodyBinding>(value, diagnostics);+ RequireAnyExactBinding<ExactGeometryCapability>(value, diagnostics);+ RequireAnyExactBinding<SelectableCapability>(value, diagnostics);+ RequireBinding<ComposeOperandCapability, ExactProfileBinding>(value, diagnostics);+ RequireAnyExactBinding<ModifyTargetCapability>(value, diagnostics);+ if (value.TryBinding<ExactProfileBinding>(out var profile))+ diagnostics.AddRange(profile.ValidateExactProfile().Select(message => new SemanticDiagnostic(NoExactBinding, message, value.AuthoredSourceSpan)));+ foreach (var member in value.ExposedMembers.OrderBy(pair => pair.Key, StringComparer.Ordinal)) Visit(member.Value, diagnostics, identities);+ }++ private static void RequireBinding<TCapability, TBinding>(SemanticValue value, List<SemanticDiagnostic> diagnostics)+ where TCapability : class, ISemanticCapability where TBinding : SemanticBinding+ {+ if (value.Capabilities.Supports<TCapability>() && !value.TryBinding<TBinding>(out _))+ diagnostics.Add(new(NoExactBinding, $"{newCapabilityName<TCapability>()} on '{value.StableIdentity}' requires {typeof(TBinding).Name}.", value.AuthoredSourceSpan));+ }++ private static void RequireAnyExactBinding<TCapability>(SemanticValue value, List<SemanticDiagnostic> diagnostics)+ where TCapability : class, ISemanticCapability+ {+ if (!value.Capabilities.Supports<TCapability>()) return;+ if (!value.Bindings.Any(binding => binding is ExactProfileBinding or ExactBrepBodyBinding or ExactBrepFaceBinding or ExactBrepRegionBinding or ExactSelectionBinding or ExactAnalysisRegionBinding))+ diagnostics.Add(new(NoExactBinding, $"{newCapabilityName<TCapability>()} on '{value.StableIdentity}' requires exact producer evidence.", value.AuthoredSourceSpan));+ }++ private static string newCapabilityName<T>() where T : class, ISemanticCapability =>+ ((ISemanticCapability)Activator.CreateInstance(typeof(T))!).Name;+}++public sealed record SemanticValueDescriptor(+ string StableId,+ string? Name,+ string SemanticType,+ IReadOnlyList<string> Capabilities,+ IReadOnlyList<string> BindingKinds,+ IReadOnlyList<SemanticValueDescriptor> Members,+ IReadOnlyList<SemanticProvenance> Provenance,+ SemanticSourceSpan? AuthoredSourceSpan,+ SemanticSourceSpan? GeneratedSourceSpan)+{+ public static SemanticValueDescriptor From(SemanticValue value) => new(+ value.StableIdentity,+ value.ExposedName,+ value.Type.ToString(),+ value.Capabilities.Values.Select(capability => capability.Name).ToArray(),+ value.Bindings.Select(binding => binding.Kind).ToArray(),+ value.ExposedMembers.OrderBy(pair => pair.Key, StringComparer.Ordinal).Select(pair => From(pair.Value)).ToArray(),+ value.Provenance,+ value.AuthoredSourceSpan,+ value.GeneratedSourceSpan);+}diff --git a/Aetheris.slnx b/Aetheris.slnxindex 291cc3b7..e5a3a940 100644--- a/Aetheris.slnx+++ b/Aetheris.slnx@@ -2,6 +2,8 @@<Project Path="Aetheris.Server/Aetheris.Server.csproj" /><Project Path="Aetheris.Server.Tests/Aetheris.Server.Tests.csproj" /><Project Path="Aetheris.Kernel.Core/Aetheris.Kernel.Core.csproj" />+ <Project Path="Aetheris.Semantics/Aetheris.Semantics.csproj" />+ <Project Path="Aetheris.Semantics.Tests/Aetheris.Semantics.Tests.csproj" /><Project Path="Aetheris.Continuum/Aetheris.Continuum.csproj" /><Project Path="Aetheris.FEA/Aetheris.FEA.csproj" /><Project Path="Aetheris.FEA.Tests/Aetheris.FEA.Tests.csproj" />diff --git a/docs/fea/firmament-analysis.md b/docs/fea/firmament-analysis.mdindex 98e213b0..eff8d76d 100644--- a/docs/fea/firmament-analysis.md+++ b/docs/fea/firmament-analysis.md@@ -1,5 +1,12 @@# Firmament linear-elastic analysis+> Semantic Value M1: boundary syntax is structurally bound to a+> `BoundaryRegionCapability` value and normalized to `SemanticRegionBinding`+> before AnalysisIR. Native analytic faces, canonical InlineStep faces, and+> exposed Recognize/Forge faces use the same normalizer. AnalysisIR retains+> stable ID, capability/binding evidence, and provenance; solver/mesh code does+> not receive the compiler semantic object or mesh IDs.+The M5 analysis block is declarative and erases to AnalysisIR before mechanics execution:```firmamentdiff --git a/docs/firmament/v2-canonical-safety-and-labeling-x4.md b/docs/firmament/v2-canonical-safety-and-labeling-x4.mdindex 39ecaa4f..88bc71e0 100644--- a/docs/firmament/v2-canonical-safety-and-labeling-x4.md+++ b/docs/firmament/v2-canonical-safety-and-labeling-x4.md@@ -1,5 +1,10 @@# CANONICAL-SAFETY-AND-LABELING-X4+> Semantic Value M1 preserves a successful canonical `Recognize` region as an+> exposed `SemanticValue` member. Its existing STEP entity/FaceId association is+> the proof for boundary, selection, exact-geometry, and analysis capabilities.+> Recognition metadata alone never creates a profile capability or new geometry.+Round 2 found two frontend integrity faults: canonical Counterbore/Countersinkfields were omitted before lowering and an unknown `Hole<Variant>` could beignored. Canonical Hole headers now bind any candidate identifier and rejectdiff --git a/docs/firmament/v2-concept-path.md b/docs/firmament/v2-concept-path.mdindex c1f63753..bd8b00b4 100644--- a/docs/firmament/v2-concept-path.md+++ b/docs/firmament/v2-concept-path.md@@ -1,5 +1,12 @@# Firmament V2 Concept Path (M1)+> Preview 2 Semantic Value M1: Concept Path is a producer of+> `SemanticValue`. A path used by a named Profile carries `ProfileCapability`,+> `ComposeOperandCapability`, and an exact validated `ResolvedProfile2D`+> binding. Guides and endpoints are typed exposed members. Compose consumes the+> common profile contract; no path-specific backend exists. See+> `docs/semantic/architecture.md`.+`Concept Path` is the concise frontend for an ordered, contiguous local-2D chain of line and tangent-arc guides. It lowers to the same named points, guides, ordinary `Profile` loops, and `ResolvedProfile2D` route as `Rect2`, `Line2`, `Circle2`, and explicit `Segment` declarations.It is a **Path**, not a Profile Loop: a Path may be open and has no opinion about closure, winding, material boundaries, or intersections. Those checks remain with `Profile`.diff --git a/docs/forge/artifacts/m1/performance.json b/docs/forge/artifacts/m1/performance.jsonindex 6cd3b291..2fcdb633 100644--- a/docs/forge/artifacts/m1/performance.json+++ b/docs/forge/artifacts/m1/performance.json@@ -1,18 +1,18 @@{"units": "milliseconds","first": {- "registration": 4.5488,- "capabilityResolution": 0.0795,- "templateInvocation": 37.5553,- "extensionLowering": 6.6124,- "compilerAndValidation": 201.7962+ "registration": 4.6145,+ "capabilityResolution": 0.0847,+ "templateInvocation": 38.8736,+ "extensionLowering": 6.9278,+ "compilerAndValidation": 213.69},"warm": {- "registration": 4.5488,- "capabilityResolution": 0.0017,- "templateInvocation": 0.4954,- "extensionLowering": 0.0333,- "compilerAndValidation": 1.2135+ "registration": 4.6145,+ "capabilityResolution": 0.0025,+ "templateInvocation": 0.5599,+ "extensionLowering": 0.0405,+ "compilerAndValidation": 1.3867},"note": "Developer-machine wall-clock evidence; not a benchmark or release gate."}diff --git a/docs/forge/extension-sdk.md b/docs/forge/extension-sdk.mdindex ae4762eb..f21d867a 100644--- a/docs/forge/extension-sdk.md+++ b/docs/forge/extension-sdk.md@@ -1,5 +1,12 @@# Forge extension SDK+> Semantic Value M1: `ForgeCapabilityOutput.SemanticRoot` may expose a+> compiler-owned typed semantic tree. Claims are validated against exact+> profile/BRep/analysis bindings, BRep associations, deterministic identities,+> and extension/capability/version provenance. Arbitrary extension objects are+> not accepted. ForgeHost exposes `SemanticValueDescriptor`, not kernel+> internals or a permanent interchange schema.+Extension packages implement `IForgeExtension` and register immutable `IForgeCapability` instances explicitly with `ForgeExtensionRegistry`.```csharpdiff --git a/docs/preview2/consolidation-gap-inventory.md b/docs/preview2/consolidation-gap-inventory.mdindex 06ba1ac0..94878652 100644--- a/docs/preview2/consolidation-gap-inventory.md+++ b/docs/preview2/consolidation-gap-inventory.md@@ -17,6 +17,9 @@ manifest (`docs/preview2/feature-manifest.json`).| Stale Preview 1 guard/fixture | Invalid fixture promoted to valid; capability manifest and roadmap updated. || CIR/FRep authority wording | Historical roadmap marked superseded and linked to settled architecture. || SurfaceMeshIR M1-era status | Current M2-M7 capability progression called out explicitly. |+| Typed semantic reference shared by Selection/FEA/Recognize | Closed by `Aetheris.Semantics`; consumers require structural capabilities and exact bindings. |+| Exact recognized-region metadata in common binder | Closed for existing Recognize families; canonical STEP entity/FaceId association is preserved. |+| Forge semantic output/exposure contract | Closed for validated compiler-owned roots/members; sample proves Selection and FEA. |## Still Experimental@@ -38,9 +41,6 @@ manifest (`docs/preview2/feature-manifest.json`).## Deferred post-Preview2-- One typed semantic-reference/value layer spanning Concept IR exposure,- recognized imported regions, Forge outputs, Selection, Modify, and AnalysisIR.-- Profile-capable and boundary-region-capable semantic value kinds for that layer.- General imported exact-profile recognition (no new recognition was invented).- Curved FEA boundary constraints/loads, nonlinear mechanics, contact, dynamics,and higher-order recovery.@@ -52,12 +52,9 @@ manifest (`docs/preview2/feature-manifest.json`).| Rank | Gap | Friction | Risk | Cost | Evidence | Preview 2 relevance || ---: | --- | ---: | ---: | ---: | ---: | ---: |-| 1 | Typed semantic reference shared by Selection/FEA/Recognize | 5 | 5 | 5 | 3 | 5 |-| 2 | Preserve exact recognized-region capability metadata in common binder | 5 | 4 | 4 | 3 | 5 |-| 3 | Compose/Profile source-span modernization | 3 | 3 | 3 | 4 | 4 |-| 4 | Forge semantic output/exposure contract | 4 | 4 | 5 | 2 | 4 |-| 5 | Curved-trim certified volume for mixed Fillet | 3 | 4 | 5 | 5 | 3 |-| 6 | Forge production source generator | 2 | 2 | 3 | 3 | 2 |+| 1 | Compose/Profile parser-wide source-span modernization beyond semantic references | 3 | 3 | 3 | 4 | 4 |+| 2 | Curved-trim certified volume for mixed Fillet | 3 | 4 | 5 | 5 | 3 |+| 3 | Forge production source generator | 2 | 2 | 3 | 3 | 2 |Scores are ordinal 1-5. No competing runtime strategy is selected here, so aJudgmentEngine integration would add machinery without improving the audit.diff --git a/docs/preview2/feature-manifest.json b/docs/preview2/feature-manifest.jsonindex ae9a1121..28d41d87 100644--- a/docs/preview2/feature-manifest.json+++ b/docs/preview2/feature-manifest.json@@ -8,8 +8,8 @@{"id":"concept-path-profile-compose","status":"Supported","reason":"Path-derived Profiles use the ordinary Compose operand dictionary and exact section-stack path."},{"id":"concept-path-profile-selection","status":"Bounded","reason":"Named ProfileSegments/Loop selection is supported; selection is not arbitrary path traversal."},{"id":"template-record-table-path-compose","status":"Supported","reason":"Expansion precedes binding; fixture retains specialization and input provenance."},- {"id":"general-semantic-member-path","status":"Unsupported","reason":"No common typed semantic-reference value spans Concept IR, Recognize, Forge, Modify, and AnalysisIR."},- {"id":"inline-step-recognize-semantic-path","status":"Bounded","reason":"Recognize exposes exact face refs for replacement/inspection, not Profile-capable semantic values."},+ {"id":"general-semantic-member-path","status":"Bounded","reason":"Compiler-owned SemanticValue/SemanticReference spans Concept IR, Concept Path, Recognize, Forge, Selection, bounded Modify and FEA; only explicitly exposed members are navigable."},+ {"id":"inline-step-recognize-semantic-path","status":"Supported","reason":"Existing Recognize regions preserve canonical STEP/FaceId evidence and can enter structured member paths, Selection and FEA; no exact-profile recognition is implied."},{"id":"fea-linear-elasticity","status":"Supported","reason":"Native and canonical imported bounded domains, exact planar constraints, traction, force, and pressure work."},{"id":"fea-curved-nonlinear-contact-dynamics","status":"Unsupported","reason":"Curved weak constraints, nonlinear mechanics, contact, and dynamics are future formulations."},{"id":"surface-mesh-ir","status":"Bounded","reason":"Analytic supports, planar holes/bands, Hyperbola and sampled non-rational B-spline trims, STL and OBJ; no NURBS support surfaces."},@@ -17,6 +17,7 @@{"id":"arbitrary-representation-recovery","status":"Unsupported","reason":"Arbitrary BRep-to-CIR and CIR/SDF-to-exact-BRep are not assumed."},{"id":"forge-template-hosting","status":"Supported","reason":"Typed Template invocation, artifact validation, imported resources, and deterministic provenance."},{"id":"forge-construction-extension","status":"Bounded","reason":"Trusted explicitly registered capabilities, one construct output, bounded standard prism or validated ExactBrep."},+ {"id":"forge-semantic-output","status":"Supported","reason":"Capabilities may expose validated SemanticValue roots/members; SecretGeometry exact faces use ordinary path, Selection and FEA consumers."},{"id":"forge-general-assembly-loft-sourcegen","status":"Unsupported","reason":"Multi-body/general loft/nested host Record/source generator/plugin discovery are not production features."},{"id":"mixed-profile-whole-loop-fillet","status":"Experimental","reason":"Exact shell executes but curved-trim certified volume envelopes remain release-loose."}]diff --git a/docs/semantic/architecture.md b/docs/semantic/architecture.mdnew file mode 100644index 00000000..0045b5c4--- /dev/null+++ b/docs/semantic/architecture.md@@ -0,0 +1,49 @@+# Compiler semantic-value architecture++`Aetheris.Semantics` owns the bounded compiler model shared by Firmament,+Recognize, Forge, Selection, and FEA. It depends on Kernel.Core for exact BRep+binding types; Kernel.Core does not depend on it. This keeps semantic policy out+of the geometry kernel and avoids a Firmament/Forge dependency cycle.++`SemanticValue` is one meaningful typed entity. It has a deterministic stable+identity, `SemanticType`, structural capability objects, exact bindings, exposed+`SemanticValue` members, authored/generated spans, and an ordered acyclic+provenance chain. `SemanticReference` is resolution context: the value plus+structured path segments and the consumer span. Transient CLR object identity is+never semantic identity.++Capabilities are consumer contracts, not origin tags. `ProfileCapability`,+`BoundaryRegionCapability`, `SelectableCapability`, `ComposeOperandCapability`,+`ModifyTargetCapability`, `BodyCapability`, `ExactGeometryCapability`, and the+analysis/material region contracts may coexist. The validator proves claims:++- Profile and Compose require a producer-owned `ExactProfileBinding` whose+ validator accepts the exact profile.+- Boundary regions require an exact BRep face/region or exact analytic analysis+ region binding.+- Body requires `ExactBrepBodyBinding`.+- Selectable, Modify, and exact-geometry claims require bounded exact evidence.+- Forge additionally verifies that bound bodies/faces belong to its validated+ `ExactBrep` output and that capability/version provenance exists.++Bindings are a closed compiler vocabulary, not a service locator:+`ResolvedProfile2D`, exact BRep body/face/region, source-grounded topology+selection, exact analysis region, construction identity, and imported STEP+entities. A binding can carry a kernel representation; CLI/API inspection emits+only `SemanticValueDescriptor`, not kernel internals. That descriptor is debug+and tooling output, explicitly not a stable interchange schema.++Concept Path, native Concept IR/Struct, template expansion, Recognize, and Forge+are producers. Profile, Compose, Selection, admitted Modify operations, and FEA+are consumers. Consumer admission calls a capability contract and then retrieves+its exact binding. Origin remains provenance and is not a lowering dispatch key.++No dynamic reflection, arbitrary object walking, string `Resolve("A.B")`, raw+BRep topology navigation, or mesh/lattice identifiers are introduced. Member+resolution accepts parsed `SemanticPathSegment` objects only. Raw topology is+reachable only when a producer deliberately exposes a semantic member and binds+it exactly.++AnalysisIR is downstream of this model. `AnalysisSemanticRegionNormalizer`+erases a boundary-capable value to compact `SemanticRegionBinding` evidence;+solver and mesh code never depend on `SemanticValue`.diff --git a/docs/semantic/artifacts/m1/architecture-audit.md b/docs/semantic/artifacts/m1/architecture-audit.mdnew file mode 100644index 00000000..7b64b553--- /dev/null+++ b/docs/semantic/artifacts/m1/architecture-audit.md@@ -0,0 +1,17 @@+# Pre-change semantic identity audit++| Area | Identity/type before M1 | Capability/binding | Span/provenance | Duplicate adapter or gap |+| --- | --- | --- | --- | --- |+| Concept IR / Struct | `ConceptIrValue.StableId`, nominal value kind; struct dictionaries | compile-time value or semantic-reference category | struct/member spans; string provenance | no common consumer value |+| Concept Path | path/guide/endpoint strings | directly produced `ResolvedProfile2D` | segment provenance | path-specific inspection and profile adapter |+| Template / Table / Record | specialization hash plus generated declarations | ordinary generated syntax | invocation, record origin, with-derived text | output identity separated only informally |+| Recognize / InlineStep | body + region name, STEP entity refs, kind/confidence | topology map proves exact imported face | recognition metadata; declaration span not carried in value | FEA/Selection could not consume a common reference |+| Selection | request ID, source stable IDs, topology role | `SemanticTopologyCorrespondence` | source string plus chain | source syntax-specific parsing |+| Modify | target strings and operation-specific exact checks | bounded body/face/profile logic | operation reports | no reusable capability diagnostic |+| Forge | capability/version and construction identity | ConstructionIR/ExactBRep output classification | dictionary plus host evidence | no exposed semantic output contract |+| FEA / AnalysisIR | body + path and optional face ID | separate `SemanticRegionBinding` | `AnalysisProvenance` | origin-specific region binding |+| CLI | subsystem-specific JSON sections | capabilities only for Concept Path inspection | partial | no unified descriptor |+| Cadmata | stable entity IDs, descendants, selections | topology DTOs | source span/metadata | retained; no M1 redesign |++M1 replaces the highlighted common gap with `SemanticValue` and retains bounded+producer validation where it proves real origin-specific facts.diff --git a/docs/semantic/artifacts/m1/deterministic-hashes.md b/docs/semantic/artifacts/m1/deterministic-hashes.mdnew file mode 100644index 00000000..35999c9b--- /dev/null+++ b/docs/semantic/artifacts/m1/deterministic-hashes.md@@ -0,0 +1,12 @@+# Determinism and performance evidence++Canonical native and imported descriptor hashes and the Forge artifact hash are+listed in `stable-ids.md`. STEP/BRep and Forge CIR association determinism remain+covered by the existing Forge evidence suite.++Developer-machine whole-process envelopes (three warm `dotnet run/test` calls,+including process startup) were 738-780 ms for native inspection, 748-756 ms for+Recognize inspection, and 1015-1039 ms for the Forge path/Selection/FEA test.+Forge's existing in-process evidence reports warm capability resolution 0.0025+ms, template invocation 0.5599 ms, extension lowering 0.0405 ms, and compiler+validation 1.3867 ms. These are diagnostic measurements, not benchmarks or gates.diff --git a/docs/semantic/artifacts/m1/forge-proof.md b/docs/semantic/artifacts/m1/forge-proof.mdnew file mode 100644index 00000000..0d0bc342--- /dev/null+++ b/docs/semantic/artifacts/m1/forge-proof.md@@ -0,0 +1,11 @@+# Forge proof++The SecretGeometry capability emits exact prism BRep plus semantic body members+`TopFace` and `LoadRegion`. Each member has exact face binding and Forge+capability/version provenance. ForgeHost exposes a kernel-free descriptor.++`ForgeSemanticMemberUsesOrdinaryPathSelectionAndFeaConsumers` resolves+`TopFace` with `SemanticPathSegment`, then passes that same reference to ordinary+Selection and FEA normalization. No sample-specific consumer branch exists.+The host artifact hash is+`7282965B703FEB85478AC8B651B6F6255D3BC922D3B2A7EBE73726C611CB4D36`.diff --git a/docs/semantic/artifacts/m1/imported-proof.md b/docs/semantic/artifacts/m1/imported-proof.mdnew file mode 100644index 00000000..eb92d3ab--- /dev/null+++ b/docs/semantic/artifacts/m1/imported-proof.md@@ -0,0 +1,11 @@+# Imported proof++`aetheris inspect fixtures/FirmamentV2/Canonical/valid/inline-step-recognize-replace.firmament --json`+reports canonical resource hash+`d165ebf5f25490b31b9c8fcdc59a4f49c6e78c4a9bf6ba9584ef35666bb42aaf`,+imported body `Source`, and exposed `MountHole` with exact BRep face,+`BoundaryRegionCapable`, `Selectable`, and `AnalysisRegionCapable`.++`InlineStepRecognizeMemberPath_NormalizesToBoundarySemanticValueBeforeAnalysisIr`+compiles `imported.MountFace`; AnalysisIR contains the recognized stable ID,+`ExactBrepFace`, capability evidence, and a non-null exact face ID.diff --git a/docs/semantic/artifacts/m1/native-proof.md b/docs/semantic/artifacts/m1/native-proof.mdnew file mode 100644index 00000000..b9348fc3--- /dev/null+++ b/docs/semantic/artifacts/m1/native-proof.md@@ -0,0 +1,11 @@+# Native proof++Ground-truth command:++`aetheris inspect fixtures/FirmamentV2/Canonical/valid/table-template-concept-path-compose.firmament --json`++The output shows Table `PlateStandards`, with-derived record `ThickSmall`,+specialization `template:a4b84f0a2a193884`, semantic root+`concept-path:Outline`, `ProfileCapable`/`ComposeOperandCapable`, exact+`ResolvedProfile2D`, typed guide/endpoint members, and Compose consumer `Stock`.+The Concept Path/Compose test suite passes through the same code path.diff --git a/docs/semantic/artifacts/m1/negative-diagnostics.md b/docs/semantic/artifacts/m1/negative-diagnostics.mdnew file mode 100644index 00000000..ddd24cea--- /dev/null+++ b/docs/semantic/artifacts/m1/negative-diagnostics.md@@ -0,0 +1,7 @@+# Negative diagnostic evidence++`Aetheris.Semantics.Tests` covers scalar-to-Profile, body-to-boundary, false+Forge Profile claim, missing/private member, raw face member, mesh ID region,+stable-ID collision, and exact Forge member consumers. Existing parser tests+cover duplicate recognized members and unresolved imported faces. Specific codes+are asserted rather than message fragments where a common code exists.diff --git a/docs/semantic/artifacts/m1/producer-consumer-matrix.md b/docs/semantic/artifacts/m1/producer-consumer-matrix.mdnew file mode 100644index 00000000..8351a254--- /dev/null+++ b/docs/semantic/artifacts/m1/producer-consumer-matrix.md@@ -0,0 +1,13 @@+# Producer / consumer matrix++| Producer | Exposed evidence | Consumers proved in M1 |+| --- | --- | --- |+| Direct Firmament profile | exact validated profile | Profile, Compose, Selection admission, admitted Modify |+| Concept Path | profile binding plus typed guide/endpoint members | Profile, Compose; ordinary selection after materialization |+| Template + Table/Record/with | same output value plus specialization/input provenance | same as native output |+| InlineStep/Recognize | exact imported face/region and STEP association | structured member path, Selection, FEA, admitted face Modify |+| Forge SecretCoupon | exact body, `TopFace`, `LoadRegion` | structured member path, Selection, FEA, admitted face/body Modify |++There are no origin-named consumer implementations. Recognition import+association checks and Forge output checks remain producer validation, not+consumer adapters.diff --git a/docs/semantic/artifacts/m1/provenance-traces.md b/docs/semantic/artifacts/m1/provenance-traces.mdnew file mode 100644index 00000000..75a670d5--- /dev/null+++ b/docs/semantic/artifacts/m1/provenance-traces.md@@ -0,0 +1,10 @@+# Provenance traces++- Native: authored `Outline` -> `template:a4b84f0a2a193884` -> exact profile -> Compose.+- Record input: Table row `Small` -> `BaseSpec` -> with-derived `ThickSmall` ->+ `PlateTemplate` specialization. Output remains `concept-path:Outline`.+- Imported: canonical resource hash -> InlineStep body -> Recognize `MountHole`+ with kind/confidence -> exact STEP face `#191` -> Selection/FEA.+- Forge: host source -> template specialization ->+ `[email protected]` -> exact construction/BRep ->+ exposed face -> Selection/FEA.diff --git a/docs/semantic/artifacts/m1/stable-ids.md b/docs/semantic/artifacts/m1/stable-ids.mdnew file mode 100644index 00000000..3e390829--- /dev/null+++ b/docs/semantic/artifacts/m1/stable-ids.md@@ -0,0 +1,12 @@+# Stable identity evidence++- Native descriptor SHA-256, repeated canonical CLI inspection:+ `7f6d9da354862e9c423fa8bd4dd71c33b3e9b590ea7f7f77959364300b7a305d`+ on both runs.+- Imported descriptor SHA-256:+ `9786bfadca391a53547284f2eb229d85b68a0dece7264048191aa2df400c60d4`+ on both runs.+- Forge repeated artifact hash:+ `7282965B703FEB85478AC8B651B6F6255D3BC922D3B2A7EBE73726C611CB4D36`.++The native check exposed and fixed nondeterministic Record-member JSON ordering.diff --git a/docs/semantic/artifacts/m1/support-matrix.md b/docs/semantic/artifacts/m1/support-matrix.mdnew file mode 100644index 00000000..7e036e3b--- /dev/null+++ b/docs/semantic/artifacts/m1/support-matrix.md@@ -0,0 +1,13 @@+# Semantic-value support matrix++| Origin | Expose member | Concept Path | Selection | Profile | Compose | Modify | FEA Region | Inspection |+| --- | --- | --- | --- | --- | --- | --- | --- | --- |+| Direct Firmament | Supported | Supported where exposed | capability | capability | capability | exact targets only | boundary capability | Supported |+| Concept Struct | Supported | Supported | capability | if exact profile bound | if profile bound | exact targets only | if boundary bound | Supported |+| Template output | Supported | Supported | capability | capability | capability | exact targets only | boundary capability | Supported |+| Table/Record Template | Supported | Supported | capability | capability | capability | exact targets only | boundary capability | Supported |+| InlineStep/Recognize | recognized members only | Supported for exposed member | Supported | future recognition needed | future recognition needed | exact face/region only | Supported | Supported |+| Forge extension | validated members only | Supported for exposed member | Supported | if exact profile bound | if profile bound | exact targets only | Supported | Supported by host descriptor |++“Capability” means supported only when the producer proves and attaches that+specific contract. Raw BRep and mesh identifiers are intentionally unsupported.diff --git a/docs/semantic/semantic-value-m1.md b/docs/semantic/semantic-value-m1.mdnew file mode 100644index 00000000..1be1066b--- /dev/null+++ b/docs/semantic/semantic-value-m1.md@@ -0,0 +1,55 @@+# Semantic Value M1++Milestone `P2-SEMANTIC-VALUE-M1` establishes the common typed layer and proves+the bounded routes already supported by Preview 2.++## Producers++- Firmament profiles and Concept Paths produce profile/selectable/exact/Compose+ values with validated `ResolvedProfile2D` bindings. Compose now obtains path+ operands through this contract.+- Concept IR scalars and Concept Struct members normalize without invented+ geometry capabilities.+- Template expansion runs first; specialization and Table/Record/with-derived+ input remain provenance while output identity remains its own identity.+- InlineStep/Recognize reimports the canonical artifact, checks the persisted+ STEP-entity-to-FaceId association, and exposes only recognized regions as exact+ boundary/selectable/analysis values. It does not infer profiles.+- Forge capabilities may return a compiler-owned semantic root. The sample+ exposes exact `TopFace` and `LoadRegion` members plus its exact body.++## Consumers and diagnostics++Profile and Compose share `ProfileSemanticConsumer`. Selection accepts a+`SemanticReference` and exact selection/BRep face/region evidence. Modify admits+only exact body, face/region, or profile bindings. FEA accepts+`BoundaryRegionCapability` and normalizes before AnalysisIR. The direct imported+proof uses `imported.MountFace`; native `body.face(+X)` syntax is also normalized+through a produced semantic value.++Standard codes are `semantic-value-missing-capability`,+`semantic-value-no-exact-binding`, `semantic-path-member-missing`,+`semantic-path-member-not-exposed`, `semantic-value-stable-identity-collision`,+and `forge-semantic-output-invalid`. Segment resolution retains the segment span.++## Stable identity and provenance++Native IDs derive from canonical authored declaration identities. Template+outputs retain their output ID and add specialization/input provenance.+Recognize IDs combine the canonical resource hash, body/member identity, and+sorted exact STEP entities. Forge IDs combine extension capability/version and+canonical arguments. Ordered member/capability/binding inspection is stable.+Repeated CLR allocation is irrelevant.++Provenance is an ordered list, never a cyclic object graph. Typical chains are+authored -> template specialization -> path segment -> consumer,+InlineStep hash -> Recognize declaration -> consumer, and template -> Forge+capability/version -> construction -> consumer.++## Bounded limitations++There is no general imported profile recognizer; recognized hole/plane regions+are boundary regions only. Modify syntax has not been broadened. Forge adds no+geometry family and the sample does not claim `ProfileCapability`. Raw faces,+edges, mesh elements, and arbitrary host objects remain unexposed. Cadmata keeps+its existing semantic/provenance tree; this M1 does not redesign its API.