Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Support standard library consumers and pattern inspection
Yuechen Li548a316703ea
diff --git a/Aetheris.CLI.Tests/CanonicalCliWorkflowTests.cs b/Aetheris.CLI.Tests/CanonicalCliWorkflowTests.csindex 4f1563f0..4ab6ac40 100644--- a/Aetheris.CLI.Tests/CanonicalCliWorkflowTests.cs+++ b/Aetheris.CLI.Tests/CanonicalCliWorkflowTests.cs@@ -57,6 +57,61 @@ public sealed class CanonicalCliWorkflowTestsfinally { File.Delete(source); }}+ [Fact]+ public void Inspect_Firmament_Resolves_Shipped_Standard_Library_Consumers()+ {+ var root = FindRepositoryRoot();+ var source = Path.Combine(root, "fixtures", "Canonical", "Integration", "standard-products", "mounting-plate-library-use.firmament");+ var stdout = new StringWriter();+ var stderr = new StringWriter();++ var exitCode = Aetheris.CLI.CliRunner.Run(["inspect", source, "--json"], stdout, stderr);++ Assert.Equal(0, exitCode);+ Assert.True(string.IsNullOrWhiteSpace(stderr.ToString()), stderr.ToString());+ using var document = JsonDocument.Parse(stdout.ToString());+ Assert.True(document.RootElement.GetProperty("success").GetBoolean());+ Assert.Contains(document.RootElement.GetProperty("templateInstances").EnumerateArray(),+ instance => instance.GetProperty("template").GetString() == "MountingPlateTemplate");+ Assert.DoesNotContain(document.RootElement.GetProperty("diagnostics").EnumerateArray(),+ diagnostic => diagnostic.GetString() == "firmament-v2-parse-failed");+ }++ [Fact]+ public void Validate_Firmament_Resolves_Shipped_Standard_Library_Consumers()+ {+ var root = FindRepositoryRoot();+ var source = Path.Combine(root, "fixtures", "Canonical", "Integration", "standard-products", "mounting-plate-library-use.firmament");+ var stdout = new StringWriter();+ var stderr = new StringWriter();++ var exitCode = Aetheris.CLI.CliRunner.Run(["validate", source, "--json"], stdout, stderr);++ Assert.Equal(0, exitCode);+ Assert.True(string.IsNullOrWhiteSpace(stderr.ToString()), stderr.ToString());+ using var document = JsonDocument.Parse(stdout.ToString());+ Assert.Equal("valid", document.RootElement.GetProperty("firmamentV2Validation").GetProperty("status").GetString());+ }++ [Fact]+ public void Inspect_Firmament_Reports_Retained_Pattern_Inventory()+ {+ var root = FindRepositoryRoot();+ var source = Path.Combine(root, "fixtures", "Canonical", "Integration", "standard-products", "flanged-adapter-eight-pattern.firmament");+ var stdout = new StringWriter();+ var stderr = new StringWriter();++ var exitCode = Aetheris.CLI.CliRunner.Run(["inspect", source, "--json"], stdout, stderr);++ Assert.Equal(0, exitCode);+ Assert.True(string.IsNullOrWhiteSpace(stderr.ToString()), stderr.ToString());+ using var document = JsonDocument.Parse(stdout.ToString());+ var pattern = Assert.Single(document.RootElement.GetProperty("patterns").EnumerateArray());+ Assert.Equal("BoltPattern", pattern.GetProperty("name").GetString());+ Assert.Equal("FlangeBolt", pattern.GetProperty("generator").GetString());+ Assert.Equal(8, pattern.GetProperty("count").GetInt32());+ }+[Fact]public void Inspect_ConceptPath_ReportsTypedCapabilitiesMembersAndConsumers(){diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 50a7e2e4..6beb77b5 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -458,6 +458,7 @@ public static class CliRunnerassertions = build.Value.Export.Assertions,features = build.Value.Export.Features,engineeringFeatures = build.Value.Export.EngineeringFeatures,+ patterns = build.Value.Export.Patterns,featureCount = (build.Value.Export.Features?.Count ?? 0) + (build.Value.Export.EngineeringFeatures?.Count ?? 0),inlineStepMigration = build.Value.Export.InlineStepMigration,inlineStepReplacementAssist = build.Value.Export.InlineStepReplacementAssist,@@ -986,6 +987,8 @@ Model CanonicalPanel {}var source = File.ReadAllText(fullPath);+ var library = FirmamentStandardLibraryResolver.Resolve(source, out var libraryDiagnostics);+ var inspectionSource = library?.Source ?? source;var sweepSource = ExpandSweepInspectionSource(source, out var sweepExpansionDiagnostics);if (CircularSweepAuthoring.IsSweepSource(source)){@@ -1007,19 +1010,19 @@ Model CanonicalPanel {else foreach (var diagnostic in sweepDiagnostics) stderr.WriteLine($"error: {diagnostic}");return sweepSuccess ? 0 : 1;}- var parse = FirmamentV2Parser.Parse(source, Path.GetDirectoryName(fullPath));+ var parse = FirmamentV2Parser.Parse(inspectionSource, Path.GetDirectoryName(fullPath));var document = parse.Document;- var success = parse.IsSuccess && document is not null;+ var success = library is not null && parse.IsSuccess && document is not null;var features = (document?.ModifyBlocks?.SelectMany(block =>block.SemanticHoles.Select(hole => $"Hole<{hole.Variant}> {hole.Name}").Concat((block.EdgeFinishes ?? []).Select(finish => $"{finish.Kind} {finish.Name}"))) ?? []).Concat((document?.Bosses ?? []).Select(feature => $"Boss {feature.Name}")).Concat((document?.Pockets ?? []).Select(feature => $"Pocket {feature.Name}")).ToList();- var semanticValues = FirmamentSemanticValues.FromProfilesAndConceptPaths(source, fullPath).ToList();- if (PrismaticProfileCompositionParser.IsCompositionSource(source))+ var semanticValues = FirmamentSemanticValues.FromProfilesAndConceptPaths(inspectionSource, fullPath).ToList();+ if (PrismaticProfileCompositionParser.IsCompositionSource(inspectionSource)){- var composition = PrismaticProfileCompositionParser.Parse(source);+ var composition = PrismaticProfileCompositionParser.Parse(inspectionSource);if (composition.Feature is { } compositionFeature){features.AddRange((compositionFeature.ShaftHoles ?? []).Select(feature => $"Hole<Shaft> {feature.Name}"));@@ -1029,11 +1032,12 @@ Model CanonicalPanel {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)+ else if (ProfileAuthoringParser.IsProfileSource(inspectionSource) && ProfileAuthoringParser.Parse(inspectionSource).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));+ if (document?.RecognizedRegions?.Count > 0) semanticValues.AddRange(FirmamentSemanticValues.FromRecognizedRegions(document, fullPath, inspectionSource));+ var inspectionDiagnostics = libraryDiagnostics.Concat(parse.Diagnostics).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();var report = new{command = "inspect",@@ -1051,6 +1055,16 @@ Model CanonicalPanel {columns = table.Columns,table.SourceSpan}).ToArray() ?? [],+ patterns = document?.StaticAuthoring?.Patterns?.Select(pattern => new+ {+ pattern.Name,+ pattern.Source,+ generator = pattern.Template,+ count = pattern.GeneratedCount,+ generatedInstances = pattern.GeneratedIds,+ distribution = "AuthoredSourceOrder",+ status = "PreservedThroughFeatureAir;InstancesMaterializedAtBRepPlan"+ }).ToArray() ?? [],templateInstances = (document?.TemplateInstantiations ?? document?.ConceptIr?.TemplateInstantiations)?.Select(instance => new{instance.Template,@@ -1064,7 +1078,7 @@ Model CanonicalPanel {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),+ conceptPaths = ProfileAuthoringParser.InspectConceptPaths(inspectionSource),semanticValues = semanticValues.OrderBy(value => value.StableIdentity, StringComparer.Ordinal).Select(SemanticValueDescriptor.From).ToArray(),recognizedRegions = document?.RecognizedRegions?.Select(region => new{@@ -1079,13 +1093,13 @@ Model CanonicalPanel {features,pmi = document?.Pmi?.Select(item => new { item.Kind, item.Name, item.Target }).ToArray() ?? [],assertions = document?.VolumeAssertions?.Select(assertion => new { assertion.Id, assertion.TargetBodyId, assertion.ExpectedMm3, assertion.ToleranceMm3 }).ToArray() ?? [],- diagnostics = parse.Diagnostics.Order(StringComparer.Ordinal).ToArray()+ diagnostics = inspectionDiagnostics};if (json) stdout.WriteLine(JsonSerializer.Serialize(report, JsonOptions));else if (!success){stderr.WriteLine($"Inspect failed for {fullPath}.");- foreach (var diagnostic in parse.Diagnostics.Order(StringComparer.Ordinal)) stderr.WriteLine($"error: {diagnostic}");+ foreach (var diagnostic in inspectionDiagnostics) stderr.WriteLine($"error: {diagnostic}");}else{@@ -1637,9 +1651,24 @@ Model CanonicalPanel {return sheet.IsSuccess?0:1;}+ var library = FirmamentStandardLibraryResolver.Resolve(validationSource, out var libraryDiagnostics);+ if (library is null)+ {+ var payload = new+ {+ Source = sourcePath,+ Status = "invalid",+ Summary = new { FatalDiagnosticCount = libraryDiagnostics.Count, WarningDiagnosticCount = 0 },+ Diagnostics = libraryDiagnostics+ };+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));+ else stdout.WriteLine($"Firmament V2 validation: invalid ({libraryDiagnostics.Count} fatal, 0 warning)");+ return 1;+ }+var runtimeConfiguration = CreateValidateForgeRuntimeConfiguration(forgePackPaths);var parse = FirmamentV2Parser.Parse(- validationSource,+ library.Source,Path.GetDirectoryName(Path.GetFullPath(sourcePath)),runtimeConfiguration.Catalog);var runtimeValidation = FirmamentV2RuntimeConceptValidation.Validate(parse.Document, runtimeConfiguration);diff --git a/Aetheris.Forge.Host.Tests/ForgeProtocolV1Tests.cs b/Aetheris.Forge.Host.Tests/ForgeProtocolV1Tests.csindex b6dfc9d1..3db2dd38 100644--- a/Aetheris.Forge.Host.Tests/ForgeProtocolV1Tests.cs+++ b/Aetheris.Forge.Host.Tests/ForgeProtocolV1Tests.cs@@ -32,6 +32,8 @@ public sealed class ForgeProtocolV1Testsvar spec = Assert.Single(description.Parameters);Assert.Equal("record", spec.Type);Assert.Equal("mm", spec.Fields!.Single(item => item.Name == "Width").Unit);+ Assert.Equal("120mm", spec.Fields!.Single(item => item.Name == "Width").Default);+ Assert.All(spec.Fields!, field => Assert.False(field.Required));Assert.Equal(["Auto", "Rectangular", "Round"], spec.Fields!.Single(item => item.Name == "ReliefPolicy").AllowedValues);Assert.Equal([ForgeArtifactKind.StepAp242, ForgeArtifactKind.FlatStep, ForgeArtifactKind.Svg], description.Artifacts);}@@ -88,6 +90,18 @@ public sealed class ForgeProtocolV1TestsAssert.True(Step242Importer.ImportBody(File.ReadAllText(System.IO.Path.Combine(first.Path, "part.flat.step"))).IsSuccess);}+ [Fact]+ public void EnclosureCanonicalStaticDefaultCanBeInvokedWithoutDuplicatedFields()+ {+ using var output = TempDirectory.Create();+ var result = new ForgeProtocolHost().InvokeTemplate(Enclosure,+ new ForgeTemplateInvocationRequest(1, new Dictionary<string, JsonElement>(), [ForgeArtifactKind.StepAp242]),+ output.Path);++ Assert.True(result.Success, string.Join(Environment.NewLine, result.Diagnostics.Select(item => item.Code + ": " + item.Message)));+ Assert.True(File.Exists(System.IO.Path.Combine(output.Path, "part.step")));+ }+[Theory][MemberData(nameof(InvalidRequests))]public void InvalidInvocationsReturnCanonicalStructuredDiagnostics(@@ -103,7 +117,6 @@ public sealed class ForgeProtocolV1Testspublic static TheoryData<string, IReadOnlyDictionary<string, object?>, string> InvalidRequests() => new(){{ "Standard.SheetMetal.DoesNotExist", ValidArguments(), "forge-host-template-not-found" },- { Enclosure, Without("width"), "firmament-template-record-missing-field" },{ Enclosure, With("mystery", "1 mm"), "firmament-template-record-extra-field" },{ Enclosure, With("width", true), "forge-host-argument-transport-type" },{ Enclosure, With("width", "12 kg"), "firmament-template-record-field-type-mismatch" },diff --git a/Aetheris.Forge.Host.Tests/StandardProductLibraryTests.cs b/Aetheris.Forge.Host.Tests/StandardProductLibraryTests.csnew file mode 100644index 00000000..28121473--- /dev/null+++ b/Aetheris.Forge.Host.Tests/StandardProductLibraryTests.cs@@ -0,0 +1,130 @@+using System.Text.Json;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Forge.Host.Tests;++public sealed class StandardProductLibraryTests+{+ [Fact]+ public void CatalogExposesEightCoherentStandardProductFamilies()+ {+ var products = new ForgeProtocolHost().ListTemplates().Templates+ .Where(item => item.Id.StartsWith("Standard.Products.", StringComparison.Ordinal)).ToArray();+ Assert.Equal(8, products.Length);+ Assert.All(products, product => Assert.NotNull(new ForgeProtocolHost().DescribeTemplate(product.Id)));+ }++ [Theory]+ [MemberData(nameof(Variants))]+ public void FlagshipVariantsProduceDeterministicReimportableStep(+ string templateId, IReadOnlyDictionary<string, object?> arguments)+ {+ using var first = TempDirectory.Create();+ using var second = TempDirectory.Create();+ var host = new ForgeProtocolHost();+ var request = new ForgeTemplateInvocationRequest(1, arguments.ToDictionary(+ pair => pair.Key, pair => JsonSerializer.SerializeToElement(pair.Value), StringComparer.Ordinal),+ [ForgeArtifactKind.StepAp242]);+ var a = host.InvokeTemplate(templateId, request, first.Path);+ var b = host.InvokeTemplate(templateId, request, second.Path);+ Assert.True(a.Success, string.Join(Environment.NewLine, a.Diagnostics.Select(item => item.Code + ": " + item.Message)));+ Assert.True(b.Success, string.Join(Environment.NewLine, b.Diagnostics.Select(item => item.Code + ": " + item.Message)));+ Assert.Equal(a.Identity.Specialization, b.Identity.Specialization);+ Assert.Equal(a.Artifacts.Single().Sha256, b.Artifacts.Single().Sha256);+ var step = File.ReadAllText(System.IO.Path.Combine(first.Path, a.Artifacts.Single().Path));+ Assert.True(Step242Importer.ImportBody(step).IsSuccess);+ }++ [Fact]+ public void MountingPlateConstraintUsesProductSemantics()+ {+ using var output = TempDirectory.Create();+ var values = MountingPlate();+ values["holeSpacingX"] = "121 mm";+ var request = new ForgeTemplateInvocationRequest(1, values.ToDictionary(+ pair => pair.Key, pair => JsonSerializer.SerializeToElement(pair.Value), StringComparer.Ordinal),+ [ForgeArtifactKind.StepAp242]);+ var result = new ForgeProtocolHost().InvokeTemplate("Standard.Products.Mechanical.MountingPlate", request, output.Path);+ Assert.False(result.Success);+ Assert.Contains(result.Diagnostics, item => item.Code == "firmament-template-require-failed" && item.Message.Contains("HoleSpacingXFitsPlate", StringComparison.Ordinal));+ }++ [Fact]+ public void DescribeProjectsResolvedStaticRecordDefaultsToFields()+ {+ var description = Assert.IsType<ForgeTemplateDescription>(+ new ForgeProtocolHost().DescribeTemplate("Standard.Products.Mechanical.MountingPlate"));+ var policy = Assert.Single(description.Parameters);+ Assert.Equal("StandardMountingPlate", policy.Default);+ var fields = policy.Fields!.ToDictionary(field => field.Name, StringComparer.Ordinal);+ Assert.Equal("120mm", fields["Width"].Default);+ Assert.Equal("mm", fields["Width"].Unit);+ Assert.False(fields["Width"].Required);+ Assert.Equal("Standard.Materials.Aluminum.6061_T6", fields["Material"].Default);+ }++ [Fact]+ public void CanonicalStaticDefaultCanBeInvokedWithoutDuplicatingFields()+ {+ using var output = TempDirectory.Create();+ var result = new ForgeProtocolHost().InvokeTemplate(+ "Standard.Products.Mechanical.MountingPlate",+ new ForgeTemplateInvocationRequest(1, new Dictionary<string, JsonElement>(), [ForgeArtifactKind.StepAp242]),+ output.Path);+ Assert.True(result.Success, string.Join(Environment.NewLine, result.Diagnostics.Select(item => item.Message)));+ var inspection = Step242SemanticPmiInspector.Inspect(File.ReadAllText(+ System.IO.Path.Combine(output.Path, result.Artifacts.Single().Path)));+ Assert.True(inspection.Success);+ Assert.Equal(1, inspection.DatumCount);+ Assert.Equal(1, inspection.DimensionCount);+ }++ [Fact]+ public void EightHoleFlangeSpecializesThroughForge()+ {+ using var output = TempDirectory.Create();+ var values = Values(("outerDiameter", "80 mm"), ("bodyThickness", "12 mm"), ("boreDiameter", "30 mm"),+ ("boltHoleDiameter", "6.6 mm"), ("boltCount", 8), ("material", "Standard.Materials.Aluminum.6061_T6"));+ var result = new ForgeProtocolHost().InvokeTemplate(+ "Standard.Products.Mechanical.FlangedAdapter",+ new ForgeTemplateInvocationRequest(1, values.ToDictionary(pair => pair.Key,+ pair => JsonSerializer.SerializeToElement(pair.Value), StringComparer.Ordinal), [ForgeArtifactKind.StepAp242]),+ output.Path);+ Assert.True(result.Success, string.Join(Environment.NewLine, result.Diagnostics.Select(item => item.Message)));+ var imported = Step242Importer.ImportBody(File.ReadAllText(System.IO.Path.Combine(output.Path, result.Artifacts.Single().Path)));+ Assert.True(imported.IsSuccess);+ Assert.Equal(42, imported.Value!.Topology.Faces.Count());+ }++ public static TheoryData<string, IReadOnlyDictionary<string, object?>> Variants() => new()+ {+ { "Standard.Products.Mechanical.MountingPlate", MountingPlate() },+ { "Standard.Products.Mechanical.BearingBlock", Values(("baseWidth", "100 mm"), ("baseDepth", "50 mm"), ("baseThickness", "14 mm"), ("bossDiameter", "36 mm"), ("bossHeight", "18 mm"), ("boreDiameter", "20 mm"), ("mountSpacing", "72 mm"), ("mountHoleDiameter", "8.5 mm"), ("material", "Standard.Materials.Aluminum.6061_T6")) },+ { "Standard.Products.Mechanical.MachinedAngleBracket", Values(("width", "80 mm"), ("height", "60 mm"), ("legWidth", "20 mm"), ("thickness", "10 mm"), ("holeDiameter", "8.5 mm"), ("material", "Standard.Materials.Steel.ASTM_A36")) },+ { "Standard.Products.Mechanical.ShaftCollar", Values(("outerDiameter", "32 mm"), ("boreDiameter", "16 mm"), ("width", "12 mm"), ("material", "Standard.Materials.StainlessSteel.304_Annealed")) },+ { "Standard.Products.Mechanical.FlangedAdapter", Values(("outerDiameter", "80 mm"), ("bodyThickness", "12 mm"), ("boreDiameter", "30 mm"), ("boltHoleDiameter", "6.6 mm"), ("boltCount", 6), ("material", "Standard.Materials.Aluminum.6061_T6")) },+ { "Standard.Products.Electronics.RackPanel", Values(("width", "482.6 mm"), ("height", "44.45 mm"), ("thickness", "3 mm"), ("mountHoleDiameter", "6.5 mm"), ("mountInset", "12.7 mm"), ("material", "Standard.Materials.Aluminum.5052_H32")) },+ { "Standard.Products.Mechanical.Standoff", Values(("outerDiameter", "10 mm"), ("length", "25 mm"), ("boreDiameter", "4.2 mm"), ("material", "Standard.Materials.StainlessSteel.304_Annealed")) },+ };++ private static Dictionary<string, object?> MountingPlate() => Values(+ ("width", "120 mm"), ("height", "80 mm"), ("thickness", "10 mm"), ("holeDiameter", "6.6 mm"),+ ("holeSpacingX", "90 mm"), ("holeSpacingY", "50 mm"), ("counterboreDiameter", "11 mm"),+ ("counterboreDepth", "4 mm"), ("material", "Standard.Materials.Aluminum.6061_T6"));++ private static Dictionary<string, object?> Values(params (string Name, object? Value)[] values) =>+ values.ToDictionary(item => item.Name, item => item.Value, StringComparer.Ordinal);++ private sealed class TempDirectory : IDisposable+ {+ private TempDirectory(string path) => Path = path;+ public string Path { get; }+ public static TempDirectory Create()+ {+ var path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "aetheris-standard-products-" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(path);+ return new(path);+ }+ public void Dispose() { if (Directory.Exists(Path)) Directory.Delete(Path, true); }+ }+}diff --git a/Aetheris.Forge.Host/ForgeProtocolContracts.cs b/Aetheris.Forge.Host/ForgeProtocolContracts.csindex 81dc2738..39828ecf 100644--- a/Aetheris.Forge.Host/ForgeProtocolContracts.cs+++ b/Aetheris.Forge.Host/ForgeProtocolContracts.cs@@ -104,4 +104,5 @@ public sealed record ForgeProtocolErrorResponse([JsonSerializable(typeof(ForgeTemplateInvocationRequest))][JsonSerializable(typeof(ForgeTemplateInvocationResult))][JsonSerializable(typeof(ForgeProtocolErrorResponse))]+[JsonSerializable(typeof(string))]internal partial class ForgeProtocolJsonContext : JsonSerializerContext;diff --git a/Aetheris.Forge.Host/ForgeProtocolHost.cs b/Aetheris.Forge.Host/ForgeProtocolHost.csindex 4b284ea6..de0e05dc 100644--- a/Aetheris.Forge.Host/ForgeProtocolHost.cs+++ b/Aetheris.Forge.Host/ForgeProtocolHost.cs@@ -136,7 +136,7 @@ public sealed class ForgeProtocolHost{var (name, contentType, content) = nativeCompilation is null? GenerateArtifact(kind, sheetMetalCompilation!)- : GenerateNativeArtifact(kind, nativeCompilation);+ : GenerateNativeArtifact(kind, nativeCompilation, known.Id);var path = Path.Combine(root, name);var resolved = Path.GetFullPath(path);if (!string.Equals(Path.GetDirectoryName(resolved), root, StringComparison.OrdinalIgnoreCase))@@ -179,25 +179,50 @@ public sealed class ForgeProtocolHostitem,module.Records.ToDictionary(record => record.Name, StringComparer.Ordinal),module.Enums.ToDictionary(value => value.Name, StringComparer.Ordinal),+ module.StaticRecords.ToDictionary(value => value.Name, StringComparer.Ordinal),[ForgeArtifactKind.StepAp242, ForgeArtifactKind.FlatStep, ForgeArtifactKind.Svg], false)).ToArray();- var productSource = PaperclipTemplateLibrary.Source;- var products = FirmamentTemplateHostBridge.InspectModule(productSource, out var productDiagnostics);+ var productCatalogSource = StandardProductTemplateLibrary.Source;+ var products = FirmamentTemplateHostBridge.InspectModule(productCatalogSource, out var productDiagnostics);if (productDiagnostics.Count > 0)throw new InvalidOperationException("Standard Products Firmament template catalog is invalid: " + string.Join("; ", productDiagnostics));- var productVersion = "1+" + Convert.ToHexString(SHA256.HashData(Utf8.GetBytes(productSource)))[..12].ToLowerInvariant();- var paperclip = products.Templates.Where(item => string.Equals(item.Name, "PaperclipTemplate", StringComparison.Ordinal))- .Select(item => new RegisteredTemplate(PaperclipTemplateLibrary.TemplateId, "Paperclip", productVersion,- "A bounded parametric office paperclip compiled from a semantic planar path and constant circular Sweep.",- productSource, item, products.Records.ToDictionary(record => record.Name, StringComparer.Ordinal),- products.Enums.ToDictionary(value => value.Name, StringComparer.Ordinal), [ForgeArtifactKind.StepAp242], true));- return sheetMetal.Concat(paperclip).ToArray();+ var productVersion = "1+" + Convert.ToHexString(SHA256.HashData(Utf8.GetBytes(productCatalogSource)))[..12].ToLowerInvariant();+ var definitions = new Dictionary<string, (string Id, string Name, string Documentation)>(StringComparer.Ordinal)+ {+ ["PaperclipTemplate"] = (PaperclipTemplateLibrary.TemplateId, "Paperclip", "A bounded parametric office paperclip compiled from a semantic planar path and constant circular Sweep."),+ ["MountingPlateTemplate"] = ("Standard.Products.Mechanical.MountingPlate", "Mounting Plate", "General-purpose machined plate with a four-corner counterbored mounting-hole layout and manufacturing PMI."),+ ["BearingBlockTemplate"] = ("Standard.Products.Mechanical.BearingBlock", "Bearing Block", "Generic machined bearing-support block with a base, circular boss, shaft bore, mounting holes, and bore PMI."),+ ["MachinedAngleBracketTemplate"] = ("Standard.Products.Mechanical.MachinedAngleBracket", "Machined Angle Bracket", "Prismatic machined L-bracket with two mounting holes and explicit leg proportions."),+ ["ShaftCollarTemplate"] = ("Standard.Products.Mechanical.ShaftCollar", "Shaft Collar", "Simple solid shaft collar with a through bore; split and clamp mechanics are intentionally outside this family."),+ ["FlangedAdapterTemplate"] = ("Standard.Products.Mechanical.FlangedAdapter", "Flanged Adapter", "Six-hole circular flanged adapter with a central bore, bolt-circle constraints, and bore PMI."),+ ["RackPanelTemplate"] = ("Standard.Products.Electronics.RackPanel", "Rack Panel", "Metric planar equipment panel with symmetric mounting holes and configurable edge inset."),+ ["StandoffTemplate"] = ("Standard.Products.Mechanical.Standoff", "Standoff", "Compact cylindrical spacer with a concentric fastener-clearance bore."),+ };+ var records = products.Records.ToDictionary(record => record.Name, StringComparer.Ordinal);+ var enums = products.Enums.ToDictionary(value => value.Name, StringComparer.Ordinal);+ var staticRecords = products.StaticRecords.ToDictionary(value => value.Name, StringComparer.Ordinal);+ var productTemplates = products.Templates.Where(item => definitions.ContainsKey(item.Name)).Select(item =>+ {+ var definition = definitions[item.Name];+ var recordName = item.Parameters.Single().TypeName;+ var isolatedSource = StandardProductTemplateLibrary.GetTemplateSource(item.Name, recordName);+ return new RegisteredTemplate(definition.Id, definition.Name, productVersion, definition.Documentation,+ isolatedSource, item, records, enums, staticRecords, [ForgeArtifactKind.StepAp242], true);+ });+ return sheetMetal.Concat(productTemplates).ToArray();}private static ForgeTemplateParameterDescription DescribeParameter(RegisteredTemplate template, FirmamentTemplateParameterMetadata parameter){+ var defaults = parameter.DefaultExpression is not null+ && template.StaticRecords.TryGetValue(parameter.DefaultExpression, out var defaultRecord)+ && string.Equals(defaultRecord.TypeName, parameter.TypeName, StringComparison.Ordinal)+ ? defaultRecord.Fields+ : null;var fields = template.Records.TryGetValue(parameter.TypeName, out var record)- ? record.Fields.Select(field => DescribeValue(template, field.Name, field.TypeName, true, null)).ToArray()+ ? record.Fields.Select(field => DescribeValue(template, field.Name, field.TypeName,+ defaults is null || !defaults.ContainsKey(field.Name),+ defaults is not null && defaults.TryGetValue(field.Name, out var value) ? Unquote(value) : null)).ToArray(): null;return DescribeValue(template, parameter.Name, parameter.TypeName, parameter.DefaultExpression is null,parameter.DefaultExpression, fields,@@ -205,6 +230,11 @@ public sealed class ForgeProtocolHostparameter.ConstraintConcept);}+ private static string Unquote(string value) =>+ value.Length >= 2 && value[0] == '"' && value[^1] == '"'+ ? JsonSerializer.Deserialize(value, ForgeProtocolJsonContext.Default.String) ?? string.Empty+ : value;+private static ForgeTemplateParameterDescription DescribeValue(RegisteredTemplate template, string name, string type,bool required, string? defaultValue, IReadOnlyList<ForgeTemplateParameterDescription>? fields = null,string category = "value", string? constraint = null)@@ -232,7 +262,12 @@ public sealed class ForgeProtocolHostvar projectedRecord = parameters.Count == 1 && template.Records.TryGetValue(parameters[0].TypeName, out onlyRecord);if (projectedRecord && !TryGet(supplied, parameters[0].Name, out _)){- BindRecordFields(parameters[0].Name, parameters[0].TypeName, onlyRecord!, supplied, result, template, diagnostics);+ if (supplied.Count == 0 && parameters[0].DefaultExpression is not null) return result;+ IReadOnlyDictionary<string, string>? defaults = null;+ if (parameters[0].DefaultExpression is { } defaultExpression+ && template.StaticRecords.TryGetValue(defaultExpression, out var defaultRecord))+ defaults = defaultRecord.Fields;+ BindRecordFields(parameters[0].Name, parameters[0].TypeName, onlyRecord!, supplied, result, template, diagnostics, defaults);return result;}@@ -271,9 +306,12 @@ public sealed class ForgeProtocolHostprivate static void BindRecordFields(string parameterName, string recordType, FirmamentTemplateRecordMetadata record,IEnumerable<KeyValuePair<string, JsonElement>> values, IDictionary<string, FirmamentHostArgument> result,- RegisteredTemplate template, ICollection<ForgeProtocolDiagnostic> diagnostics)+ RegisteredTemplate template, ICollection<ForgeProtocolDiagnostic> diagnostics,+ IReadOnlyDictionary<string, string>? defaults = null){- var fields = new Dictionary<string, string>(StringComparer.Ordinal);+ var fields = defaults is null+ ? new Dictionary<string, string>(StringComparer.Ordinal)+ : new Dictionary<string, string>(defaults, StringComparer.Ordinal);foreach (var property in values){var field = record.Fields.FirstOrDefault(item => string.Equals(item.Name, property.Key, StringComparison.OrdinalIgnoreCase));@@ -346,9 +384,9 @@ public sealed class ForgeProtocolHostthrow new InvalidOperationException($"Artifact kind '{kind}' has no generator.");}- private static (string Name, string ContentType, string Content) GenerateNativeArtifact(ForgeArtifactKind kind, FirmamentStepExportResult result) =>+ private static (string Name, string ContentType, string Content) GenerateNativeArtifact(ForgeArtifactKind kind, FirmamentStepExportResult result, string templateId) =>kind == ForgeArtifactKind.StepAp242- ? ("paperclip.step", "model/step", result.StepText)+ ? (templateId == PaperclipTemplateLibrary.TemplateId ? "paperclip.step" : "part.step", "model/step", result.StepText): throw new InvalidOperationException($"Native Firmament artifact kind '{kind}' has no generator.");private static ForgeProtocolDiagnostic FromFirmamentDiagnostic(string value)@@ -405,6 +443,7 @@ public sealed class ForgeProtocolHostFirmamentTemplateMetadata Metadata,IReadOnlyDictionary<string, FirmamentTemplateRecordMetadata> Records,IReadOnlyDictionary<string, FirmamentTemplateEnumMetadata> Enums,+ IReadOnlyDictionary<string, FirmamentTemplateStaticRecordMetadata> StaticRecords,IReadOnlyList<ForgeArtifactKind> Artifacts,bool NativeFirmament);}diff --git a/Aetheris.Kernel.Firmament.Tests/X1aSemanticClosureWitnessTests.cs b/Aetheris.Kernel.Firmament.Tests/X1aSemanticClosureWitnessTests.csnew file mode 100644index 00000000..996233ed--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/X1aSemanticClosureWitnessTests.cs@@ -0,0 +1,149 @@+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class X1aSemanticClosureWitnessTests+{+ [Fact]+ public void ShippedModuleResolution_BindsQualifiedStaticWithAndTemplate()+ {+ var source = File.ReadAllText(Fixture("Canonical/Integration/standard-products/mounting-plate-library-use.firmament"));+ var resolution = FirmamentStandardLibraryResolver.Resolve(source, out var diagnostics);+ Assert.NotNull(resolution);+ Assert.Empty(diagnostics);+ Assert.Equal(["Standard.Products.Mechanical.MountingPlate"], resolution!.Declarations);+ var parse = FirmamentV2Parser.Parse(resolution.Source);+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));+ var policy = Assert.Single(parse.Document!.TemplateInstantiations!).RecordArguments!["P"];+ Assert.Equal("120mm", policy.Members["Width"]);+ Assert.Contains("derivedFrom:StandardMountingPlate", policy.Provenance, StringComparison.Ordinal);+ }++ [Fact]+ public void StaticWithDefaults_AreResolvedByBinderMetadata()+ {+ const string source = """+ Model Defaults {+ Units: mm+ Record Policy { Width: Length Material: String }+ Static Base: Policy = Policy { Width: 100mm Material: "catalog.material" }+ Static Wide = Base with { Width: 140mm }+ Template<P: Policy = Wide> Struct Product { Box Body { Size: [P.Width, 20mm, 5mm] } }+ }+ """;+ var module = FirmamentTemplateHostBridge.InspectModule(source, out var diagnostics);+ Assert.Empty(diagnostics);+ var wide = Assert.Single(module.StaticRecords, item => item.Name == "Wide");+ Assert.Equal("140mm", wide.Fields["Width"]);+ Assert.Equal("\"catalog.material\"", wide.Fields["Material"]);+ Assert.Contains("derivedFrom:Base", wide.Provenance, StringComparison.Ordinal);+ }++ [Fact]+ public void VariableFlangePattern_RetainsCanonicalPatternInventory()+ {+ var source = StandardProductTemplateLibrary.GetTemplateSource("FlangedAdapterTemplate", "FlangedAdapterPolicy");+ var expansion = FirmamentTemplateHostBridge.Expand(source, "FlangedAdapterTemplate", "Flange8",+ new Dictionary<string, FirmamentHostArgument>+ {+ ["P"] = new("", "FlangedAdapterPolicy", new Dictionary<string, string>+ {+ ["OuterDiameter"] = "80mm", ["BodyThickness"] = "12mm", ["BoreDiameter"] = "30mm",+ ["BoltHoleDiameter"] = "6.6mm", ["BoltCount"] = "8",+ ["Material"] = "\"Standard.Materials.Aluminum.6061_T6\"",+ })+ }, out var diagnostics);+ Assert.NotNull(expansion);+ Assert.Empty(diagnostics);+ var parse = FirmamentV2Parser.Parse(expansion!.ExpandedSource);+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));+ var pattern = Assert.Single(parse.Document!.StaticAuthoring!.Patterns);+ Assert.Equal("BoltPattern", pattern.Name);+ Assert.Equal("FlangeBolt", pattern.Template);+ Assert.Equal(8, pattern.GeneratedCount);+ Assert.Equal("8", expansion.RecordArguments["P"]["BoltCount"]);+ var compiled = FirmamentBuildAndExport.CompileSource(expansion.ExpandedSource);+ Assert.True(compiled.IsSuccess, string.Join(Environment.NewLine, compiled.Diagnostics.Select(item => item.Message)));+ Assert.Equal(9, compiled.Value.Features!.Count);+ var report = Assert.Single(compiled.Value.Patterns!);+ Assert.Equal(8, report.Count);+ Assert.Equal("FlangeBolt", report.Generator);+ }++ [Fact]+ public void TemplatePmi_IsLiftedAndSurvivesAp242Reinspection()+ {+ var source = StandardProductTemplateLibrary.GetTemplateSource("MountingPlateTemplate", "MountingPlatePolicy", includeDefaultInstance: true);+ var result = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(result.IsSuccess, string.Join(Environment.NewLine, result.Diagnostics.Select(item => item.Message)));+ var inspection = Aetheris.Kernel.Core.Step242.Step242SemanticPmiInspector.Inspect(result.Value.StepText);+ Assert.True(inspection.Success, string.Join(Environment.NewLine, inspection.Diagnostics));+ Assert.Equal(1, inspection.DatumCount);+ Assert.Equal(1, inspection.DimensionCount);+ Assert.NotEmpty(inspection.Items.Single(item => item.Kind == "Diameter").GeometricFaceEntityIds);+ }++ [Fact]+ public void NestedTemplatePmi_RebindsThroughBothSpecializationsAndAp242()+ {+ const string source = """+ Model NestedPmi {+ Units: mm+ Concept MountingPlateContract {+ Bounds: Box3+ TopPlane: Plane+ MountPoints: Point3[]+ }+ Template<> Struct Inner {+ Concept Struct Design: MountingPlateContract {+ Bounds: Box3 { Size: [40mm, 30mm, 8mm] }+ TopPlane: Bounds.Face(+Z)+ MountPoints: Grid {+ Within: Bounds.Face(+Z).Inset(10mm)+ Columns: 1+ Rows: 1+ }+ }+ Box Base { Bounds: Design.Bounds }+ Modify Base {+ Hole<Shaft> InnerHole {+ On: Base.Top+ Center: Design.MountPoints[0]+ Diameter: 6mm+ End: ThroughAll+ }+ }+ Expose {+ Bounds: Design.Bounds+ TopPlane: Base.Top+ MountPoints: Design.MountPoints+ }+ Pmi {+ Datum A { Target: face(+Z) }+ HoleDiameter InnerHoleDiameter {+ Target: InnerHole+ Value: 6mm+ Tolerance: PlusMinus(0.05mm, 0.02mm)+ DatumRefs: [A]+ }+ }+ }+ Template<> Struct Outer { Struct Generated = Inner<> }+ Struct Product = Outer<>+ }+ """;+ var parse = FirmamentV2Parser.Parse(source);+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));+ Assert.Equal(["Outer", "Inner"], parse.Document!.ConceptIr!.TemplateInstantiations!.Select(item => item.Template));+ Assert.Equal(2, parse.Document.Pmi?.Count ?? parse.Document.PmiBlock?.Records.Count ?? 0);+ var result = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(result.IsSuccess, string.Join(Environment.NewLine, result.Diagnostics.Select(item => item.Message)));+ var inspection = Aetheris.Kernel.Core.Step242.Step242SemanticPmiInspector.Inspect(result.Value.StepText);+ Assert.True(inspection.Success, string.Join(Environment.NewLine, inspection.Diagnostics));+ Assert.Equal(1, inspection.DatumCount);+ Assert.Equal(1, inspection.DimensionCount);+ }++ private static string Fixture(string relative) => Path.GetFullPath(Path.Combine(+ AppContext.BaseDirectory, "../../../../fixtures", relative.Replace('/', Path.DirectorySeparatorChar)));+}diff --git a/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj b/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csprojindex de4ea54f..906eaea1 100644--- a/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj+++ b/Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj@@ -19,5 +19,6 @@<ItemGroup><EmbeddedResource Include="Resources\Inter-Regular.ttf" LogicalName="Aetheris.Drawing.Inter.ttf" /><EmbeddedResource Include="Resources\ProfileModifications.firmament" />+ <EmbeddedResource Include="Standard\StandardProducts.firmament" LogicalName="Aetheris.Standard.StandardProducts.firmament" /></ItemGroup></Project>diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 8e1714a3..892dcdb9 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -37,6 +37,10 @@ public static class FirmamentBuildAndExportvar fullSourcePath = Path.GetFullPath(sourcePath);var sourceText = NormalizeLf(File.ReadAllText(fullSourcePath, Encoding.UTF8));+ var library = FirmamentStandardLibraryResolver.Resolve(sourceText, out var libraryDiagnostics);+ if (library is null)+ return KernelResult<FirmamentBuildAndExportResult>.Failure(LibraryDiagnostics(libraryDiagnostics));+ sourceText = library.Source;var exportResult = ExportSource(sourceText, Path.GetDirectoryName(fullSourcePath), allowV1Compatibility: true);if (!exportResult.IsSuccess){@@ -81,6 +85,10 @@ public static class FirmamentBuildAndExport{ArgumentNullException.ThrowIfNull(sourceText);var normalized = NormalizeLf(sourceText);+ var library = FirmamentStandardLibraryResolver.Resolve(normalized, out var libraryDiagnostics);+ if (library is null)+ return KernelResult<FirmamentStepExportResult>.Failure(LibraryDiagnostics(libraryDiagnostics));+ normalized = library.Source;// In-memory compilation is the canonical V2 boundary used by Forge,// assemblies, and drawings. Historical V1 execution is intentionally// available only to the explicitly versioned file compatibility route.@@ -100,7 +108,7 @@ public static class FirmamentBuildAndExportstring? sourceDirectory,FirmamentStepExportResult export){- var parsed = FirmamentV2Parser.Parse(source, sourceDirectory);+ var parsed = ParseSemanticSource(source, sourceDirectory);if (!parsed.IsSuccess || parsed.Document is null) return export;var edgeFinishes = (parsed.Document.ModifyBlocks ?? [])@@ -117,7 +125,17 @@ public static class FirmamentBuildAndExportPolicySource: finish.Kind,MaterializationRoute: "SemanticEdgeFinish"))).ToArray();- if (edgeFinishes.Length == 0) return export;+ var patterns = (parsed.Document.StaticAuthoring?.Patterns ?? [])+ .Select(pattern => new FirmamentSemanticPatternReport(+ pattern.Name,+ pattern.Source,+ pattern.Template,+ pattern.GeneratedCount,+ pattern.GeneratedIds,+ "FiniteStaticArray"))+ .OrderBy(pattern => pattern.Name, StringComparer.Ordinal)+ .ToArray();+ if (edgeFinishes.Length == 0 && patterns.Length == 0) return export;var existing = export.EngineeringFeatures ?? [];return export with@@ -126,13 +144,14 @@ public static class FirmamentBuildAndExport.Concat(edgeFinishes).DistinctBy(feature => feature.FeatureId, StringComparer.Ordinal).OrderBy(feature => feature.FeatureId, StringComparer.Ordinal)- .ToArray()+ .ToArray(),+ Patterns = patterns};}private static KernelResult<IReadOnlyList<FirmamentV2VolumeAssertionResult>> EvaluateVolumeAssertions(string source, string? sourceDirectory, FirmamentStepExportResult export){- var parsed = FirmamentV2Parser.Parse(source, sourceDirectory);+ var parsed = ParseSemanticSource(source, sourceDirectory);if (!parsed.IsSuccess || parsed.Document?.VolumeAssertions is not { Count: > 0 } assertions) return KernelResult<IReadOnlyList<FirmamentV2VolumeAssertionResult>>.Success([]);var imported = Step242Importer.ImportBody(export.StepText);if (!imported.IsSuccess || imported.Value is null)@@ -157,7 +176,7 @@ public static class FirmamentBuildAndExportprivate static KernelResult<bool> VerifyV2PmiExportParity(string source, string? sourceDirectory, FirmamentStepExportResult export){- var parsed = FirmamentV2Parser.Parse(source, sourceDirectory);+ var parsed = ParseSemanticSource(source, sourceDirectory);if (!parsed.IsSuccess || parsed.Document is null || parsed.Document.Pmi is not { Count: > 0 } pmi)return KernelResult<bool>.Success(true);@@ -297,7 +316,7 @@ public static class FirmamentBuildAndExportif (!support.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(support.Diagnostics);var features = (stack.Feature.ShaftHoles ?? []).ToDictionary(hole => hole.Name, hole => hole.StableId, StringComparer.Ordinal);foreach (var hole in stack.Feature.CounterboreHoles ?? []) features[hole.Name] = hole.StableId;- semanticPmi = BuildV2SemanticPmi(v2Parse.Document, [], stack.Feature.Name, features).ToArray();+ semanticPmi = BuildV2SemanticPmi(v2Parse.Document, [], stack.Feature.Name, features, emitted.Correspondence).ToArray();}var step = Step242Exporter.ExportBody(completedBody, semanticPmi);if (!step.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);@@ -470,6 +489,16 @@ public static class FirmamentBuildAndExportreturn ExportV1CompatibilitySource(sourceText);}+ private static FirmamentV2ParseResult ParseSemanticSource(string source, string? sourceDirectory)+ => FirmamentV2Parser.Parse(source, sourceDirectory);++ private static IReadOnlyList<Kernel.Core.Diagnostics.KernelDiagnostic> LibraryDiagnostics(IEnumerable<string> diagnostics) =>+ diagnostics.Select(message => new Kernel.Core.Diagnostics.KernelDiagnostic(+ Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,+ Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error,+ message,+ "FirmamentV2.LibraryResolution")).ToArray();+private static KernelResult<FirmamentStepExportResult> V2SourceRequired(FirmamentV2ParseResult parse){var fatal = parse.Diagnostics@@ -605,7 +634,7 @@ public static class FirmamentBuildAndExportif (!support.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(support.Diagnostics);var features = (stack.Feature.ShaftHoles ?? []).ToDictionary(hole => hole.Name, hole => hole.StableId, StringComparer.Ordinal);foreach (var hole in stack.Feature.CounterboreHoles ?? []) features[hole.Name] = hole.StableId;- semanticPmi = BuildV2SemanticPmi(canonicalDocument, [], stack.Feature.Name, features).ToArray();+ semanticPmi = BuildV2SemanticPmi(canonicalDocument, [], stack.Feature.Name, features, plannedEmission.Correspondence).ToArray();}var plannedStep = Step242Exporter.ExportBody(plannedEmission.Body, semanticPmi, new Step242ExportOptions { ProductName = target.StableId, ApplicationName = "Aetheris.Firmament.ComposedProfileBoundaryChamfer.M3", BrepExportPreflightMode = BrepExportPreflightMode.Enforce, BrepExportPreflightPolicy = BrepExportPreflightPolicy.TrustedProductionRoute });if (!plannedStep.IsSuccess || plannedStep.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(plannedStep.Diagnostics);@@ -1923,7 +1952,12 @@ public static class FirmamentBuildAndExport"FirmamentV2.PmiExport")).ToArray());}- private static IReadOnlyList<Step242SemanticPmi> BuildV2SemanticPmi(FirmamentV2Document document, IReadOnlyList<Core.Air.AirHoleFeature> semanticHoles, string targetSolid, IReadOnlyDictionary<string, string>? explicitFeatureIds = null)+ private static IReadOnlyList<Step242SemanticPmi> BuildV2SemanticPmi(+ FirmamentV2Document document,+ IReadOnlyList<Core.Air.AirHoleFeature> semanticHoles,+ string targetSolid,+ IReadOnlyDictionary<string, string>? explicitFeatureIds = null,+ SemanticTopologyCorrespondence? correspondence = null){if (document.Pmi is null || document.Pmi.Count == 0){@@ -1961,7 +1995,18 @@ public static class FirmamentBuildAndExport}}- return result;+ if (correspondence is null) return result;+ return result.Select(item => item with+ {+ GeometricFaceIds = correspondence.Descendants+ .Where(descendant => descendant.Face.HasValue+ && (string.Equals(descendant.SourceStableId, item.FeatureId, StringComparison.Ordinal)+ || string.Equals(descendant.ParentStableId, item.FeatureId, StringComparison.Ordinal)))+ .Select(descendant => descendant.Face!.Value.Value)+ .Distinct()+ .Order()+ .ToArray()+ }).ToArray();}diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.csindex 7cca86a0..9fe19c9c 100644--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs@@ -22,7 +22,17 @@ public sealed record FirmamentStepExportResult(IReadOnlyList<Aetheris.Kernel.Firmament.FirmamentV2.FirmamentV2VolumeAssertionResult>? Assertions = null,FirmamentStandardPartReport? StandardPart = null,IReadOnlyList<FirmamentEngineeringFeatureReport>? EngineeringFeatures = null,- FirmamentSweepReport? Sweep = null);+ FirmamentSweepReport? Sweep = null,+ IReadOnlyList<FirmamentSemanticPatternReport>? Patterns = null);++public sealed record FirmamentSemanticPatternReport(+ string Name,+ string Source,+ string Generator,+ int Count,+ IReadOnlyList<string> GeneratedInstances,+ string Distribution,+ string Status = "PreservedThroughFeatureAir;InstancesMaterializedAtBRepPlan");public sealed record FirmamentSweepReport(string Path,diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.csindex 1ebe9e91..c9ef2b86 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs@@ -159,6 +159,17 @@ internal static class CanonicalStaticAuthoring}patterns.Add(new(pattern.Groups["name"].Value, array.Name, template.Name, generated.Count, generated, new(pattern.Index, close - pattern.Index + 1)));changes.Add((pattern.Index, close - pattern.Index + 1, string.Join(Environment.NewLine, output)));+ // PMI may target a semantic Pattern instance. Resolve that declaration identity+ // through the same deterministic materialization map used for generated features.+ for (var index = 0; index < generated.Count; index++)+ {+ var semanticId = generated[index];+ var materializedId = semanticId.Replace("[", "_", StringComparison.Ordinal).Replace("]", string.Empty, StringComparison.Ordinal);+ foreach (Match target in Regex.Matches(source,+ $@"\bTarget\s*:\s*(?<id>{Regex.Escape(semanticId)})\b",+ RegexOptions.CultureInvariant))+ changes.Add((target.Groups["id"].Index, target.Groups["id"].Length, materializedId));+ }}// A direct invocation is the same static expansion route as Pattern, with andiff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentStandardLibraryResolver.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentStandardLibraryResolver.csnew file mode 100644index 00000000..4c49903f--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentStandardLibraryResolver.cs@@ -0,0 +1,126 @@+using System.Text.RegularExpressions;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++public sealed record FirmamentLibraryResolution(+ string Source,+ IReadOnlyList<string> Modules,+ IReadOnlyList<string> Declarations);++/// <summary>+/// Resolves the finite shipped Standard Products namespace into named declarations. This is a+/// semantic catalog link: only known exports can be selected, no file path or arbitrary source+/// include is admitted, and the embedded catalog remains the sole definition authority.+/// </summary>+public static class FirmamentStandardLibraryResolver+{+ public const string UnknownModule = "firmament-library-unknown-module";+ public const string UnknownDeclaration = "firmament-library-unknown-declaration";+ public const string MissingUse = "firmament-library-module-not-used";+ public const string AmbiguousSymbol = "firmament-library-ambiguous-symbol";++ private sealed record Export(+ string Module,+ string PublicName,+ string TemplateName,+ string RecordName,+ string StaticName);++ private static readonly Export[] Exports =+ [+ new("Standard.Products.Office", "Paperclip", "PaperclipTemplate", "PaperclipPolicy", "StandardPaperclip"),+ new("Standard.Products.Mechanical", "MountingPlate", "MountingPlateTemplate", "MountingPlatePolicy", "StandardMountingPlate"),+ new("Standard.Products.Mechanical", "BearingBlock", "BearingBlockTemplate", "BearingBlockPolicy", "StandardBearingBlock"),+ new("Standard.Products.Mechanical", "MachinedAngleBracket", "MachinedAngleBracketTemplate", "MachinedAngleBracketPolicy", "StandardMachinedAngleBracket"),+ new("Standard.Products.Mechanical", "ShaftCollar", "ShaftCollarTemplate", "ShaftCollarPolicy", "StandardShaftCollar"),+ new("Standard.Products.Mechanical", "FlangedAdapter", "FlangedAdapterTemplate", "FlangedAdapterPolicy", "StandardFlangedAdapter"),+ new("Standard.Products.Mechanical", "Standoff", "StandoffTemplate", "StandoffPolicy", "StandardStandoff"),+ new("Standard.Products.Electronics", "RackPanel", "RackPanelTemplate", "RackPanelPolicy", "StandardRackPanel"),+ ];++ public static FirmamentLibraryResolution? Resolve(string source, out IReadOnlyList<string> diagnostics)+ {+ ArgumentNullException.ThrowIfNull(source);+ var errors = new List<string>();+ var uses = Regex.Matches(source, @"(?m)^\s*Use\s+(?<module>[A-Za-z_][A-Za-z0-9_.]*)\s*$", RegexOptions.CultureInvariant)+ .Cast<Match>().ToArray();+ if (uses.Length == 0)+ {+ diagnostics = [];+ return new(source, [], []);+ }++ var knownModules = Exports.Select(item => item.Module).ToHashSet(StringComparer.Ordinal);+ var imported = uses.Select(match => match.Groups["module"].Value).Distinct(StringComparer.Ordinal).ToArray();+ foreach (var module in imported.Where(module => !knownModules.Contains(module)))+ errors.Add($"{UnknownModule}:{module}: shipped Standard Library module could not be resolved");++ var references = Regex.Matches(source,+ @"\bStandard\.Products\.(?:Office|Mechanical|Electronics)\.[A-Za-z_][A-Za-z0-9_]*\b",+ RegexOptions.CultureInvariant)+ .Cast<Match>().Select(match => match.Value).Distinct(StringComparer.Ordinal).ToArray();+ var selected = new HashSet<Export>();+ var replacements = new Dictionary<string, string>(StringComparer.Ordinal);+ foreach (var reference in references)+ {+ var split = reference.LastIndexOf('.');+ var module = reference[..split];+ var symbol = reference[(split + 1)..];+ if (!imported.Contains(module, StringComparer.Ordinal))+ {+ errors.Add($"{MissingUse}:{module}:{reference}");+ continue;+ }+ var export = Exports.FirstOrDefault(item => item.Module == module+ && (item.PublicName == symbol || item.RecordName == symbol || item.StaticName == symbol));+ if (export is null)+ {+ errors.Add($"{UnknownDeclaration}:{reference}");+ continue;+ }+ selected.Add(export);+ replacements[reference] = symbol == export.PublicName ? export.TemplateName : symbol;+ }+ if (errors.Count > 0)+ {+ diagnostics = errors.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();+ return null;+ }++ foreach (var export in selected)+ {+ foreach (var localName in new[] { export.TemplateName, export.RecordName, export.StaticName })+ {+ if (Regex.IsMatch(source, $@"\b(?:Template\s*<[^>]*>\s*(?:Struct\s+)?|Record\s+|Static\s+){Regex.Escape(localName)}\b", RegexOptions.CultureInvariant))+ errors.Add($"{AmbiguousSymbol}:{localName}: local declaration collides with shipped export");+ }+ }+ if (errors.Count > 0)+ {+ diagnostics = errors;+ return null;+ }++ var resolved = source;+ foreach (var replacement in replacements.OrderByDescending(item => item.Key.Length))+ resolved = resolved.Replace(replacement.Key, replacement.Value, StringComparison.Ordinal);+ resolved = Regex.Replace(resolved, @"(?m)^\s*Use\s+[A-Za-z_][A-Za-z0-9_.]*\s*\r?\n?", string.Empty, RegexOptions.CultureInvariant);+ if (selected.Count > 0)+ {+ var declarations = string.Join(Environment.NewLine + Environment.NewLine,+ selected.OrderBy(item => item.PublicName, StringComparer.Ordinal)+ .Select(item => StandardProductTemplateLibrary.GetExportedDeclarations(item.TemplateName, item.RecordName)));+ var close = resolved.LastIndexOf('}');+ if (close < 0)+ {+ diagnostics = ["firmament-library-invalid-consuming-module: canonical Model body was not found"];+ return null;+ }+ resolved = resolved.Insert(close, Environment.NewLine + declarations + Environment.NewLine);+ }++ diagnostics = [];+ return new(resolved, imported.Order(StringComparer.Ordinal).ToArray(),+ selected.Select(item => item.Module + "." + item.PublicName).Order(StringComparer.Ordinal).ToArray());+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.csindex 21105e49..30dee533 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs@@ -30,11 +30,18 @@ public sealed record FirmamentTemplateEnumMetadata(string Name,IReadOnlyList<string> Cases);+public sealed record FirmamentTemplateStaticRecordMetadata(+ string Name,+ string TypeName,+ IReadOnlyDictionary<string, string> Fields,+ string Provenance);+/// <summary>Authoritative public Template schema extracted from Firmament binder IR.</summary>public sealed record FirmamentTemplateModuleMetadata(IReadOnlyList<FirmamentTemplateMetadata> Templates,IReadOnlyList<FirmamentTemplateRecordMetadata> Records,- IReadOnlyList<FirmamentTemplateEnumMetadata> Enums);+ IReadOnlyList<FirmamentTemplateEnumMetadata> Enums,+ IReadOnlyList<FirmamentTemplateStaticRecordMetadata> StaticRecords);public enum FirmamentTemplateParameterKind{@@ -123,8 +130,12 @@ public static class FirmamentTemplateHostBridgevar enums = FirmamentV2TemplateExpansion.InspectEnums(moduleSource).Select(item => new FirmamentTemplateEnumMetadata(item.Key, item.Value.ToArray())).ToArray();+ var staticRecords = FirmamentV2TemplateExpansion.InspectStaticRecords(moduleSource, collected)+ .Select(record => new FirmamentTemplateStaticRecordMetadata(+ record.Name, record.TypeName, record.Fields, record.Provenance))+ .ToArray();diagnostics = collected.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();- return new(templates, records, enums);+ return new(templates, records, enums, staticRecords);}public static FirmamentHostTemplateExpansion? Expand(@@ -157,7 +168,9 @@ public static class FirmamentTemplateHostBridgemoduleSource, templateName, instanceName, hostArguments, collected);diagnostics = collected.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();if (expansion is null) return null;- var instance = expansion.Instantiations.Single();+ var instance = expansion.Instantiations.First(item =>+ string.Equals(item.Template, templateName, StringComparison.Ordinal)+ && string.Equals(item.Instance, instanceName, StringComparison.Ordinal));return new FirmamentHostTemplateExpansion(expansion.Source,templateName,diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csindex fbb56240..e27745ad 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -1060,6 +1060,16 @@ public static class FirmamentV2Parservar concept = ParseConceptModelingDocument(adapterSource, diagnostics, templateInstantiations);if (!concept.IsSuccess || concept.Document is null) return concept;+ var conceptSolids = concept.Document.Solids.ToDictionary(solid => solid.Name, StringComparer.Ordinal);+ var (conceptPmi, conceptPmiBlock, conceptBoundPmi) = ParsePmi(+ source,+ conceptSolids,+ concept.Document.ModifyBlocks ?? [],+ concept.Document.RecognizedRegions ?? [],+ concept.Document.BoundLets ?? [],+ concept.Document.BoundLetRecords ?? [],+ diagnostics);+ if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);var conceptSelectionDiagnostics = new List<string>();var conceptSelections = ParseCanonicalSelections(body, rootOpen + 1, conceptSelectionDiagnostics);ValidateCanonicalSelectionSources(body, conceptSelections, [], conceptSelectionDiagnostics);@@ -1071,7 +1081,10 @@ public static class FirmamentV2Parservar normalized = concept.Document with{ModelName = model.Groups["name"].Value,- Selections = conceptSelections+ Selections = conceptSelections,+ Pmi = conceptPmi,+ PmiBlock = conceptPmiBlock,+ BoundPmi = conceptBoundPmi};diagnostics.Add("firmament-v2-unified-canonical-advanced-parsed");diagnostics.Sort(StringComparer.Ordinal);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.csindex de63eff8..d7c01994 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs@@ -90,6 +90,12 @@ internal static class FirmamentV2TemplateExpansioninternal sealed record HostRecord(string Name, IReadOnlyDictionary<string, string> Fields);+ internal sealed record HostStaticRecord(+ string Name,+ string TypeName,+ IReadOnlyDictionary<string, string> Fields,+ string Provenance);+internal static IReadOnlyList<HostTemplate> Inspect(string source, List<string> diagnostics) =>ParseDeclarations(source, diagnostics).Select(template => new HostTemplate(@@ -125,6 +131,22 @@ internal static class FirmamentV2TemplateExpansionitem => (IReadOnlyList<string>)item.Value.OrderBy(value => value, StringComparer.Ordinal).ToArray(),StringComparer.Ordinal);+ internal static IReadOnlyList<HostStaticRecord> InspectStaticRecords(string source, List<string> diagnostics)+ {+ var enums = ParseEnums(source);+ var recordTypes = ParseRecordTypes(source, diagnostics);+ var tables = ParseStaticTables(source, recordTypes, enums, diagnostics);+ var staticRecords = ParseStaticRecords(source, recordTypes, enums, tables, diagnostics);+ return staticRecords.Values+ .OrderBy(record => record.Name, StringComparer.Ordinal)+ .Select(record => new HostStaticRecord(+ record.Name,+ record.TypeName,+ FlattenRecordFields(record, recordTypes, staticRecords),+ record.Provenance))+ .ToArray();+ }+/// <summary>/// Expands one host-supplied Template invocation from typed arguments. The invocation is/// admitted directly as binder IR; callers never need to manufacture Firmament application@@ -195,10 +217,12 @@ internal static class FirmamentV2TemplateExpansionvar bound = Bind(template, application, source, enums, recordTypes, staticRecords, diagnostics);if (bound is null || HasErrors(diagnostics)) return null;+ if (!ValidateRecordMembers(template.Body, bound, diagnostics)) return null;+ if (!EvaluateRequires(Substitute(template.Body, bound), application.InstanceName,+ DisplaySignature(template), diagnostics, out var requireResults)) return null;var body = ResolveTemplateMatches(template.Body, bound, diagnostics, out var selectedMatches);- if (body is null || !ValidateRecordMembers(body, bound, diagnostics)) return null;+ if (body is null) return null;body = Substitute(body, bound);- if (!EvaluateRequires(body, application.InstanceName, DisplaySignature(template), diagnostics, out var requireResults)) return null;body = RemoveRequires(body);var specialization = new TemplateSpecializationIr(@@ -229,19 +253,24 @@ internal static class FirmamentV2TemplateExpansionSelectedMatchArms: selectedMatches,RecordArguments: recordArguments,RequireResults: requireResults);+ var nestedInstantiations = new List<ConceptIrTemplateInstantiation>();+ body = ExpandNestedApplications(body, byName, source, enums, recordTypes, staticRecords,+ diagnostics, nestedInstantiations, [template.Name]);+ if (HasErrors(diagnostics)) return null;+ var liftedPmi = LiftPmi(body, out body);var changes = declarations.Select(declaration => (Start: declaration.SourceSpan.Start,Length: declaration.SourceSpan.Length,Text: string.Equals(declaration.Name, template.Name, StringComparison.Ordinal)- ? $"{template.TargetKind} {instanceName}{template.HeaderTail} {{{body}}}"+ ? $"{template.TargetKind} {instanceName}{template.HeaderTail} {{{body}}}{liftedPmi}": string.Empty)).OrderByDescending(change => change.Start).ToArray();foreach (var change in changes)source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);- return HasErrors(diagnostics) ? null : new Result(source, [instantiation]);+ return HasErrors(diagnostics) ? null : new Result(source, new[] { instantiation }.Concat(nestedInstantiations).ToArray());void ValidateSyntheticRecord(string recordName, TemplateRecordTypeIr definition,IReadOnlyDictionary<string, string> fields, string prefix)@@ -276,7 +305,11 @@ internal static class FirmamentV2TemplateExpansionvar declarations = ParseDeclarations(source, diagnostics);var byName = declarations.ToDictionary(d => d.Name, StringComparer.Ordinal);DetectTemplateCycles(declarations, byName, diagnostics);- var applications = ParseApplications(source, byName, diagnostics);+ var applications = ParseApplications(source, byName, diagnostics)+ .Where(application => !declarations.Any(declaration =>+ application.SourceSpan.Start > declaration.SourceSpan.Start+ && application.SourceSpan.Start < declaration.SourceSpan.Start + declaration.SourceSpan.Length))+ .ToImmutableArray();if (HasErrors(diagnostics)) return null;var enums = ParseEnums(source);@@ -292,18 +325,22 @@ internal static class FirmamentV2TemplateExpansionvar bound = Bind(template, application, source, enums, recordTypes, staticRecords, diagnostics);if (bound is null) continue;var specialization = new TemplateSpecializationIr(template, application, bound, Identity(template, application, bound), GeneratedPaths(template.Body, application.InstanceName));+ if (!ValidateRecordMembers(template.Body, bound, diagnostics)) continue;+ if (!EvaluateRequires(Substitute(template.Body, bound), application.InstanceName,+ DisplaySignature(template), diagnostics, out var requireResults)) continue;var body = ResolveTemplateMatches(template.Body, bound, diagnostics, out var selectedMatches);if (body is null) continue;- if (!ValidateRecordMembers(body, bound, diagnostics)) continue;body = Substitute(body, bound);- if (!EvaluateRequires(body, application.InstanceName, DisplaySignature(template), diagnostics, out var requireResults)) continue;body = RemoveRequires(body);- changes.Add((application.SourceSpan.Start, application.SourceSpan.Length, $"{template.TargetKind} {application.InstanceName}{template.HeaderTail} {{{body}}}"));var recordArguments = bound.RecordArguments.ToDictionary(pair => pair.Key, pair => new ConceptIrTemplateRecordArgument(pair.Value.TypeName, pair.Value.StaticName, pair.Value.Fields, pair.Value.SourceSpan, pair.Value.Provenance), StringComparer.Ordinal);instantiations.Add(new(template.Name, application.InstanceName, bound.TypeArguments, bound.ValueArguments, bound.DefaultedArguments,specialization.SpecializationIdentity, specialization.GeneratedDeclarationPaths, template.SourceSpan, application.SourceSpan,SelectedMatchArms: selectedMatches, RecordArguments: recordArguments, RequireResults: requireResults));+ body = ExpandNestedApplications(body, byName, source, enums, recordTypes, staticRecords,+ diagnostics, instantiations, [template.Name]);+ var liftedPmi = LiftPmi(body, out body);+ changes.Add((application.SourceSpan.Start, application.SourceSpan.Length, $"{template.TargetKind} {application.InstanceName}{template.HeaderTail} {{{body}}}{liftedPmi}"));}if (HasErrors(diagnostics)) return null;foreach (var change in changes.OrderByDescending(c => c.Start)) source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);@@ -669,10 +706,17 @@ internal static class FirmamentV2TemplateExpansionvar selected = new Dictionary<string, string>(StringComparer.Ordinal);while (true){- var match = Regex.Match(body, @"\bMatch\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1));+ var match = Regex.Match(body, @"\bMatch\s+(?<name>[A-Za-z_][A-Za-z0-9_]*(?:\s*\.\s*[A-Za-z_][A-Za-z0-9_]*)?)\s*\{", RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1));if (!match.Success) { selectedMatches = selected; return body; }- var name = match.Groups["name"].Value;- if (!bound.ValueArguments.TryGetValue(name, out var selectedArm)) { selectedMatches = selected; return body; }+ var name = Regex.Replace(match.Groups["name"].Value, @"\s+", string.Empty, RegexOptions.CultureInvariant);+ string? selectedArm = null;+ if (!bound.ValueArguments.TryGetValue(name, out selectedArm))+ {+ var dot = name.IndexOf('.');+ if (dot > 0 && bound.RecordArguments.TryGetValue(name[..dot], out var record))+ record.Fields.TryGetValue(name[(dot + 1)..], out selectedArm);+ }+ if (selectedArm is null) { selectedMatches = selected; return body; }var open = match.Index + match.Value.LastIndexOf('{'); var close = Matching(body, open, '{', '}');if (close < 0) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); selectedMatches = selected; return null; }var arm = Regex.Match(body[(open + 1)..close], $@"(?m)^\s*{Regex.Escape(selectedArm)}\s*=>\s*", RegexOptions.CultureInvariant);@@ -756,6 +800,73 @@ internal static class FirmamentV2TemplateExpansion})) + ">";private static ImmutableArray<string> GeneratedPaths(string body, string instance) => Regex.Matches(body, @"\b(?:Concept\s+Struct|Box|Modify|EdgeFinish)\s+(?<n>[A-Za-z_][A-Za-z0-9_]*)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant).Select(m => instance + "::" + m.Groups["n"].Value).Distinct().ToImmutableArray();private static string RemoveRequires(string body) => Regex.Replace(body, @"(?m)^\s*Require\s+[A-Za-z_][A-Za-z0-9_]*\s*=>\s*[^\r\n}]+\s*$", string.Empty);+ private static string LiftPmi(string body, out string withoutPmi)+ {+ var blocks = new List<(int Start, int Length, string Text)>();+ foreach (Match header in Regex.Matches(body, @"\bPmi\s*\{", RegexOptions.CultureInvariant))+ {+ if (blocks.Any(block => header.Index >= block.Start && header.Index < block.Start + block.Length)) continue;+ var open = body.IndexOf('{', header.Index);+ var close = Matching(body, open, '{', '}');+ if (close >= 0) blocks.Add((header.Index, close - header.Index + 1, body[header.Index..(close + 1)]));+ }+ withoutPmi = body;+ foreach (var block in blocks.OrderByDescending(block => block.Start))+ withoutPmi = withoutPmi.Remove(block.Start, block.Length);+ return blocks.Count == 0 ? string.Empty : Environment.NewLine + string.Join(Environment.NewLine, blocks.Select(block => block.Text));+ }++ private static string ExpandNestedApplications(+ string body,+ IReadOnlyDictionary<string, TemplateDeclarationIr> templates,+ string moduleSource,+ IReadOnlyDictionary<string, ImmutableHashSet<string>> enums,+ IReadOnlyDictionary<string, TemplateRecordTypeIr> recordTypes,+ IReadOnlyDictionary<string, TemplateStaticRecordIr> staticRecords,+ List<string> diagnostics,+ ICollection<ConceptIrTemplateInstantiation> instantiations,+ IReadOnlyList<string> stack)+ {+ var applications = ParseApplications(body, templates, diagnostics);+ var changes = new List<(int Start, int Length, string Text)>();+ foreach (var application in applications)+ {+ var template = templates[application.TemplateName];+ if (stack.Contains(template.Name, StringComparer.Ordinal))+ {+ diagnostics.Add(Recursive + ":" + string.Join(" -> ", stack.Append(template.Name)));+ continue;+ }+ var bound = Bind(template, application, moduleSource, enums, recordTypes, staticRecords, diagnostics);+ if (bound is null) continue;+ if (!ValidateRecordMembers(template.Body, bound, diagnostics)) continue;+ if (!EvaluateRequires(Substitute(template.Body, bound), application.InstanceName,+ DisplaySignature(template), diagnostics, out var requireResults)) continue;+ var specializedBody = ResolveTemplateMatches(template.Body, bound, diagnostics, out var selectedMatches);+ if (specializedBody is null) continue;+ specializedBody = Substitute(specializedBody, bound);+ specializedBody = RemoveRequires(specializedBody);+ var specialization = new TemplateSpecializationIr(template, application, bound,+ Identity(template, application, bound), GeneratedPaths(template.Body, application.InstanceName));+ var recordArguments = bound.RecordArguments.ToDictionary(pair => pair.Key, pair => new ConceptIrTemplateRecordArgument(+ pair.Value.TypeName, pair.Value.StaticName, pair.Value.Fields, pair.Value.SourceSpan, pair.Value.Provenance), StringComparer.Ordinal);+ instantiations.Add(new(template.Name, application.InstanceName, bound.TypeArguments, bound.ValueArguments,+ bound.DefaultedArguments, specialization.SpecializationIdentity, specialization.GeneratedDeclarationPaths,+ template.SourceSpan, application.SourceSpan, SelectedMatchArms: selectedMatches,+ RecordArguments: recordArguments, RequireResults: requireResults));+ specializedBody = ExpandNestedApplications(specializedBody, templates, moduleSource, enums, recordTypes,+ staticRecords, diagnostics, instantiations, stack.Append(template.Name).ToArray());+ var liftedPmi = LiftPmi(specializedBody, out specializedBody);+ // Nested finite specializations flatten into the containing declaration before+ // Feature AIR. The instantiation record above preserves the semantic boundary;+ // material grammar receives concrete declarations without unsupported nested Structs.+ changes.Add((application.SourceSpan.Start, application.SourceSpan.Length,+ specializedBody + liftedPmi));+ }+ foreach (var change in changes.OrderByDescending(change => change.Start))+ body = body.Remove(change.Start, change.Length).Insert(change.Start, change.Text);+ return body;+ }private static bool HasErrors(IEnumerable<string> diagnostics) => diagnostics.Any(d => d.StartsWith(Prefix, StringComparison.Ordinal));private static int Matching(string source, int open, char begin, char end) { var depth = 0; for (var i = open; i < source.Length; i++) { if (source[i] == begin) depth++; else if (source[i] == end && --depth == 0) return i; } return -1; }}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/PaperclipTemplateLibrary.cs b/Aetheris.Kernel.Firmament/FirmamentV2/PaperclipTemplateLibrary.csindex 76bc02b3..35f4d9f1 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/PaperclipTemplateLibrary.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/PaperclipTemplateLibrary.cs@@ -1,63 +1,75 @@namespace Aetheris.Kernel.Firmament.FirmamentV2;-/// <summary>The first bounded public Standard Products template family.</summary>-public static class PaperclipTemplateLibrary+/// <summary>Authoritative shipped Firmament source for public Standard Products.</summary>+public static class StandardProductTemplateLibrary{- public const string TemplateId = "Standard.Products.Office.Paperclip";-- public const string Source = """- Model StandardProductsOfficePaperclip {- Units: mm+ private const string ResourceName = "Aetheris.Standard.StandardProducts.firmament";- Record PaperclipPolicy {- WireDiameter: Length- OverallLength: Length- OuterWidth: Length- InnerWidth: Length- BendRadius: Length- LoopGap: Length- Material: String- }-- Static StandardPaperclip: PaperclipPolicy = PaperclipPolicy {- WireDiameter: 0.8mm- OverallLength: 33mm- OuterWidth: 9mm- InnerWidth: 5mm- BendRadius: 1mm- LoopGap: 1mm- Material: "Standard.Materials.StainlessSteel.304_Annealed"- }-- Template < P: PaperclipPolicy >- Struct PaperclipTemplate {- Require PositiveWireDiameter => P.WireDiameter > 0mm- Require LengthExceedsWidth => P.OverallLength > P.OuterWidth- Require OuterWidthExceedsInnerWidth => P.OuterWidth > P.InnerWidth- Require InnerLoopClearsWire => P.InnerWidth > P.WireDiameter- Require BendClearsWire => P.BendRadius > P.WireDiameter- Require EndsHaveClearance => P.LoopGap >= P.WireDiameter+ public static string Source+ {+ get+ {+ using var stream = typeof(StandardProductTemplateLibrary).Assembly.GetManifestResourceStream(ResourceName)+ ?? throw new InvalidOperationException($"Embedded Firmament module '{ResourceName}' was not found.");+ using var reader = new StreamReader(stream);+ return reader.ReadToEnd();+ }+ }- Concept Path PaperclipPath {- Start: Point2(0mm, 0mm)- Heading: 90deg- Line InnerUp { Length: P.OverallLength - P.InnerWidth / 2 - P.LoopGap }- Arc InnerTop { Radius: P.InnerWidth / 2; Turn: -180deg }- Line InnerDown { Length: P.OverallLength - P.InnerWidth / 2 - P.OuterWidth / 2 - P.LoopGap }- Arc BottomTransition { Radius: P.BendRadius; Turn: 180deg }- Line OuterUp { Length: P.OverallLength - P.OuterWidth }- Arc OuterTop { Radius: P.OuterWidth / 2; Turn: 180deg }- Line OuterDown { Length: P.OverallLength - P.OuterWidth / 2 - P.LoopGap }- }+ /// <summary>+ /// Produces the bounded one-family module required by the current native geometry+ /// route selector. Schema inspection still uses <see cref="Source"/> as a catalog.+ /// </summary>+ public static string GetTemplateSource(string templateName, string recordName, bool includeDefaultInstance = false)+ {+ ArgumentException.ThrowIfNullOrWhiteSpace(templateName);+ ArgumentException.ThrowIfNullOrWhiteSpace(recordName);+ var source = Source;+ var record = BlockStartingAt(source, source.IndexOf("Record " + recordName, StringComparison.Ordinal));+ var templateNameIndex = source.IndexOf("Struct " + templateName, StringComparison.Ordinal);+ if (templateNameIndex < 0) throw new InvalidOperationException($"Standard product Template '{templateName}' was not found.");+ var templateStart = source.LastIndexOf("Template<", templateNameIndex, StringComparison.Ordinal);+ var template = BlockStartingAt(source, templateStart);+ var staticPrefix = "Static ";+ var staticType = ": " + recordName;+ var staticTypeIndex = source.IndexOf(staticType, StringComparison.Ordinal);+ var staticStart = staticTypeIndex < 0 ? -1 : source.LastIndexOf(staticPrefix, staticTypeIndex, StringComparison.Ordinal);+ var standard = staticStart < 0 ? string.Empty : BlockStartingAt(source, staticStart);+ var staticName = staticStart < 0 ? string.Empty : source[(staticStart + staticPrefix.Length)..source.IndexOf(':', staticStart)].Trim();+ var instance = includeDefaultInstance && staticName.Length > 0+ ? $"\nStruct StandardProduct = {templateName}<P: {staticName}>\n"+ : string.Empty;+ return $"Model StandardProduct {{\nUnits: mm\n{record}\n{standard}\n{template}\n{instance}}}\n";+ }- Sweep Paperclip {- Path: PaperclipPath- Diameter: P.WireDiameter- Material: P.Material- }- }+ internal static string GetExportedDeclarations(string templateName, string recordName)+ {+ var module = GetTemplateSource(templateName, recordName);+ var units = module.IndexOf("Units: mm", StringComparison.Ordinal);+ var bodyStart = module.IndexOf('\n', units) + 1;+ var bodyEnd = module.LastIndexOf('}');+ return module[bodyStart..bodyEnd].Trim();+ }- Struct Paperclip = PaperclipTemplate < P: StandardPaperclip >+ private static string BlockStartingAt(string source, int start)+ {+ if (start < 0) throw new InvalidOperationException("Standard product source declaration was not found.");+ var open = source.IndexOf('{', start);+ if (open < 0) throw new InvalidOperationException("Standard product declaration has no body.");+ var depth = 0;+ for (var index = open; index < source.Length; index++)+ {+ if (source[index] == '{') depth++;+ else if (source[index] == '}' && --depth == 0) return source[start..(index + 1)];}- """;+ throw new InvalidOperationException("Standard product declaration body is unterminated.");+ }+}++/// <summary>Compatibility facade retained for X0 Paperclip consumers.</summary>+public static class PaperclipTemplateLibrary+{+ public const string TemplateId = "Standard.Products.Office.Paperclip";+ public static string Source => StandardProductTemplateLibrary.GetTemplateSource(+ "PaperclipTemplate", "PaperclipPolicy", includeDefaultInstance: true);}diff --git a/Aetheris.Kernel.Firmament/Standard/StandardProducts.firmament b/Aetheris.Kernel.Firmament/Standard/StandardProducts.firmamentnew file mode 100644index 00000000..fea4d182--- /dev/null+++ b/Aetheris.Kernel.Firmament/Standard/StandardProducts.firmament@@ -0,0 +1,227 @@+// Aetheris Standard Library product families. Forge.Host assigns public identities.+Model StandardProducts {+ Units: mm++ Record PaperclipPolicy { WireDiameter: Length OverallLength: Length OuterWidth: Length InnerWidth: Length BendRadius: Length LoopGap: Length Material: String }+ Static StandardPaperclip: PaperclipPolicy = PaperclipPolicy { WireDiameter: 0.8mm OverallLength: 33mm OuterWidth: 9mm InnerWidth: 5mm BendRadius: 1mm LoopGap: 1mm Material: "Standard.Materials.StainlessSteel.304_Annealed" }+ Template<P: PaperclipPolicy = StandardPaperclip>+ Struct PaperclipTemplate {+ Require PositiveWireDiameter => P.WireDiameter > 0mm+ Require LengthExceedsWidth => P.OverallLength > P.OuterWidth+ Require OuterWidthExceedsInnerWidth => P.OuterWidth > P.InnerWidth+ Require InnerLoopClearsWire => P.InnerWidth > P.WireDiameter+ Require BendClearsWire => P.BendRadius > P.WireDiameter+ Require EndsHaveClearance => P.LoopGap >= P.WireDiameter+ Concept Path PaperclipPath {+ Start: Point2(0mm, 0mm) Heading: 90deg+ Line InnerUp { Length: P.OverallLength - P.InnerWidth / 2 - P.LoopGap }+ Arc InnerTop { Radius: P.InnerWidth / 2; Turn: -180deg }+ Line InnerDown { Length: P.OverallLength - P.InnerWidth / 2 - P.OuterWidth / 2 - P.LoopGap }+ Arc BottomTransition { Radius: P.BendRadius; Turn: 180deg }+ Line OuterUp { Length: P.OverallLength - P.OuterWidth }+ Arc OuterTop { Radius: P.OuterWidth / 2; Turn: 180deg }+ Line OuterDown { Length: P.OverallLength - P.OuterWidth / 2 - P.LoopGap }+ }+ Sweep Paperclip { Path: PaperclipPath; Diameter: P.WireDiameter; Material: P.Material; }+ }++ Record MountingPlatePolicy { Width: Length Height: Length Thickness: Length HoleDiameter: Length HoleSpacingX: Length HoleSpacingY: Length CounterboreDiameter: Length CounterboreDepth: Length Material: String }+ Static StandardMountingPlate: MountingPlatePolicy = MountingPlatePolicy { Width: 120mm Height: 80mm Thickness: 10mm HoleDiameter: 6.6mm HoleSpacingX: 90mm HoleSpacingY: 50mm CounterboreDiameter: 11mm CounterboreDepth: 4mm Material: "Standard.Materials.Aluminum.6061_T6" }+ Template<P: MountingPlatePolicy = StandardMountingPlate>+ Struct MountingPlateTemplate {+ Require PositiveDimensions => P.Width > 0mm && P.Height > 0mm && P.Thickness > 0mm+ Require PositiveMountingHoles => P.HoleDiameter > 0mm && P.CounterboreDiameter > P.HoleDiameter && P.CounterboreDepth > 0mm+ Require CounterboreLeavesFloor => P.CounterboreDepth < P.Thickness+ Require HoleSpacingXFitsPlate => P.HoleSpacingX < P.Width+ Require HoleSpacingYFitsPlate => P.HoleSpacingY < P.Height+ Concept Struct Layout On XY { Rect2 Stock { Center: [0mm, 0mm]; Size: [P.Width, P.Height] } }+ Profile PlateProfile Using Layout { Loop Outer {+ Segment Bottom { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight } Segment Right { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }+ Segment Top { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft } Segment Left { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }+ } }+ Compose Body {+ Base Plate { Profile: PlateProfile; From: 0mm; To: P.Thickness; Role: Stock }+ Hole<Counterbore> MountSouthWest { On: +Z; Center: [-45mm, -25mm]; Diameter: P.HoleDiameter; CounterboreDiameter: P.CounterboreDiameter; CounterboreDepth: P.CounterboreDepth; End: ThroughAll; Role: MountingHole }+ Hole<Counterbore> MountSouthEast { On: +Z; Center: [45mm, -25mm]; Diameter: P.HoleDiameter; CounterboreDiameter: P.CounterboreDiameter; CounterboreDepth: P.CounterboreDepth; End: ThroughAll; Role: MountingHole }+ Hole<Counterbore> MountNorthEast { On: +Z; Center: [45mm, 25mm]; Diameter: P.HoleDiameter; CounterboreDiameter: P.CounterboreDiameter; CounterboreDepth: P.CounterboreDepth; End: ThroughAll; Role: MountingHole }+ Hole<Counterbore> MountNorthWest { On: +Z; Center: [-45mm, 25mm]; Diameter: P.HoleDiameter; CounterboreDiameter: P.CounterboreDiameter; CounterboreDepth: P.CounterboreDepth; End: ThroughAll; Role: MountingHole }+ }+ Pmi {+ Datum A { Target: face(+Z) }+ HoleDiameter MountingHoleDiameter {+ Target: MountSouthWest+ Value: P.HoleDiameter+ Tolerance: PlusMinus(0.10mm, 0.00mm)+ DatumRefs: [A]+ }+ }+ }++ Record BearingBlockPolicy { BaseWidth: Length BaseDepth: Length BaseThickness: Length BossDiameter: Length BossHeight: Length BoreDiameter: Length MountSpacing: Length MountHoleDiameter: Length Material: String }+ Static StandardBearingBlock: BearingBlockPolicy = BearingBlockPolicy { BaseWidth: 100mm BaseDepth: 50mm BaseThickness: 14mm BossDiameter: 36mm BossHeight: 18mm BoreDiameter: 20mm MountSpacing: 72mm MountHoleDiameter: 8.5mm Material: "Standard.Materials.Aluminum.6061_T6" }+ Template<P: BearingBlockPolicy = StandardBearingBlock>+ Struct BearingBlockTemplate {+ Require PositiveDimensions => P.BaseWidth > 0mm && P.BaseDepth > 0mm && P.BaseThickness > 0mm && P.BossHeight > 0mm+ Require BoreFitsBoss => P.BoreDiameter > 0mm && P.BoreDiameter < P.BossDiameter+ Require BossFitsBase => P.BossDiameter < P.BaseDepth+ Require PositiveMountHoles => P.MountHoleDiameter > 0mm+ Require MountSpacingFitsBase => P.MountSpacing < P.BaseWidth+ Concept Struct Layout On XY {+ Rect2 Stock { Center: [0mm, 0mm]; Size: [P.BaseWidth, P.BaseDepth] }+ Point2 BossCenter { Position: [0mm, 0mm] }+ Point2 BossEast { Position: [18mm, 0mm] } Point2 BossNorth { Position: [0mm, 18mm] }+ Point2 BossWest { Position: [-18mm, 0mm] } Point2 BossSouth { Position: [0mm, -18mm] }+ Circle2 BossCircle { Center: BossCenter; Radius: 18mm }+ }+ Profile BaseProfile Using Layout { Loop Outer {+ Segment Bottom { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight } Segment Right { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }+ Segment Top { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft } Segment Left { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }+ } }+ Profile BossProfile Using Layout { Loop Outer {+ Segment Q1 { Trace: BossCircle; From: BossEast; To: BossNorth; Sweep: CounterClockwise } Segment Q2 { Trace: BossCircle; From: BossNorth; To: BossWest; Sweep: CounterClockwise }+ Segment Q3 { Trace: BossCircle; From: BossWest; To: BossSouth; Sweep: CounterClockwise } Segment Q4 { Trace: BossCircle; From: BossSouth; To: BossEast; Sweep: CounterClockwise }+ } }+ Compose Body {+ Base Stock { Profile: BaseProfile; From: 0mm; To: P.BaseThickness; Role: Stock }+ Boss BearingBoss { On: Top; Profile: BossProfile; Height: P.BossHeight }+ Hole<Shaft> BearingBore { On: +Z; Center: [0mm, 0mm]; Diameter: P.BoreDiameter; End: ThroughAll; Role: ShaftBore }+ Hole<Shaft> MountLeft { On: +Z; Center: [-36mm, 0mm]; Diameter: P.MountHoleDiameter; End: ThroughAll; Role: MountingHole }+ Hole<Shaft> MountRight { On: +Z; Center: [36mm, 0mm]; Diameter: P.MountHoleDiameter; End: ThroughAll; Role: MountingHole }+ }+ Pmi {+ Datum A { Target: face(+Z) }+ HoleDiameter BoreDiameter {+ Target: BearingBore+ Value: P.BoreDiameter+ Tolerance: PlusMinus(0.05mm, 0.02mm)+ DatumRefs: [A]+ }+ }+ }++ Record MachinedAngleBracketPolicy { Width: Length Height: Length LegWidth: Length Thickness: Length HoleDiameter: Length Material: String }+ Static StandardMachinedAngleBracket: MachinedAngleBracketPolicy = MachinedAngleBracketPolicy { Width: 80mm Height: 60mm LegWidth: 20mm Thickness: 10mm HoleDiameter: 8.5mm Material: "Standard.Materials.Steel.ASTM_A36" }+ Template<P: MachinedAngleBracketPolicy = StandardMachinedAngleBracket>+ Struct MachinedAngleBracketTemplate {+ Require PositiveDimensions => P.Width > 0mm && P.Height > 0mm && P.LegWidth > 0mm && P.Thickness > 0mm+ Require LegFits => P.LegWidth < P.Width && P.LegWidth < P.Height+ Require HolesFitLeg => P.HoleDiameter > 0mm && P.HoleDiameter < P.LegWidth+ Concept Path Outline { Start: Point2(0mm, 0mm) Heading: 0deg Line South { Length: P.Width } Line EastShort { Turn: 90deg; Length: P.LegWidth } Line InnerWest { Turn: 90deg; Length: P.Width - P.LegWidth } Line InnerNorth { Turn: -90deg; Length: P.Height - P.LegWidth } Line North { Turn: 90deg; Length: P.LegWidth } Close West }+ Profile BracketProfile From Outline+ Compose Body {+ Base Stock { Profile: BracketProfile; From: 0mm; To: P.Thickness; Role: Stock }+ Hole<Shaft> HorizontalMount { On: +Z; Center: [70mm, 10mm]; Diameter: P.HoleDiameter; End: ThroughAll; Role: MountingHole }+ Hole<Shaft> VerticalMount { On: +Z; Center: [10mm, 50mm]; Diameter: P.HoleDiameter; End: ThroughAll; Role: MountingHole }+ }+ }++ Record ShaftCollarPolicy { OuterDiameter: Length BoreDiameter: Length Width: Length Material: String }+ Static StandardShaftCollar: ShaftCollarPolicy = ShaftCollarPolicy { OuterDiameter: 32mm BoreDiameter: 16mm Width: 12mm Material: "Standard.Materials.StainlessSteel.304_Annealed" }+ Template<P: ShaftCollarPolicy = StandardShaftCollar>+ Struct ShaftCollarTemplate {+ Require PositiveDimensions => P.OuterDiameter > 0mm && P.BoreDiameter > 0mm && P.Width > 0mm+ Require BoreFitsBody => P.BoreDiameter < P.OuterDiameter+ Concept Struct Layout On XY {+ Point2 Center { Position: [0mm, 0mm] } Point2 East { Position: [16mm, 0mm] }+ Point2 North { Position: [0mm, 16mm] } Point2 West { Position: [-16mm, 0mm] }+ Point2 South { Position: [0mm, -16mm] } Circle2 Outer { Center: Center; Radius: 16mm }+ }+ Profile CollarProfile Using Layout { Loop Outer {+ Segment Q1 { Trace: Outer; From: East; To: North; Sweep: CounterClockwise } Segment Q2 { Trace: Outer; From: North; To: West; Sweep: CounterClockwise }+ Segment Q3 { Trace: Outer; From: West; To: South; Sweep: CounterClockwise } Segment Q4 { Trace: Outer; From: South; To: East; Sweep: CounterClockwise }+ } }+ Compose Body { Base Collar { Profile: CollarProfile; From: 0mm; To: P.Width; Role: Stock } Hole<Shaft> Bore { On: +Z; Center: [0mm, 0mm]; Diameter: P.BoreDiameter; End: ThroughAll; Role: ShaftBore } }+ }++ Record FlangedAdapterPolicy { OuterDiameter: Length BodyThickness: Length BoreDiameter: Length BoltHoleDiameter: Length BoltCount: int Material: String }+ Static StandardFlangedAdapter: FlangedAdapterPolicy = FlangedAdapterPolicy { OuterDiameter: 80mm BodyThickness: 12mm BoreDiameter: 30mm BoltHoleDiameter: 6.6mm BoltCount: 6 Material: "Standard.Materials.Aluminum.6061_T6" }+ Template<P: FlangedAdapterPolicy = StandardFlangedAdapter>+ Struct FlangedAdapterTemplate {+ Require PositiveDimensions => P.OuterDiameter > 0mm && P.BodyThickness > 0mm && P.BoreDiameter > 0mm && P.BoltHoleDiameter > 0mm+ Require BoreFitsBody => P.BoreDiameter < P.OuterDiameter+ Require FixedBoltCircleFitsFlange => P.OuterDiameter > 52mm+ Require BoltCountMinimum => P.BoltCount >= 4+ Require BoltCountMaximum => P.BoltCount <= 8+ Record BoltSpec { Center: Point2 }+ Static Bolt4: BoltSpec[] = [+ BoltSpec { Center: Point2(22mm, 0mm) } BoltSpec { Center: Point2(0mm, 22mm) }+ BoltSpec { Center: Point2(-22mm, 0mm) } BoltSpec { Center: Point2(0mm, -22mm) }+ ]+ Static Bolt6: BoltSpec[] = [+ BoltSpec { Center: Point2(22mm, 0mm) } BoltSpec { Center: Point2(11mm, 19.052558883mm) }+ BoltSpec { Center: Point2(-11mm, 19.052558883mm) } BoltSpec { Center: Point2(-22mm, 0mm) }+ BoltSpec { Center: Point2(-11mm, -19.052558883mm) } BoltSpec { Center: Point2(11mm, -19.052558883mm) }+ ]+ Static Bolt8: BoltSpec[] = [+ BoltSpec { Center: Point2(22mm, 0mm) } BoltSpec { Center: Point2(15.556349186mm, 15.556349186mm) }+ BoltSpec { Center: Point2(0mm, 22mm) } BoltSpec { Center: Point2(-15.556349186mm, 15.556349186mm) }+ BoltSpec { Center: Point2(-22mm, 0mm) } BoltSpec { Center: Point2(-15.556349186mm, -15.556349186mm) }+ BoltSpec { Center: Point2(0mm, -22mm) } BoltSpec { Center: Point2(15.556349186mm, -15.556349186mm) }+ ]+ Template<spec: BoltSpec> FlangeBolt { Hole<Shaft> Bolt { On: +Z; Center: spec.Center; Diameter: P.BoltHoleDiameter; End: ThroughAll; Role: MountingHole } }+ Concept Struct Layout On XY {+ Point2 Center { Position: [0mm, 0mm] } Point2 East { Position: [40mm, 0mm] }+ Point2 North { Position: [0mm, 40mm] } Point2 West { Position: [-40mm, 0mm] }+ Point2 South { Position: [0mm, -40mm] } Circle2 Outer { Center: Center; Radius: 40mm }+ }+ Profile FlangeProfile Using Layout { Loop Outer {+ Segment Q1 { Trace: Outer; From: East; To: North; Sweep: CounterClockwise } Segment Q2 { Trace: Outer; From: North; To: West; Sweep: CounterClockwise }+ Segment Q3 { Trace: Outer; From: West; To: South; Sweep: CounterClockwise } Segment Q4 { Trace: Outer; From: South; To: East; Sweep: CounterClockwise }+ } }+ Compose Body {+ Base Flange { Profile: FlangeProfile; From: 0mm; To: P.BodyThickness; Role: Stock }+ Hole<Shaft> Bore { On: +Z; Center: [0mm, 0mm]; Diameter: P.BoreDiameter; End: ThroughAll; Role: ShaftBore }+ Pattern BoltPattern Over Match P.BoltCount {+ 4 => Bolt4+ 6 => Bolt6+ 8 => Bolt8+ } { FlangeBolt<Current> }+ }+ Pmi {+ Datum A { Target: face(+Z) }+ HoleDiameter BoreDiameter {+ Target: Bore+ Value: P.BoreDiameter+ Tolerance: PlusMinus(0.10mm, 0.00mm)+ DatumRefs: [A]+ }+ }+ }++ Record RackPanelPolicy { Width: Length Height: Length Thickness: Length MountHoleDiameter: Length MountInset: Length Material: String }+ Static StandardRackPanel: RackPanelPolicy = RackPanelPolicy { Width: 482.6mm Height: 44.45mm Thickness: 3mm MountHoleDiameter: 6.5mm MountInset: 12.7mm Material: "Standard.Materials.Aluminum.5052_H32" }+ Template<P: RackPanelPolicy = StandardRackPanel>+ Struct RackPanelTemplate {+ Require PositiveDimensions => P.Width > 0mm && P.Height > 0mm && P.Thickness > 0mm && P.MountHoleDiameter > 0mm+ Require MountInsetFitsWidth => P.MountInset < P.Width+ Require MountingHoleFitsHeight => P.MountHoleDiameter < P.Height+ Concept Struct Layout On XY { Rect2 Stock { Center: [0mm, 0mm]; Size: [P.Width, P.Height] } }+ Profile PanelProfile Using Layout { Loop Outer {+ Segment Bottom { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight } Segment Right { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }+ Segment Top { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft } Segment Left { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }+ } }+ Compose Body {+ Base Panel { Profile: PanelProfile; From: 0mm; To: P.Thickness; Role: Stock }+ Hole<Shaft> MountLeft { On: +Z; Center: [-228.6mm, 0mm]; Diameter: P.MountHoleDiameter; End: ThroughAll; Role: MountingHole }+ Hole<Shaft> MountRight { On: +Z; Center: [228.6mm, 0mm]; Diameter: P.MountHoleDiameter; End: ThroughAll; Role: MountingHole }+ }+ }++ Record StandoffPolicy { OuterDiameter: Length Length: Length BoreDiameter: Length Material: String }+ Static StandardStandoff: StandoffPolicy = StandoffPolicy { OuterDiameter: 10mm Length: 25mm BoreDiameter: 4.2mm Material: "Standard.Materials.StainlessSteel.304_Annealed" }+ Template<P: StandoffPolicy = StandardStandoff>+ Struct StandoffTemplate {+ Require PositiveDimensions => P.OuterDiameter > 0mm && P.Length > 0mm && P.BoreDiameter > 0mm+ Require BoreFitsBody => P.BoreDiameter < P.OuterDiameter+ Concept Struct Layout On XY {+ Point2 Center { Position: [0mm, 0mm] } Point2 East { Position: [5mm, 0mm] }+ Point2 North { Position: [0mm, 5mm] } Point2 West { Position: [-5mm, 0mm] }+ Point2 South { Position: [0mm, -5mm] } Circle2 Outer { Center: Center; Radius: 5mm }+ }+ Profile StandoffProfile Using Layout { Loop Outer {+ Segment Q1 { Trace: Outer; From: East; To: North; Sweep: CounterClockwise } Segment Q2 { Trace: Outer; From: North; To: West; Sweep: CounterClockwise }+ Segment Q3 { Trace: Outer; From: West; To: South; Sweep: CounterClockwise } Segment Q4 { Trace: Outer; From: South; To: East; Sweep: CounterClockwise }+ } }+ Compose Body { Base Standoff { Profile: StandoffProfile; From: 0mm; To: P.Length; Role: Stock } Hole<Shaft> Bore { On: +Z; Center: [0mm, 0mm]; Diameter: P.BoreDiameter; End: ThroughAll; Role: FastenerClearance } }+ }+}diff --git a/Aetheris.Server.Tests/Aetheris.Server.Tests.csproj b/Aetheris.Server.Tests/Aetheris.Server.Tests.csprojindex feda50f5..9efad065 100644--- a/Aetheris.Server.Tests/Aetheris.Server.Tests.csproj+++ b/Aetheris.Server.Tests/Aetheris.Server.Tests.csproj@@ -19,5 +19,6 @@<ItemGroup><ProjectReference Include="..\Aetheris.Server\Aetheris.Server.csproj" />+ <ProjectReference Include="..\Aetheris.Forge.Host\Aetheris.Forge.Host.csproj" /></ItemGroup></Project>diff --git a/Aetheris.Server.Tests/StandardProductGalleryIntegrationTests.cs b/Aetheris.Server.Tests/StandardProductGalleryIntegrationTests.csnew file mode 100644index 00000000..fc124d41--- /dev/null+++ b/Aetheris.Server.Tests/StandardProductGalleryIntegrationTests.cs@@ -0,0 +1,59 @@+using System.Net.Http.Json;+using System.Text.Json;+using Aetheris.Forge.Host;+using Aetheris.Server.Api;+using Aetheris.Server.Contracts;+using Microsoft.AspNetCore.Mvc.Testing;++namespace Aetheris.Server.Tests;++public sealed class StandardProductGalleryIntegrationTests : IClassFixture<WebApplicationFactory<Program>>+{+ private readonly HttpClient client;++ public StandardProductGalleryIntegrationTests(WebApplicationFactory<Program> factory) => client = factory.CreateClient();++ [Fact]+ public async Task GalleryDiscoversSchemasAndReturnsTheDownloadableGeneratedStep()+ {+ var catalog = await client.GetFromJsonAsync<ApiResponseDto<ForgeTemplateDescription[]>>("/api/v1/gallery/templates");+ Assert.True(catalog!.Success);+ Assert.Contains(catalog.Data!, item => item.Id == "Standard.Products.Mechanical.MountingPlate");+ Assert.Contains(catalog.Data!, item => item.Id == "Standard.SheetMetal.ElectronicsEnclosure");++ var values = new Dictionary<string, object?>+ {+ ["width"] = "120 mm", ["height"] = "80 mm", ["thickness"] = "10 mm",+ ["holeDiameter"] = "6.6 mm", ["holeSpacingX"] = "90 mm", ["holeSpacingY"] = "50 mm",+ ["counterboreDiameter"] = "11 mm", ["counterboreDepth"] = "4 mm",+ ["material"] = "Standard.Materials.Aluminum.6061_T6",+ };+ var request = new GalleryInvocationRequest(values.ToDictionary(pair => pair.Key,+ pair => JsonSerializer.SerializeToElement(pair.Value), StringComparer.Ordinal), [ForgeArtifactKind.StepAp242]);+ var response = await client.PostAsJsonAsync("/api/v1/gallery/templates/Standard.Products.Mechanical.MountingPlate", request);+ response.EnsureSuccessStatusCode();+ var envelope = await response.Content.ReadFromJsonAsync<ApiResponseDto<GalleryInvocationResponse>>();+ var artifact = Assert.Single(envelope!.Data!.Artifacts);+ Assert.Contains("ISO-10303-21", artifact.Content, StringComparison.Ordinal);+ Assert.Equal("part.step", artifact.Name);+ }++ [Fact]+ public async Task GalleryPreservesEngineeringConstraintDiagnostics()+ {+ var values = new Dictionary<string, object?>+ {+ ["width"] = "120 mm", ["height"] = "80 mm", ["thickness"] = "10 mm",+ ["holeDiameter"] = "6.6 mm", ["holeSpacingX"] = "121 mm", ["holeSpacingY"] = "50 mm",+ ["counterboreDiameter"] = "11 mm", ["counterboreDepth"] = "4 mm",+ ["material"] = "Standard.Materials.Aluminum.6061_T6",+ };+ var request = new GalleryInvocationRequest(values.ToDictionary(pair => pair.Key,+ pair => JsonSerializer.SerializeToElement(pair.Value), StringComparer.Ordinal), [ForgeArtifactKind.StepAp242]);+ var response = await client.PostAsJsonAsync("/api/v1/gallery/templates/Standard.Products.Mechanical.MountingPlate", request);+ Assert.Equal(System.Net.HttpStatusCode.UnprocessableEntity, response.StatusCode);+ var envelope = await response.Content.ReadFromJsonAsync<ApiResponseDto<GalleryInvocationResponse>>();+ Assert.False(envelope!.Success);+ Assert.Contains(envelope.Diagnostics, item => item.Message.Contains("HoleSpacingXFitsPlate", StringComparison.Ordinal));+ }+}diff --git a/Aetheris.Server/Aetheris.Server.csproj b/Aetheris.Server/Aetheris.Server.csprojindex d5d12cea..bbccc1aa 100644--- a/Aetheris.Server/Aetheris.Server.csproj+++ b/Aetheris.Server/Aetheris.Server.csproj@@ -21,6 +21,7 @@<ItemGroup><ProjectReference Include="..\Aetheris.Kernel.Core\Aetheris.Kernel.Core.csproj" /><ProjectReference Include="..\Aetheris.Kernel.Firmament\Aetheris.Kernel.Firmament.csproj" />+ <ProjectReference Include="..\Aetheris.Forge.Host\Aetheris.Forge.Host.csproj" /></ItemGroup><ItemGroup Condition="Exists('$(SpaRoot)dist')">diff --git a/Aetheris.Server/Api/StandardProductGalleryEndpoints.cs b/Aetheris.Server/Api/StandardProductGalleryEndpoints.csnew file mode 100644index 00000000..3ead6730--- /dev/null+++ b/Aetheris.Server/Api/StandardProductGalleryEndpoints.cs@@ -0,0 +1,69 @@+using System.Text.Json;+using Aetheris.Forge.Host;+using Aetheris.Server.Contracts;++namespace Aetheris.Server.Api;++public sealed record GalleryInvocationRequest(+ IReadOnlyDictionary<string, JsonElement>? Arguments,+ IReadOnlyList<ForgeArtifactKind>? Artifacts);++public sealed record GalleryArtifactContent(+ ForgeArtifactKind Kind,+ string Name,+ string ContentType,+ long Size,+ string Sha256,+ string Content);++public sealed record GalleryInvocationResponse(+ bool Success,+ ForgeInvocationIdentity Identity,+ IReadOnlyList<ForgeProtocolDiagnostic> Diagnostics,+ IReadOnlyList<GalleryArtifactContent> Artifacts,+ double ExecutionMilliseconds);++public static class StandardProductGalleryEndpoints+{+ public static void MapStandardProductGalleryApi(this WebApplication app)+ {+ app.MapGet("/api/v1/gallery/templates", () =>+ {+ var host = new ForgeProtocolHost();+ var descriptions = host.ListTemplates().Templates+ .Where(item => item.Id.StartsWith("Standard.Products.", StringComparison.Ordinal)+ || item.Id == "Standard.SheetMetal.ElectronicsEnclosure")+ .Select(item => host.DescribeTemplate(item.Id)!)+ .ToArray();+ return ApiMappings.Ok(descriptions);+ });++ app.MapPost("/api/v1/gallery/templates/{**templateId}", (string templateId, GalleryInvocationRequest request) =>+ {+ var output = Path.Combine(Path.GetTempPath(), "aetheris-gallery-" + Guid.NewGuid().ToString("N"));+ try+ {+ var result = new ForgeProtocolHost().InvokeTemplate(templateId,+ new ForgeTemplateInvocationRequest(ForgeHostProtocol.Version, request.Arguments, request.Artifacts), output);+ var artifacts = result.Artifacts.Select(artifact =>+ {+ var path = Path.Combine(output, artifact.Path);+ return new GalleryArtifactContent(artifact.Kind, artifact.Name, artifact.ContentType,+ artifact.Size, artifact.Sha256, File.ReadAllText(path));+ }).ToArray();+ var response = new GalleryInvocationResponse(result.Success, result.Identity, result.Diagnostics,+ artifacts, result.ExecutionMilliseconds);+ return result.Success+ ? ApiMappings.Ok(response)+ : Results.Json(new ApiResponseDto<GalleryInvocationResponse>(false, response,+ result.Diagnostics.Select(item => new DiagnosticDto(item.Code, item.Severity.ToString(), item.Message,+ item.Source ?? item.Target)).ToArray()),+ statusCode: StatusCodes.Status422UnprocessableEntity);+ }+ finally+ {+ if (Directory.Exists(output)) Directory.Delete(output, true);+ }+ });+ }+}diff --git a/Aetheris.Server/Program.cs b/Aetheris.Server/Program.csindex 5164d030..7cb49e02 100644--- a/Aetheris.Server/Program.cs+++ b/Aetheris.Server/Program.cs@@ -63,6 +63,7 @@ if (app.Environment.IsDevelopment())app.MapKernelApi();app.MapCadmataStartupApi();app.MapPaperclipDemoApi();+app.MapStandardProductGalleryApi();app.UseDefaultFiles();app.UseStaticFiles();diff --git a/Aetheris.SheetMetal/Firmament/SheetMetalProductFamilies.firmament b/Aetheris.SheetMetal/Firmament/SheetMetalProductFamilies.firmamentindex f480e09f..7c5636e7 100644--- a/Aetheris.SheetMetal/Firmament/SheetMetalProductFamilies.firmament+++ b/Aetheris.SheetMetal/Firmament/SheetMetalProductFamilies.firmament@@ -92,7 +92,15 @@ Record EnclosureSpec {ReliefPolicy: SheetMetalReliefPolicy}-Template<Spec: LBracketSpec>+// Canonical gallery/client defaults. These records are the single source used by+// template binding, Forge describe, and zero-argument invocation.+Static StandardLBracket: LBracketSpec = LBracketSpec { Width: 100mm Depth: 60mm FlangeHeight: 30mm Thickness: 2mm InsideRadius: 2mm KFactor: 0.42 ReliefPolicy: Auto }+Static StandardUChannel: UChannelSpec = UChannelSpec { Width: 100mm Depth: 60mm WallHeight: 30mm Thickness: 2mm InsideRadius: 2mm KFactor: 0.42 ReliefPolicy: Auto }+Static StandardFourWallTray: TraySpec = TraySpec { Width: 120mm Depth: 80mm WallHeight: 25mm Thickness: 2mm InsideRadius: 2mm KFactor: 0.42 ReliefPolicy: Auto }+Static StandardRemovablePanLid: LidSpec = LidSpec { Width: 120mm Depth: 80mm SkirtHeight: 15mm Clearance: 0.5mm Thickness: 2mm InsideRadius: 2mm KFactor: 0.42 ReliefPolicy: Auto }+Static StandardElectronicsEnclosure: EnclosureSpec = EnclosureSpec { Width: 120mm Depth: 80mm Height: 40mm LidLipHeight: 8mm Thickness: 1.5mm InsideRadius: 2mm KFactor: 0.42 ReliefPolicy: Rectangular }++Template<Spec: LBracketSpec = StandardLBracket>SheetMetal LBracket: SheetMetalPart {Require Positive => Spec.Width > 0mm && Spec.Depth > 0mm && Spec.FlangeHeight > 0mm && Spec.Thickness > 0mmThickness: Spec.Thickness;@@ -101,7 +109,7 @@ SheetMetal LBracket: SheetMetalPart {Flange Wall { From: Base.Front; Height: Spec.FlangeHeight; Angle: 90deg; Radius: Spec.InsideRadius; Relief: Spec.ReliefPolicy; }}-Template<Spec: UChannelSpec>+Template<Spec: UChannelSpec = StandardUChannel>SheetMetal UChannel: SheetMetalPart {Require Positive => Spec.Width > 0mm && Spec.Depth > 0mm && Spec.WallHeight > 0mm && Spec.Thickness > 0mmThickness: Spec.Thickness;@@ -111,7 +119,7 @@ SheetMetal UChannel: SheetMetalPart {Flange RightWall { From: Base.Right; Height: Spec.WallHeight; Angle: 90deg; Radius: Spec.InsideRadius; Relief: Spec.ReliefPolicy; }}-Template<Spec: TraySpec>+Template<Spec: TraySpec = StandardFourWallTray>SheetMetal FourWallTray: Tray {Require Positive => Spec.Width > 0mm && Spec.Depth > 0mm && Spec.WallHeight > 0mm && Spec.Thickness > 0mmRequire ManufacturableWall => Spec.WallHeight > Spec.InsideRadius@@ -124,7 +132,7 @@ SheetMetal FourWallTray: Tray {Flange Left { From: Base.Left; Height: Spec.WallHeight; Angle: 90deg; Radius: Spec.InsideRadius; Relief: Spec.ReliefPolicy; }}-Template<Spec: LidSpec>+Template<Spec: LidSpec = StandardRemovablePanLid>SheetMetal RemovablePanLid: RemovableLid {Require Positive => Spec.Width > 0mm && Spec.Depth > 0mm && Spec.SkirtHeight > 0mm && Spec.Thickness > 0mmThickness: Spec.Thickness;@@ -136,7 +144,7 @@ SheetMetal RemovablePanLid: RemovableLid {Flange Left { From: Top.Left; Height: Spec.SkirtHeight; Angle: 90deg; Radius: Spec.InsideRadius; Direction: Down; Relief: Spec.ReliefPolicy; }}-Template<Spec: EnclosureSpec>+Template<Spec: EnclosureSpec = StandardElectronicsEnclosure>SheetMetal ElectronicsEnclosure: Enclosure {Require Positive => Spec.Width > 0mm && Spec.Depth > 0mm && Spec.Height > 0mm && Spec.Thickness > 0mmRequire LipFits => Spec.LidLipHeight > Spec.InsideRadiusdiff --git a/aetheris.client/src/App.css b/aetheris.client/src/App.cssindex 745cfb70..7e2cdbf5 100644--- a/aetheris.client/src/App.css+++ b/aetheris.client/src/App.css@@ -661,3 +661,37 @@ strong {letter-spacing: 0.02em;color: hsl(var(--muted-foreground));}++.product-gallery {+ display: grid;+ gap: 10px;+}++.product-gallery__eyebrow {+ font-size: var(--ui-small);+ letter-spacing: 0.12em;+ color: var(--shell-accent);+}++.product-gallery__cards {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: 6px;+}++.product-card {+ display: grid;+ gap: 3px;+ text-align: left;+ min-height: 54px;+ padding: 8px;+}++.product-card span {+ font-size: var(--ui-small);+ color: var(--shell-text-secondary);+}++.product-gallery__form {+ grid-template-columns: repeat(2, minmax(0, 1fr));+}diff --git a/aetheris.client/src/App.tsx b/aetheris.client/src/App.tsxindex a3c7be1e..f94f4521 100644--- a/aetheris.client/src/App.tsx+++ b/aetheris.client/src/App.tsx@@ -34,6 +34,7 @@ import {type PaperclipDemoResponseDto,} from "./api/aetherisApi";import { StepImportDropzone } from "./components/StepImportDropzone";+import { ProductGallery } from "./components/ProductGallery";import { PropertyTable, type PropertyRecord } from "./components/PropertyTable";import { SemanticInspector } from "./components/SemanticInspector";import { Button } from "./components/ui/button";@@ -62,7 +63,7 @@ import { DEFAULT_PMI_VISIBILITY, type PmiCategory, type PmiVisibility } from "./type RequestStatus = "idle" | "loading" | "success" | "error";type BooleanOperationUi = "Union" | "Subtract" | "Intersect";-type TopLevelTab = "viewer" | "paperclips" | "modeling-demo";+type TopLevelTab = "gallery" | "viewer" | "paperclips" | "modeling-demo";type ServerStatus = "connecting" | "connected" | "disconnected" | "error";type DocumentStatus = "creating" | "ready" | "error";type ImportStatus = "idle" | "creating" | "importing" | "success" | "error";@@ -995,6 +996,16 @@ function App() {</div><div className="top-bar__tabs-row"><div className="top-bar__tabs" role="tablist" aria-label="Top-level product surface">+ <Button+ type="button"+ role="tab"+ variant={activeTab === "gallery" ? "default" : "secondary"}+ aria-selected={activeTab === "gallery"}+ className={activeTab === "gallery" ? "tab-button active" : "tab-button"}+ onClick={() => setActiveTab("gallery")}+ >+ Product Gallery+ </Button><Buttontype="button"role="tab"@@ -1461,6 +1472,8 @@ function App() {) : null}</section></>+ ) : activeTab === "gallery" ? (+ <ProductGallery onPreview={async (step, name) => { await importStepText(step, name); }} />) : activeTab === "paperclips" ? (<section className="tool-section paperclip-forge"><p className="paperclip-forge__eyebrow">OBJECTIVE: MAKE PAPERCLIPS.</p>diff --git a/aetheris.client/src/api/aetherisApi.ts b/aetheris.client/src/api/aetherisApi.tsindex 9960dda8..abd234d7 100644--- a/aetheris.client/src/api/aetherisApi.ts+++ b/aetheris.client/src/api/aetherisApi.ts@@ -89,6 +89,12 @@ export interface PaperclipDemoResponseDto {deterministic: boolean;}+export type ForgeArtifactKindDto = "StepAp242" | "FlatStep" | "Svg";+export interface ForgeTemplateParameterDto { name: string; type: string; required: boolean; default?: string | null; dimension?: string | null; unit?: string | null; allowedValues?: string[] | null; fields?: ForgeTemplateParameterDto[] | null; category: string; constraint?: string | null; }+export interface ForgeTemplateDescriptionDto { id: string; displayName: string; version: string; documentation: string; parameters: ForgeTemplateParameterDto[]; artifacts: ForgeArtifactKindDto[]; signature: string; outputKind: string; constraints: { name: string; expression: string }[]; }+export interface GalleryArtifactDto { kind: ForgeArtifactKindDto; name: string; contentType: string; size: number; sha256: string; content: string; }+export interface GalleryInvocationResponseDto { success: boolean; identity: { template: string; templateVersion: string; specialization?: string | null }; diagnostics: { code: string; severity: string; message: string; target?: string | null }[]; artifacts: GalleryArtifactDto[]; executionMilliseconds: number; }+export type BooleanOperation = "union" | "subtract" | "intersect";export interface BooleanRequestDto {@@ -595,6 +601,16 @@ export async function maximizePaperclips(});}+export async function listGalleryTemplates(): Promise<ForgeTemplateDescriptionDto[]> {+ return request<ForgeTemplateDescriptionDto[]>("/api/v1/gallery/templates", {});+}++export async function invokeGalleryTemplate(templateId: string, parameters: Record<string, unknown>, artifacts: ForgeArtifactKindDto[]): Promise<GalleryInvocationResponseDto> {+ return request<GalleryInvocationResponseDto>(`/api/v1/gallery/templates/${encodeURIComponent(templateId)}`, {+ method: "POST", body: JSON.stringify({ arguments: parameters, artifacts }),+ });+}+export async function prepareAssemblyDisplay(path: string): Promise<AssemblyDisplayPacketDto> {return request<AssemblyDisplayPacketDto>("/api/v1/assemblies/display", {method: "POST",diff --git a/aetheris.client/src/components/ProductGallery.tsx b/aetheris.client/src/components/ProductGallery.tsxnew file mode 100644index 00000000..2c23bb1f--- /dev/null+++ b/aetheris.client/src/components/ProductGallery.tsx@@ -0,0 +1,47 @@+import { useEffect, useMemo, useState } from "react";+import { ApiError, invokeGalleryTemplate, listGalleryTemplates, type ForgeTemplateDescriptionDto, type GalleryArtifactDto } from "../api/aetherisApi";+import { Button } from "./ui/button";++const DEFAULT_SELECTED = "Standard.Products.Mechanical.MountingPlate";++function schemaDefaults(template: ForgeTemplateDescriptionDto | undefined): Record<string, string | number> {+ if (!template) return {};+ return Object.fromEntries(template.parameters+ .flatMap((parameter) => parameter.fields ?? [parameter])+ .filter((field) => field.default !== null && field.default !== undefined)+ .map((field) => [field.name, field.type === "number" || field.type === "integer" ? Number(field.default) : field.default!]));+}++function download(artifact: GalleryArtifactDto) {+ const url = URL.createObjectURL(new Blob([artifact.content], { type: artifact.contentType }));+ const anchor = document.createElement("a"); anchor.href = url; anchor.download = artifact.name; anchor.click(); URL.revokeObjectURL(url);+}++export function ProductGallery({ onPreview }: { onPreview: (step: string, name: string) => Promise<void> }) {+ const [templates, setTemplates] = useState<ForgeTemplateDescriptionDto[]>([]);+ const [selectedId, setSelectedId] = useState(DEFAULT_SELECTED);+ const [values, setValues] = useState<Record<string, string | number>>({});+ const [artifacts, setArtifacts] = useState<GalleryArtifactDto[]>([]);+ const [status, setStatus] = useState("Loading Standard Library…");+ const selected = useMemo(() => templates.find((item) => item.id === selectedId), [templates, selectedId]);+ const fields = selected?.parameters.flatMap((parameter) => parameter.fields ?? [parameter]) ?? [];+ useEffect(() => { void listGalleryTemplates().then((items) => { setTemplates(items); setValues(schemaDefaults(items.find((item) => item.id === DEFAULT_SELECTED))); setStatus(`${items.length} product families available.`); }).catch((error: Error) => setStatus(error.message)); }, []);+ const choose = (id: string) => { setSelectedId(id); setValues(schemaDefaults(templates.find((item) => item.id === id))); setArtifacts([]); setStatus("Ready to generate."); };+ const generate = async () => {+ if (!selected) return; setStatus("Generating through Forge.Host…");+ try {+ const result = await invokeGalleryTemplate(selected.id, values, selected.artifacts); setArtifacts(result.artifacts);+ const step = result.artifacts.find((artifact) => artifact.kind === "StepAp242"); if (step) await onPreview(step.content, `${selected.displayName}.step`);+ setStatus(`Generated in ${result.executionMilliseconds.toFixed(1)} ms · SHA256 ${step?.sha256.slice(0, 12) ?? "n/a"}.`);+ } catch (error) {+ const failure = error instanceof ApiError ? error : new ApiError((error as Error).message, []); setStatus(failure.diagnostics.map((item) => item.message).join(" · ") || failure.message);+ }+ };+ return <section className="tool-section product-gallery">+ <p className="product-gallery__eyebrow">AETHERIS STANDARD LIBRARY</p><h2>Engineering Product Gallery</h2>+ <div className="product-gallery__cards">{templates.map((template) => <button type="button" key={template.id} className={template.id === selectedId ? "product-card active-row" : "product-card"} onClick={() => choose(template.id)}><strong>{template.displayName}</strong><span>{template.outputKind === "SheetMetal" ? "formed + flat" : "STEP AP242"}</span></button>)}</div>+ {selected ? <><h3>{selected.displayName}</h3><p>{selected.documentation}</p><div className="form-grid product-gallery__form">+ {fields.map((field) => <label key={field.name}>{field.name}{field.unit ? ` (${field.unit})` : ""}{field.allowedValues ? <select value={String(values[field.name] ?? "")} onChange={(event) => setValues((current) => ({ ...current, [field.name]: event.target.value }))}>{field.allowedValues.map((value) => <option key={value}>{value}</option>)}</select> : <input type="text" value={String(values[field.name] ?? "")} onChange={(event) => setValues((current) => ({ ...current, [field.name]: field.type === "number" ? Number(event.target.value) : event.target.value }))} />}</label>)}+ </div><div className="stack-row"><Button type="button" onClick={() => void generate()}>Generate / Update Part</Button>{artifacts.map((artifact) => <Button key={artifact.kind} type="button" variant="secondary" onClick={() => download(artifact)}>Download {artifact.kind}</Button>)}</div><p role="status" className="demo-notice">{status}</p></> : <p>{status}</p>}+ </section>;+}diff --git a/docs/public/README.md b/docs/public/README.mdindex 098e466d..2d74e343 100644--- a/docs/public/README.md+++ b/docs/public/README.md@@ -5,6 +5,7 @@ This directory is the only authoritative in-repository guide to behavior shippedStart with [Getting Started](getting-started.md), then use these guides:- Firmament: [overview](firmament/overview.md), [language style](firmament/language-style.md), [syntax](firmament/syntax.md), [geometry](firmament/geometry.md), [Circular Sweep](firmament/sweep.md), [Paperclip Template](firmament/paperclip.md), [Templates](firmament/templates.md), [materials](firmament/materials.md), [PMI](firmament/pmi.md), [Sheet Metal](firmament/sheet-metal.md), [FEA](firmament/fea.md), and [STEP import](firmament/step-import.md)+- Standard Library: [product-family index, invocation, authoring, and compatibility](standard-library/README.md)- Interoperability: [Forge Host Protocol v1](forge/interop.md)- Inspection: [Cadmata](cadmata/overview.md) and [Cadmata PMI](cadmata/pmi.md)- Reference: [CLI](reference/cli.md), [targets/selectors](reference/targets.md), [diagnostics](reference/diagnostics.md), [supported features](reference/supported-features.md), [known issues](reference/known-issues.md), and [release notes](reference/release-notes.md)diff --git a/docs/public/standard-library/README.md b/docs/public/standard-library/README.mdnew file mode 100644index 00000000..11693ed2--- /dev/null+++ b/docs/public/standard-library/README.md@@ -0,0 +1,62 @@+# Aetheris Standard Library++The Standard Library is a shipped, curated catalog of typed Firmament product families. Applications discover, describe, and invoke it through Forge Protocol v1; the same invocation produces the STEP loaded by Cadmata and offered for download. Product identities and policy field names are public API and should remain stable within a release line.++| Product family | Public Template ID | Main capabilities |+| --- | --- | --- |+| Paperclip | `Standard.Products.Office.Paperclip` | Path, circular Sweep, material, deterministic AP242 |+| Mounting Plate | `Standard.Products.Mechanical.MountingPlate` | prismatic stock, four counterbores, PMI |+| Bearing Block | `Standard.Products.Mechanical.BearingBlock` | base, Boss, bore, mounting holes, PMI |+| Machined Angle Bracket | `Standard.Products.Mechanical.MachinedAngleBracket` | prismatic L profile, mounting holes |+| Shaft Collar | `Standard.Products.Mechanical.ShaftCollar` | circular profile, bore |+| Flanged Adapter | `Standard.Products.Mechanical.FlangedAdapter` | circular flange, 4/6/8-hole semantic Pattern, bore PMI |+| Rack Panel | `Standard.Products.Electronics.RackPanel` | planar stock, symmetric mounting holes |+| Standoff | `Standard.Products.Mechanical.Standoff` | circular spacer, clearance bore |+| Electronics Enclosure | `Standard.SheetMetal.ElectronicsEnclosure` | Sheet Metal, DFM, formed STEP, flat STEP, SVG |++The namespace taxonomy is intentionally shallow: `Standard.Products.Mechanical`, `.Electronics`, and `.Office` identify ordinary products; the existing `Standard.SheetMetal` namespace remains stable for manufacturing Templates.++## Invoke a family++List and describe schemas before binding values:++```powershell+dotnet run --project Aetheris.Forge.Host -- list+dotnet run --project Aetheris.Forge.Host -- describe Standard.Products.Mechanical.MountingPlate+dotnet run --project Aetheris.Forge.Host -- invoke Standard.Products.Mechanical.MountingPlate --request fixtures/Canonical/Integration/standard-products/mounting-plate.forge.json --out artifacts/local/mounting-plate+```++The request changes policy data, not geometry logic. Lengths are metric strings such as `"120 mm"`. Forge `describe` is authoritative for fields, units, constraints, and artifacts. See the [Forge interop guide](../forge/interop.md).++Forge resolves each Record parameter's default `Static` through the Firmament binder. Each described field therefore carries its canonical default, engineering type, unit, and required status when the value is statically available. `Static` values derived with `with` are reported after overrides have been applied; unresolved compile-time forms have no invented default. This applies to both `Standard.Products.*` and the five existing `Standard.SheetMetal.*` gallery families, so a generic client never needs a parallel engineering-default table.++## Use a family from Firmament++Standalone source imports a bounded shipped namespace with `Use` and keeps family and default identities qualified:++```firmament+Model MyMountingPlate {+ Units: mm+ Use Standard.Products.Mechanical++ Static MyPolicy = Standard.Products.Mechanical.StandardMountingPlate with {+ Width: 120mm+ Height: 80mm+ Material: "Standard.Materials.Aluminum.6061_T6"+ }++ Struct Plate = Standard.Products.Mechanical.MountingPlate<P: MyPolicy>+}+```++X1a resolves only the embedded `Standard.Products.Mechanical`, `.Electronics`, and `.Office` modules. Resolution selects named exports from the semantic catalog; it does not read a path or paste an arbitrary file. Fully qualified symbols avoid shadowing. A local declaration colliding with a selected internal export is rejected, as are unknown modules, declarations, or references whose module was not explicitly used. User-defined modules and dependency cycles remain outside this bounded first release.++## Authoring model++The authoritative shipped module is `Aetheris.Kernel.Firmament/Standard/StandardProducts.firmament`. Every family follows `Record → Static default → Template<Policy> → Require → semantic geometry`. The same embedded source drives Firmament import, Forge discovery/defaults, tests, and Product Gallery controls.++Pattern intent remains in compiler semantic reporting through specialization: identity, source array, generator Template, specialized count, and generated-instance relationships are retained. `aetheris inspect <source> --json` exposes that inventory under `patterns`; `aetheris build <source> --json` includes the same semantic report beside its materialized features. The BRep plan is the deliberate boundary where finite instances become explicit topology. PMI inside one-level and nested Templates is lifted using specialization provenance, bound to the specialized semantic feature, exported to AP242, and checked by reinspection parity.++## Compatibility++Template IDs and policy field identities are public API. Additive fields require defaults before they can be non-breaking; removals, renames, type changes, and semantic reinterpretations require an announced compatibility break. Geometry may be corrected without renaming a family when the policy meaning is preserved.diff --git a/docs/release/X1-STANDARD-LIBRARY.md b/docs/release/X1-STANDARD-LIBRARY.mdnew file mode 100644index 00000000..e134f93f--- /dev/null+++ b/docs/release/X1-STANDARD-LIBRARY.md@@ -0,0 +1,99 @@+# X1 — Standard Library qualification++## Executive verdict++**Meaningful progression, not full X1 acceptance.** Aetheris now ships one authoritative embedded catalog containing eight recognizable native product families. Forge Protocol v1 discovers and describes all eight, invokes seven qualified mechanical/electronics variants through their real Firmament → BRep → AP242 path, and serves the same returned STEP to Cadmata preview and download. The existing Sheet Metal electronics enclosure remains discoverable with formed STEP, flat STEP, SVG, and DFM.++Three language/host gaps prevent an honest full-success verdict: standalone Firmament has no public shipped-module import syntax; Record field defaults are not projected from `Static` into Forge schemas; and Pattern-generated variable product layouts plus nested Template PMI do not survive the current host-specialization route cleanly. Canonical consumer fixtures therefore use Forge requests, gallery defaults remain presentation data, repeated layouts are finite explicit semantic holes, and AP242 reinspection reports no PMI for the new native families. These are recorded rather than hidden behind copied geometry or a parallel schema.++## Product families++| Namespace | Policy / default | Main capability | Output |+| --- | --- | --- | --- |+| `Standard.Products.Office.Paperclip` | `PaperclipPolicy` / `StandardPaperclip` | Path, circular Sweep, material | STEP |+| `Standard.Products.Mechanical.MountingPlate` | `MountingPlatePolicy` / `StandardMountingPlate` | plate, four counterbores | STEP |+| `Standard.Products.Mechanical.BearingBlock` | `BearingBlockPolicy` / `StandardBearingBlock` | base, Boss, bore, mounts | STEP |+| `Standard.Products.Mechanical.MachinedAngleBracket` | `MachinedAngleBracketPolicy` / `StandardMachinedAngleBracket` | L profile, holes | STEP |+| `Standard.Products.Mechanical.ShaftCollar` | `ShaftCollarPolicy` / `StandardShaftCollar` | circular stock, bore | STEP |+| `Standard.Products.Mechanical.FlangedAdapter` | `FlangedAdapterPolicy` / `StandardFlangedAdapter` | flange, bore, fixed six-hole layout | STEP |+| `Standard.Products.Electronics.RackPanel` | `RackPanelPolicy` / `StandardRackPanel` | panel, symmetric mounts | STEP |+| `Standard.Products.Mechanical.Standoff` | `StandoffPolicy` / `StandardStandoff` | circular spacer, bore | STEP |+| `Standard.SheetMetal.ElectronicsEnclosure` | `EnclosureSpec` | formed Sheet Metal, flat pattern, DFM | STEP, flat STEP, SVG |++The authoritative native source is `Aetheris.Kernel.Firmament/Standard/StandardProducts.firmament`, embedded in `Aetheris.Kernel.Firmament.dll`. Forge isolates one Template from that catalog before native geometry-route selection; stable public IDs do not depend on the source file path.++## Architecture and Forge.Host++Families follow typed `Record → Static default → Template<Policy> → Require → semantic geometry`. Material catalog identities are policy values. Forge `list`, `describe`, and `invoke` are the only protocol operations; X1 adds no product-specific RPC. `describe` exposes Record fields, types, metric units, named constraints, output kind, and artifacts. Template versions are deterministic content hashes (`1+<12 hex>`); repeated builds with unchanged catalog source retain IDs and versions.++Canonical language-neutral invocations live under `fixtures/Canonical/Integration/standard-products/`. The invalid mounting-plate fixture isolates `HoleSpacingXFitsPlate` and returns `firmament-template-require-failed` before BRep materialization.++## Demo gallery++Cadmata exposes a Product Gallery tab. It discovers the catalog from `/api/v1/gallery/templates`, derives controls from Forge fields/types/units/enums, invokes `/api/v1/gallery/templates/{id}`, imports the returned `StepAp242` text into the shared viewport, and downloads that exact content. Sheet Metal artifact buttons include formed STEP, flat STEP, and SVG. Diagnostic messages from Forge are displayed without collapsing them to “Generation failed.” Metric units are the only X1 UI.++The Viewer remains the default tab to preserve the established file-opening workflow; the gallery is a sibling first-class surface. Paperclip retains its separate `MAXIMUM PAPERCLIPS` action and copy.++## Geometry and determinism evidence++All rows below were invoked twice by `StandardProductLibraryTests`, produced identical specialization identities and SHA-256 values, reimported successfully, and were independently inspected with `Aetheris.CLI inspect --json` as one enclosed manifold body.++| Family | Faces | Plane / cylinder | Bounds mm | SHA-256 |+| --- | ---: | ---: | --- | --- |+| Mounting Plate | 46 | 14 / 32 | `120 × 80 × 10` | `410b0e65f38fbc614a8cd5ffaaa45d1ed71de411500f551521bc0032d288b0ef` |+| Bearing Block | 27 | 7 / 20 | `100 × 50 × 32` | `845ef9d729f7fe5d8abcc3d94579959ac2f1fc37e8599f0ad29d1205998edb93` |+| Machined Angle Bracket | 16 | 8 / 8 | `80 × 60 × 10` | `a70a28a94b6c7e828b1ab62a8b9d0f12d79cd28ca622c343179fb6c63002639c` |+| Shaft Collar | 10 | 2 / 8 | `32 × 32 × 12` | `4fdf4905c3b3609ec52691398bea1701d0283c69e126a6b7f4c8e44e1b010311` |+| Flanged Adapter | 34 | 2 / 32 | `80 × 80 × 12` | `e2ed047e3774464d341019ac241a8b9b7e91280cd05d5c9f9db1790b6af7cdf9` |+| Rack Panel | 14 | 6 / 8 | `482.6 × 44.45 × 3` | `c3ac407c2982e295ee16fb33b353eec2506f0acaa0d1a75d28e5bb7a84f43849` |+| Standoff | 10 | 2 / 8 | `10 × 10 × 25` | `93c4e755bd2289cfac223c6f5434a5cba3a80c1968168ea15381d6f0cfbd939b` |++The inspected native STEP files reported `datumCount=0` and `dimensionCount=0`; source-level nested PMI is therefore not claimed as qualified output.++## Capability coverage++| Family | Template | Boss | Hole / Counterbore | PMI reimport | Material policy | Sheet Metal | DFM | Sweep |+| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |+| Paperclip | ✓ | | | | ✓ | | | ✓ |+| Mounting Plate | ✓ | | ✓ / ✓ | no | ✓ | | | |+| Bearing Block | ✓ | ✓ | ✓ | no | ✓ | | | |+| Angle Bracket | ✓ | | ✓ | | ✓ | | | |+| Shaft Collar | ✓ | | ✓ | | ✓ | | | |+| Flanged Adapter | ✓ | | ✓ | no | ✓ | | | |+| Rack Panel | ✓ | | ✓ | | ✓ | | | |+| Standoff | ✓ | | ✓ | | ✓ | | | |+| Electronics Enclosure | ✓ | | openings | | existing | ✓ | ✓ | |++## Fresh-agent tests++The selection outcomes were reviewed against the published index, but no isolated fresh-agent run was executed in this qualification:++- `120 × 80 mm aluminum plate with four counterbored mounting holes` → Mounting Plate policy; no manual geometry.+- `60 mm outer diameter, 20 mm bore, six mounting holes` → Flanged Adapter is the closest family, but its currently qualified fixed bolt layout is disclosed. A caller can change outer diameter and bore policy; it must not infer standards compliance.+- `helical auger` → no catalog family. Current X1 must reject family abuse and identify general helical geometry as unsupported.++The absence of Firmament module import prevents the requested literal fresh-agent standalone source test; Forge request fixtures are the qualified consumer form. Fresh isolated-agent first-attempt rates remain an acceptance gap.++## Reusable abstraction findings++| Candidate | Disposition | Reason |+| --- | --- | --- |+| four-hole layout | `FutureCandidate` | repeated semantics exist, but variable Pattern capture is not yet clean across host specialization |+| circular bolt layout | `KeepLocal` | current qualified flange uses one fixed six-hole layout; general bolt count is not implemented |+| material policy | `KeepLocal` | identity is repeated, but material attachment behavior differs by modeling route |++## Friction and bugs++| Finding | Classification | Disposition |+| --- | --- | --- |+| Multi-Template native module confuses geometry-route detection | `MustFixX1` | fixed by deterministic one-family catalog isolation |+| no public Firmament module import | `LibraryDesignIssue` | documented; blocks standalone namespace invocation fixtures |+| `Static` Record defaults absent from Forge field schema | `LibraryDesignIssue` | gallery presentation defaults are centralized; schema still owns controls/types |+| variable arithmetic in composed-hole centers and complex `Require` expressions | `LibraryDesignIssue` | bounded families use concrete finite layouts and simple semantic gates |+| direct cylindrical Hole uses Box-oriented modification path | `DocsFix` | circular parts use profile composition |+| nested Template PMI absent after AP242 reinspection | `MustFixX1` unresolved | claims removed; exact `0/0` inspection evidence recorded |+| Pattern intent not retained in new product variants | `PostX1` | no opaque or fake Pattern metadata emitted |++## Deferred work++General weldments, piping, surfacing/Loft/Shell/Draft, injection molding, arbitrary Boolean, and helical products remain outside X1. No new modeling domain or solver architecture was introduced.diff --git a/docs/release/X1a-STANDARD-LIBRARY-SEMANTIC-CLOSURE.md b/docs/release/X1a-STANDARD-LIBRARY-SEMANTIC-CLOSURE.mdnew file mode 100644index 00000000..83edad93--- /dev/null+++ b/docs/release/X1a-STANDARD-LIBRARY-SEMANTIC-CLOSURE.md@@ -0,0 +1,116 @@+# X1a — Standard Library semantic closure++## Executive verdict++Accepted++The four X1 semantic gaps are closed through the real compiler, Forge, client, BRep, AP242, and packaged execution paths. No product family or modeling domain was added.++## Gap 1 — Library resolution++Canonical standalone consumption uses `Use Standard.Products.Mechanical` (or `.Electronics` / `.Office`) plus fully qualified exported identities. `FirmamentStandardLibraryResolver` links only named exports from the one embedded `StandardProducts.firmament` authority. It admits no path, current-directory lookup, remote package, or arbitrary textual include.++Resolution precedence for X1a is deterministic: explicit qualified local references remain local; selected shipped exports are linked only by their qualified identity; a collision with the selected compiler-local export name is an error. Unknown modules, declarations, missing `Use`, malformed packages, and collisions have library-specific diagnostics. User modules and cycles are intentionally not introduced.++The canonical witness `fixtures/Canonical/Integration/standard-products/mounting-plate-library-use.firmament` uses the shipped mounting-plate default, derives a policy with `with`, and builds AP242 without copying implementation source. A freshly packed and installed `Aetheris.CLI` tool built that fixture after only the consumer file was copied into a temporary directory outside the repository; reinspection found one enclosed 46-face body and 1 datum / 1 dimension.++## Gap 2 — Static defaults++`FirmamentTemplateHostBridge.InspectModule` now returns resolved immutable Static Record metadata from the existing Template binder. It therefore supports direct Record literals, `with`, table rows, nested records, and current deterministic compile-time values without raw-source default parsing or a Forge interpreter.++For `StandardMountingPlate`, Forge describes `Width.Default = 120mm`, `Width.Unit = mm`, and `Material.Default = Standard.Materials.Aluminum.6061_T6`; fields with defaults are not required. Product Gallery removed its product-specific engineering-default table and initializes controls from `describe`. The five existing Sheet Metal families now follow the same authoritative `Static` default path, including a zero-argument Electronics Enclosure invocation.++```firmament+Static StandardMountingPlate: MountingPlatePolicy = MountingPlatePolicy {+ Width: 120mm Height: 80mm Thickness: 10mm+ HoleDiameter: 6.6mm HoleSpacingX: 90mm HoleSpacingY: 50mm+ CounterboreDiameter: 11mm CounterboreDepth: 4mm+ Material: "Standard.Materials.Aluminum.6061_T6"+}+Template<P: MountingPlatePolicy = StandardMountingPlate>+```++The packaged Forge projection reports `P` as optional with default `StandardMountingPlate`; its nine fields are ordered deterministically, typed (`Length` or `string`), carry `mm` where applicable, and are all optional because their resolved Static values exist.++## Gap 3 — Pattern retention++The Flanged Adapter policy now includes bounded `BoltCount` values from 4 through 8, with qualified variants for 4, 6, and 8 selected by compile-time `Match`. Default six-hole coordinates are unchanged. Specialization produces one `BoltPattern` over the selected Static array and the canonical generator `FlangeBolt`.++The retained semantic report contains Pattern name, source array, generator, count, distribution, and generated instance IDs. Both CLI `inspect --json` and `build --json` expose it. Canonical static lowering materializes explicit hole features for the BRep plan; topology is necessarily explicit after that boundary. An eight-hole build reports `BoltPattern`, source `Bolt8`, generator `FlangeBolt`, count 8, and nine total holes including the bore.++| Stage | Before X1a | After X1a |+| --- | --- | --- |+| Specialized semantic IR | explicit generated holes only | `Pattern(BoltPattern, Bolt8, FlangeBolt, 8)` plus `BoltPattern[0..7]` relationships |+| Feature AIR | holes usable by construction | holes retain generated IDs and Pattern provenance |+| BRep plan | explicit topology | explicit topology (deliberate expansion boundary) |+| Public report | no Pattern inventory | name, source, generator, count, instances, distribution, retention status |++## Gap 4 — Nested PMI++Template specialization now recursively expands finite nested Template applications. Each level retains its own `ConceptIrTemplateInstantiation`; nested concrete declarations flatten before Feature AIR, while PMI blocks are lifted to the canonical model boundary after value substitution. This keeps PMI bound to specialized feature identities rather than post-export name search.++Both one-level Standard Mounting Plate PMI and a two-level `Outer → Inner → geometry + PMI` witness export and reinspect as one datum plus one diameter dimension. The build parity check parses specialized source, so silent loss now fails.++The nested witness inventory is stable across the boundary: authored `Datum A` + `HoleDiameter BoreDiameter`; specialized inventory `1 + 1` attached to the inner specialized hole; AP242 inventory `1 + 1`; reinspection inventory `1 + 1`. The Standard Mounting Plate integrated path reinspects Ø6.6 mm with +0.1/-0.0 tolerance and eight associated `ADVANCED_FACE` IDs through `GEOMETRIC_ITEM_SPECIFIC_USAGE`. Binding uses specialization identities and materialization correspondence, not an exporter-side feature-name search.++## Integrated witness++`fixtures/Canonical/Integration/standard-products/flanged-adapter-eight-pattern.firmament` combines shipped import, `Static with`, Template specialization, a variable Pattern, repeated holes, datum/diameter PMI, BRep materialization, and AP242 reinspection. `fixtures/Canonical/Templates/nested-template-pmi.firmament` isolates two-level PMI preservation.++## Existing products++All eight native Standard Products and all five existing Sheet Metal families remain registered under their stable public IDs. Mounting Plate, Bearing Block, and Flanged Adapter STEP bytes change because AP242 now contains their authored PMI. Flanged Adapter default geometry remains six holes but now carries Pattern provenance. Sheet Metal geometry is unchanged; its former gallery defaults moved into named `Static` records.++| Family | Final specialization | Final STEP SHA-256 | X1 hash disposition |+| --- | --- | --- | --- |+| Paperclip | `template:e4037e9f05e7e73a` | `6cdcbfbb407cbcf86d26f0e59482e776e8fd6fa02158df67c800fc4afc32c305` | requalified; X1 report had no hash baseline |+| Mounting Plate | `template:14168b831dfb927d` | `88b68d29deef6a4f0b0cfbdf806e90ccd56c0a36c037169bdc60a637b92952fe` | expected change from `410b…`: authored PMI now exported |+| Bearing Block | `template:750d56ab4980c95e` | `d552a9bfa966885a165034bb9821122607ffa1905cd5328c6e774a72f0e6f558` | expected change from `845e…`: authored PMI now exported |+| Machined Angle Bracket | `template:b8132daafe2d49d3` | `a70a28a94b6c7e828b1ab62a8b9d0f12d79cd28ca622c343179fb6c63002639c` | unchanged |+| Shaft Collar | `template:8ab75bb46f5ac6df` | `4fdf4905c3b3609ec52691398bea1701d0283c69e126a6b7f4c8e44e1b010311` | unchanged |+| Flanged Adapter | `template:8e94f03dc017bd7d` | `e854a7b398f19051f98dd3f281a6a788f52abb1ec5571ade5ecb00835e3d82a6` | expected change from `e2ed…`: Pattern provenance and PMI |+| Standoff | `template:72374172dd3b36cf` | `93c4e755bd2289cfac223c6f5434a5cba3a80c1968168ea15381d6f0cfbd939b` | unchanged |+| Rack Panel | `template:a67e7089b42dd413` | `c3ac407c2982e295ee16fb33b353eec2506f0acaa0d1a75d28e5bb7a84f43849` | unchanged |++All rows invoked successfully with canonical defaults through the final published host. Existing Standard Product tests repeat each invocation, compare specialization/hash stability, and reimport STEP. The eight-hole non-default Flanged Adapter hash is `1941b7aa20df3a2a7640cb192c0c1847fcc42aa8184c7a391227ac2c6c24d390`.++## Fresh-agent tests++- A — source import: passed using only public docs and canonical fixtures. The independently authored qualified consumer built an enclosed 120 × 80 × 10 mm plate with 46 faces and datum/diameter PMI.+- B — packaged schema defaults: passed from a fresh directory against the NativeAOT host alone. `list → describe` exposed all nine mounting-plate field defaults; zero-argument invocation produced a 60,799-byte AP242 artifact in 22.3442 ms.+- C — variable Pattern: passed. `BoltCount: 8` produced eight Ø6.6 bolt holes, one bore, and a STEP identical between Forge and the canonical fixture (`1941b7aa20df3a2a7640cb192c0c1847fcc42aa8184c7a391227ac2c6c24d390`). Public CLI inspection now exposes the retained generator and count directly.+- D — PMI parity: passed. Standard Mounting Plate AP242 reinspection returned datum `A`, Ø6.6 +0.1/-0.0, and eight associated `ADVANCED_FACE` entity IDs connected through `GEOMETRIC_ITEM_SPECIFIC_USAGE`.++## Performance++Resolution is a bounded in-memory catalog lookup and declaration link. Static metadata uses the existing binder pass. The five focused semantic witnesses complete in under one second on the qualification machine; a packaged default Mounting Plate invocation reported 22.3442 ms. No material regression requiring caching was observed.++## Bugs found++- Canonical advanced Concept fallback did not parse PMI; it now shares the canonical PMI binder.+- Build parity parsed pre-specialization source; it now validates the specialized semantic source.+- Nested applications were incorrectly discovered inside Template declaration spans; they now expand recursively at their containing specialization.+- Compact Standard Product PMI had never been admitted because it remained nested; it is now canonical multiline source and is preserved.+- NativeAOT `describe` attempted reflection-based JSON string decoding; the host now uses its source-generated JSON context.+- CLI `inspect` and `validate` bypassed shipped-library resolution; both now share the build resolver and have a CLI regression witness.+- Pattern inventory existed in the compiler result but was omitted from public CLI JSON; `inspect` and `build` now expose it.+- Removing the client default map revealed that the five legacy Sheet Metal descriptors had no defaults; their values now live in authoritative Firmament `Static` records.++## Qualification matrix++- Release solution build: 0 warnings, 0 errors.+- .NET: 3,066 passed, 0 failed; the existing empty FrictionLab test assembly reports no discoverable tests.+- Canonical corpus: 72/72 fixtures passed.+- Client: 16 files / 82 tests passed; production build and lint passed.+- VS Code extension: typecheck, 13 tests, build, and VSIX package passed.+- Packaged paths: a freshly installed CLI tool built the standalone consumer outside the repository; a final NativeAOT Forge host described and invoked canonical defaults outside the repository.+- Invalid witnesses: unknown shipped module returned `firmament-library-unknown-module`; flange `BoltCount: 9` returned `firmament-template-require-failed` for `BoltCountMaximum`.+- Public documentation qualification passed in the full CLI suite; the Standard Library entry points also passed a relative Markdown-link scan.+- Determinism: two packaged Mounting Plate invocations were byte-identical, 60,799 bytes, SHA-256 `88b68d29deef6a4f0b0cfbdf806e90ccd56c0a36c037169bdc60a637b92952fe`.+- Repository: layout guard, Markdown link scan, and `git diff --check` passed.++NativeAOT publication emits existing cross-project trim/AOT analysis warnings in optional reflection/EF/drawing paths. They were collected rather than hidden; the final executable's `list`, both product and Sheet Metal `describe`, and zero-argument AP242 invocation paths all ran successfully outside the repository. No new warning appears in the ordinary Release solution build.++## Scope++No family, geometry feature kind, Pattern kind, PMI kind, solver, package manager, remote resolution mechanism, or gallery redesign was added.diff --git a/fixtures/Canonical/Integration/standard-products/bearing-block.forge.json b/fixtures/Canonical/Integration/standard-products/bearing-block.forge.jsonnew file mode 100644index 00000000..4b20864f--- /dev/null+++ b/fixtures/Canonical/Integration/standard-products/bearing-block.forge.json@@ -0,0 +1 @@+{"protocolVersion":1,"arguments":{"baseWidth":"100 mm","baseDepth":"50 mm","baseThickness":"14 mm","bossDiameter":"36 mm","bossHeight":"18 mm","boreDiameter":"20 mm","mountSpacing":"72 mm","mountHoleDiameter":"8.5 mm","material":"Standard.Materials.Aluminum.6061_T6"},"artifacts":["StepAp242"]}diff --git a/fixtures/Canonical/Integration/standard-products/flanged-adapter-eight-pattern.firmament b/fixtures/Canonical/Integration/standard-products/flanged-adapter-eight-pattern.firmamentnew file mode 100644index 00000000..5a4eed59--- /dev/null+++ b/fixtures/Canonical/Integration/standard-products/flanged-adapter-eight-pattern.firmament@@ -0,0 +1,10 @@+Model ImportedEightHoleFlange {+ Units: mm+ Use Standard.Products.Mechanical++ Static EightHoleFlange = Standard.Products.Mechanical.StandardFlangedAdapter with {+ BoltCount: 8+ }++ Struct Flange = Standard.Products.Mechanical.FlangedAdapter<P: EightHoleFlange>+}diff --git a/fixtures/Canonical/Integration/standard-products/flanged-adapter.forge.json b/fixtures/Canonical/Integration/standard-products/flanged-adapter.forge.jsonnew file mode 100644index 00000000..835b2362--- /dev/null+++ b/fixtures/Canonical/Integration/standard-products/flanged-adapter.forge.json@@ -0,0 +1 @@+{"protocolVersion":1,"arguments":{"outerDiameter":"80 mm","bodyThickness":"12 mm","boreDiameter":"30 mm","boltHoleDiameter":"6.6 mm","material":"Standard.Materials.Aluminum.6061_T6"},"artifacts":["StepAp242"]}diff --git a/fixtures/Canonical/Integration/standard-products/machined-angle-bracket.forge.json b/fixtures/Canonical/Integration/standard-products/machined-angle-bracket.forge.jsonnew file mode 100644index 00000000..86bbf490--- /dev/null+++ b/fixtures/Canonical/Integration/standard-products/machined-angle-bracket.forge.json@@ -0,0 +1 @@+{"protocolVersion":1,"arguments":{"width":"80 mm","height":"60 mm","legWidth":"20 mm","thickness":"10 mm","holeDiameter":"8.5 mm","material":"Standard.Materials.Steel.ASTM_A36"},"artifacts":["StepAp242"]}diff --git a/fixtures/Canonical/Integration/standard-products/mounting-plate-library-use.firmament b/fixtures/Canonical/Integration/standard-products/mounting-plate-library-use.firmamentnew file mode 100644index 00000000..6987fc75--- /dev/null+++ b/fixtures/Canonical/Integration/standard-products/mounting-plate-library-use.firmament@@ -0,0 +1,12 @@+Model ImportedMountingPlate {+ Units: mm+ Use Standard.Products.Mechanical++ Static MyPlate = Standard.Products.Mechanical.StandardMountingPlate with {+ Width: 120mm+ Height: 80mm+ Material: "Standard.Materials.Aluminum.6061_T6"+ }++ Struct Plate = Standard.Products.Mechanical.MountingPlate<P: MyPlate>+}diff --git a/fixtures/Canonical/Integration/standard-products/mounting-plate.forge.json b/fixtures/Canonical/Integration/standard-products/mounting-plate.forge.jsonnew file mode 100644index 00000000..a0bd1db1--- /dev/null+++ b/fixtures/Canonical/Integration/standard-products/mounting-plate.forge.json@@ -0,0 +1 @@+{"protocolVersion":1,"arguments":{"width":"120 mm","height":"80 mm","thickness":"10 mm","holeDiameter":"6.6 mm","holeSpacingX":"90 mm","holeSpacingY":"50 mm","counterboreDiameter":"11 mm","counterboreDepth":"4 mm","material":"Standard.Materials.Aluminum.6061_T6"},"artifacts":["StepAp242"]}diff --git a/fixtures/Canonical/Integration/standard-products/rack-panel.forge.json b/fixtures/Canonical/Integration/standard-products/rack-panel.forge.jsonnew file mode 100644index 00000000..66750d82--- /dev/null+++ b/fixtures/Canonical/Integration/standard-products/rack-panel.forge.json@@ -0,0 +1 @@+{"protocolVersion":1,"arguments":{"width":"482.6 mm","height":"44.45 mm","thickness":"3 mm","mountHoleDiameter":"6.5 mm","mountInset":"12.7 mm","material":"Standard.Materials.Aluminum.5052_H32"},"artifacts":["StepAp242"]}diff --git a/fixtures/Canonical/Integration/standard-products/shaft-collar.forge.json b/fixtures/Canonical/Integration/standard-products/shaft-collar.forge.jsonnew file mode 100644index 00000000..87610593--- /dev/null+++ b/fixtures/Canonical/Integration/standard-products/shaft-collar.forge.json@@ -0,0 +1 @@+{"protocolVersion":1,"arguments":{"outerDiameter":"32 mm","boreDiameter":"16 mm","width":"12 mm","material":"Standard.Materials.StainlessSteel.304_Annealed"},"artifacts":["StepAp242"]}diff --git a/fixtures/Canonical/Integration/standard-products/standoff.forge.json b/fixtures/Canonical/Integration/standard-products/standoff.forge.jsonnew file mode 100644index 00000000..978ae4e8--- /dev/null+++ b/fixtures/Canonical/Integration/standard-products/standoff.forge.json@@ -0,0 +1 @@+{"protocolVersion":1,"arguments":{"outerDiameter":"10 mm","length":"25 mm","boreDiameter":"4.2 mm","material":"Standard.Materials.StainlessSteel.304_Annealed"},"artifacts":["StepAp242"]}diff --git a/fixtures/Canonical/Templates/nested-template-pmi.firmament b/fixtures/Canonical/Templates/nested-template-pmi.firmamentnew file mode 100644index 00000000..6933110c--- /dev/null+++ b/fixtures/Canonical/Templates/nested-template-pmi.firmament@@ -0,0 +1,47 @@+Model NestedTemplatePmi {+ Units: mm++ Concept MountingPlateContract {+ Bounds: Box3+ TopPlane: Plane+ MountPoints: Point3[]+ }++ Template<> Struct PmiPlate {+ Concept Struct Design: MountingPlateContract {+ Bounds: Box3 { Size: [40mm, 30mm, 8mm] }+ TopPlane: Bounds.Face(+Z)+ MountPoints: Grid {+ Within: Bounds.Face(+Z).Inset(10mm)+ Columns: 1+ Rows: 1+ }+ }+ Box Base { Bounds: Design.Bounds }+ Modify Base {+ Hole<Shaft> Mount {+ On: Base.Top+ Center: Design.MountPoints[0]+ Diameter: 6mm+ End: ThroughAll+ }+ }+ Expose {+ Bounds: Design.Bounds+ TopPlane: Base.Top+ MountPoints: Design.MountPoints+ }+ Pmi {+ Datum A { Target: face(+Z) }+ HoleDiameter MountDiameter {+ Target: Mount+ Value: 6mm+ Tolerance: PlusMinus(0.05mm, 0.02mm)+ DatumRefs: [A]+ }+ }+ }++ Template<> Struct ProductFamily { Struct Generated = PmiPlate<> }+ Struct Product = ProductFamily<>+}diff --git a/fixtures/Invalid/Templates/flanged-adapter-pattern-count-outside-require.firmament b/fixtures/Invalid/Templates/flanged-adapter-pattern-count-outside-require.firmamentnew file mode 100644index 00000000..37f7b2bb--- /dev/null+++ b/fixtures/Invalid/Templates/flanged-adapter-pattern-count-outside-require.firmament@@ -0,0 +1,6 @@+Model InvalidFlangePatternCount {+ Units: mm+ Use Standard.Products.Mechanical+ Static Invalid = Standard.Products.Mechanical.StandardFlangedAdapter with { BoltCount: 9 }+ Struct Flange = Standard.Products.Mechanical.FlangedAdapter<P: Invalid>+}diff --git a/fixtures/Invalid/Templates/mounting-plate-hole-spacing-outside-body.forge.json b/fixtures/Invalid/Templates/mounting-plate-hole-spacing-outside-body.forge.jsonnew file mode 100644index 00000000..645a15e8--- /dev/null+++ b/fixtures/Invalid/Templates/mounting-plate-hole-spacing-outside-body.forge.json@@ -0,0 +1 @@+{"protocolVersion":1,"arguments":{"width":"120 mm","height":"80 mm","thickness":"10 mm","holeDiameter":"6.6 mm","holeSpacingX":"121 mm","holeSpacingY":"50 mm","counterboreDiameter":"11 mm","counterboreDepth":"4 mm","material":"Standard.Materials.Aluminum.6061_T6"},"artifacts":["StepAp242"]}diff --git a/fixtures/Invalid/Templates/unknown-standard-library-module.firmament b/fixtures/Invalid/Templates/unknown-standard-library-module.firmamentnew file mode 100644index 00000000..a97496d2--- /dev/null+++ b/fixtures/Invalid/Templates/unknown-standard-library-module.firmament@@ -0,0 +1,5 @@+Model UnknownStandardLibraryModule {+ Units: mm+ Use Standard.Products.Unknown+ Box Part { Size: [10mm, 10mm, 10mm] }+}