Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Expose template signatures and support canonical template syntax
Yuechen Li54749017682a
diff --git a/Aetheris.Forge.Host.Tests/ForgeProtocolV1Tests.cs b/Aetheris.Forge.Host.Tests/ForgeProtocolV1Tests.csindex 04a6fb64..bf86a7b1 100644--- a/Aetheris.Forge.Host.Tests/ForgeProtocolV1Tests.cs+++ b/Aetheris.Forge.Host.Tests/ForgeProtocolV1Tests.cs@@ -23,6 +23,10 @@ public sealed class ForgeProtocolV1TestsAssert.DoesNotContain(list.Templates, item => item.Id.Contains("Aetheris.", StringComparison.Ordinal));var description = host.DescribeTemplate(Enclosure)!;+ Assert.StartsWith("ElectronicsEnclosure<", description.Signature, StringComparison.Ordinal);+ Assert.Equal("SheetMetal", description.OutputKind);+ Assert.Contains(description.Constraints, item => item.Name == "Positive");+ Assert.All(description.Parameters, parameter => Assert.Contains(parameter.Category, new[] { "type", "value", "record" }));var spec = Assert.Single(description.Parameters);Assert.Equal("record", spec.Type);Assert.Equal("mm", spec.Fields!.Single(item => item.Name == "Width").Unit);diff --git a/Aetheris.Forge.Host/ForgeProtocolContracts.cs b/Aetheris.Forge.Host/ForgeProtocolContracts.csindex fb987db2..81dc2738 100644--- a/Aetheris.Forge.Host/ForgeProtocolContracts.cs+++ b/Aetheris.Forge.Host/ForgeProtocolContracts.cs@@ -36,7 +36,13 @@ public sealed record ForgeTemplateParameterDescription(string? Dimension,string? Unit,IReadOnlyList<string>? AllowedValues,- IReadOnlyList<ForgeTemplateParameterDescription>? Fields);+ IReadOnlyList<ForgeTemplateParameterDescription>? Fields,+ string Category,+ string? Constraint);++public sealed record ForgeTemplateConstraintDescription(+ string Name,+ string Expression);public sealed record ForgeTemplateDescription(int ProtocolVersion,@@ -45,7 +51,10 @@ public sealed record ForgeTemplateDescription(string Version,string Documentation,IReadOnlyList<ForgeTemplateParameterDescription> Parameters,- IReadOnlyList<ForgeArtifactKind> Artifacts);+ IReadOnlyList<ForgeArtifactKind> Artifacts,+ string Signature,+ string OutputKind,+ IReadOnlyList<ForgeTemplateConstraintDescription> Constraints);public sealed record ForgeTemplateInvocationRequest(int ProtocolVersion,diff --git a/Aetheris.Forge.Host/ForgeProtocolHost.cs b/Aetheris.Forge.Host/ForgeProtocolHost.csindex 4cc3264e..56bfd261 100644--- a/Aetheris.Forge.Host/ForgeProtocolHost.cs+++ b/Aetheris.Forge.Host/ForgeProtocolHost.cs@@ -51,7 +51,11 @@ public sealed class ForgeProtocolHosttemplate.Version,template.Documentation,template.Metadata.Parameters.Select(parameter => DescribeParameter(template, parameter)).ToArray(),- template.Artifacts);+ template.Artifacts,+ Signature(template.Metadata),+ template.Metadata.TargetKind,+ template.Metadata.Constraints.Select(constraint => new ForgeTemplateConstraintDescription(+ constraint.Name, constraint.Expression)).ToArray());}public ForgeTemplateInvocationResult InvokeTemplate(@@ -168,18 +172,27 @@ public sealed class ForgeProtocolHost? record.Fields.Select(field => DescribeValue(template, field.Name, field.TypeName, true, null)).ToArray(): null;return DescribeValue(template, parameter.Name, parameter.TypeName, parameter.DefaultExpression is null,- parameter.DefaultExpression, fields);+ parameter.DefaultExpression, fields,+ parameter.Kind == FirmamentTemplateParameterKind.Type ? "type" : fields is null ? "value" : "record",+ parameter.ConstraintConcept);}private static ForgeTemplateParameterDescription DescribeValue(RegisteredTemplate template, string name, string type,- bool required, string? defaultValue, IReadOnlyList<ForgeTemplateParameterDescription>? fields = null)+ bool required, string? defaultValue, IReadOnlyList<ForgeTemplateParameterDescription>? fields = null,+ string category = "value", string? constraint = null){var dimension = type switch { "Length" => "length", "Angle" => "angle", _ => null };var unit = type switch { "Length" => "mm", "Angle" => "deg", _ => null };var allowed = template.Enums.TryGetValue(type, out var enumeration) ? enumeration.Cases : null;- return new(name, PublicType(type, fields is not null), required, defaultValue, dimension, unit, allowed, fields);+ return new(name, PublicType(type, fields is not null), required, defaultValue, dimension, unit, allowed, fields, category, constraint);}+ private static string Signature(FirmamentTemplateMetadata template) =>+ template.Name + "<" + string.Join(", ", template.Parameters.Select(parameter =>+ parameter.Kind == FirmamentTemplateParameterKind.Type+ ? $"type {parameter.Name} satisfies {parameter.ConstraintConcept}"+ : $"{parameter.Name}: {parameter.TypeName}" + (parameter.DefaultExpression is null ? string.Empty : $" = {parameter.DefaultExpression}"))) + ">";+private static IReadOnlyDictionary<string, FirmamentHostArgument> BindArguments(RegisteredTemplate template,IReadOnlyDictionary<string, JsonElement> supplied,diff --git a/Aetheris.Forge.SampleExtension/Templates/SecretGeometry.firmament b/Aetheris.Forge.SampleExtension/Templates/SecretGeometry.firmamentindex 7b3f57ae..cf187c86 100644--- a/Aetheris.Forge.SampleExtension/Templates/SecretGeometry.firmament+++ b/Aetheris.Forge.SampleExtension/Templates/SecretGeometry.firmament@@ -4,7 +4,7 @@ Record SecretCouponSpec {Height: Length}-Template < Spec: SecretCouponSpec >+Template<Spec: SecretCouponSpec>Struct SecretCoupon {Construct MyCompany.SecretGeometry.SecretCoupon SecretBody {Width: Spec.Widthdiff --git a/Aetheris.Kernel.Firmament.Tests/BossPocketSemanticFeatureTests.cs b/Aetheris.Kernel.Firmament.Tests/BossPocketSemanticFeatureTests.csindex 41aa2020..350f1079 100644--- a/Aetheris.Kernel.Firmament.Tests/BossPocketSemanticFeatureTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/BossPocketSemanticFeatureTests.cs@@ -84,6 +84,32 @@ public sealed class BossPocketSemanticFeatureTestsAssert.Equal("Template.minimumFloorThickness", pocket.PolicySource);}+ [Fact]+ public void PocketMinimumFloor_UsesCanonicalCncPolicyBeforeLegacyCompatibilityChannel()+ {+ var source = File.ReadAllText(Fixture("Canonical/valid/boss-pocket-mounting-block.firmament"))+ .Replace("; MinimumFloorThickness: 2mm", string.Empty, StringComparison.Ordinal)+ .Replace(" Concept Struct Layout On XY", """+ Concept CncManufacturingPolicy {+ MinimumFloorThickness: Length+ MinimumWallThickness: Length+ }+ Concept Struct ShopPolicy: CncManufacturingPolicy {+ MinimumFloorThickness: 5mm+ MinimumWallThickness: 3mm+ }++ Concept Struct Layout On XY+ """, StringComparison.Ordinal);++ var build = FirmamentBuildAndExport.CompileSource(source);++ Assert.True(build.IsSuccess, string.Join("; ", build.Diagnostics.Select(item => item.Message)));+ var pocket = Assert.Single(build.Value!.EngineeringFeatures!, item => item.Kind == "Pocket");+ Assert.Equal(5d, pocket.MinimumFloorThickness);+ Assert.Equal("CncManufacturingPolicy.MinimumFloorThickness", pocket.PolicySource);+ }+[Fact]public void BossPocketCounterboreCombination_BuildsAndReimports(){diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentManufacturingPolicyTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentManufacturingPolicyTests.csnew file mode 100644index 00000000..482cfbe2--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentManufacturingPolicyTests.cs@@ -0,0 +1,49 @@+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentManufacturingPolicyTests+{+ [Theory]+ [InlineData("cnc-dfm-policy.firmament", "CNC", "CncManufacturingPolicy")]+ [InlineData("fdm-dfm-policy.firmament", "FDM", "FdmManufacturingPolicy")]+ [InlineData("sheet-metal-dfm-policy.firmament", "SheetMetal", "SheetMetalManufacturingPolicy")]+ public void CanonicalPolicyFamilies_AreTypedMaterializedAndDiscoverable(string fixture, string process, string contract)+ {+ var parse = FirmamentV2Parser.Parse(Source(fixture));++ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));+ var policy = Assert.Single(FirmamentManufacturingPolicyResolver.Resolve(parse.Document!, process));+ Assert.Contains(contract, policy.Source, StringComparison.Ordinal);+ Assert.NotEmpty(policy.Members);+ }++ [Fact]+ public void CanonicalCncPolicy_EnforcesMinimumToolRadiusOnRealSemanticHole()+ {+ var source = Source("cnc-dfm-policy.firmament")+ .Replace("MinimumToolRadius: 0.75mm", "MinimumToolRadius: 3mm", StringComparison.Ordinal);++ var parse = FirmamentV2Parser.Parse(source);+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));+ var dfm = FirmamentV2DfmEnforcement.Validate(parse.Document!);++ Assert.False(dfm.IsSuccess);+ Assert.Contains(dfm.Diagnostics, diagnostic => diagnostic.Message.StartsWith(FirmamentV2Parser.DfmMinimumToolRadiusViolation, StringComparison.Ordinal));+ }++ [Fact]+ public void HistoricalLowercaseCncTemplate_RemainsACompatibilityInput()+ {+ var parse = FirmamentV2Parser.Parse(File.ReadAllText(Path.Combine(+ FirmamentCorpusHarness.RepoRoot(), "fixtures", "Templates", "invalid", "template-v2-cnc-min-tool-radius-enforced.invalid.firmfixture")));+ Assert.True(parse.IsSuccess, string.Join(Environment.NewLine, parse.Diagnostics));+ var dfm = FirmamentV2DfmEnforcement.Validate(parse.Document!);++ Assert.False(dfm.IsSuccess);+ Assert.Contains(dfm.Diagnostics, diagnostic => diagnostic.Message.StartsWith(FirmamentV2Parser.DfmMinimumToolRadiusViolation, StringComparison.Ordinal));+ }++ private static string Source(string fixture) => File.ReadAllText(Path.Combine(+ FirmamentCorpusHarness.RepoRoot(), "fixtures", "Templates", "Canonical", fixture));+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalAdvancedGrammarTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalAdvancedGrammarTests.csindex bea4fd9b..cc6db7b9 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalAdvancedGrammarTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2CanonicalAdvancedGrammarTests.cs@@ -18,7 +18,7 @@ public sealed class FirmamentV2CanonicalAdvancedGrammarTestsMountSpec { Center: Point2(20mm, 0mm) Diameter: 8mm }]Require ValidDiameter => 8mm > 0mm- Template MountHole(MountSpec spec) {+ Template<spec: MountSpec> MountHole {Hole<Shaft> Mount {On: +ZCenter: spec.Center@@ -28,7 +28,7 @@ public sealed class FirmamentV2CanonicalAdvancedGrammarTests}Box Base { Size: [80mm, 40mm, 10mm] }Modify Base {- Pattern MountPattern Over Mounts { MountHole(Current) }+ Pattern MountPattern Over Mounts { MountHole<Current> }}}""");@@ -90,7 +90,7 @@ public sealed class FirmamentV2CanonicalAdvancedGrammarTestsUnits: mmRecord SlotSpec { Center: Point2 Direction: Vector2 Length: Length Width: Length }Static Vents: SlotSpec[] = [ SlotSpec { Center: Point2(0mm, 0mm) Direction: Vector2(1, 0) Length: 80mm Width: 40mm } ]- Template Vent(SlotSpec spec) { Slot<Capsule> Vent { Center: spec.Center Direction: spec.Direction Length: spec.Length Width: spec.Width Extent: ThroughAll Role: ThroughSlot } }+ Template<spec: SlotSpec> Vent { Slot<Capsule> Vent { Center: spec.Center Direction: spec.Direction Length: spec.Length Width: spec.Width Extent: ThroughAll Role: ThroughSlot } }Concept Struct Layout On XY { Rect2 Stock { Center: Point2(0mm, 0mm); Size: [200mm, 100mm] } }Profile Plate Using Layout { Loop Outer {Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }@@ -98,7 +98,7 @@ public sealed class FirmamentV2CanonicalAdvancedGrammarTestsSegment North { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft }Segment West { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }} }- Struct Plate { Compose Body { Base Stock { Profile: Plate; From: -10mm; To: 10mm; Role: Stock } Pattern SlotPattern Over Vents { Vent(Current) } } }+ Struct Plate { Compose Body { Base Stock { Profile: Plate; From: -10mm; To: 10mm; Role: Stock } Pattern SlotPattern Over Vents { Vent<Current> } } }}""");Assert.True(slots.IsSuccess, string.Join(Environment.NewLine, slots.Diagnostics));@@ -108,14 +108,14 @@ public sealed class FirmamentV2CanonicalAdvancedGrammarTestsUnits: mmRecord ProfileSpec { Center: Point2 }Static Specs: ProfileSpec[] = [ ProfileSpec { Center: Point2(0mm, 0mm) } ]- Template PlateProfile(ProfileSpec spec) { Profile Plate Using Layout { Loop Outer {+ Template<spec: ProfileSpec> PlateProfile { Profile Plate Using Layout { Loop Outer {Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }Segment East { Trace: Stock.Right; From: Stock.BottomRight; To: Stock.TopRight }Segment North { Trace: Stock.Top; From: Stock.TopRight; To: Stock.TopLeft }Segment West { Trace: Stock.Left; From: Stock.TopLeft; To: Stock.BottomLeft }} } }Concept Struct Layout On XY { Rect2 Stock { Center: Specs[0].Center; Size: [20mm, 10mm] } }- PlateProfile(Specs[0])+ PlateProfile<Specs[0]>Struct PlateBody { Extrude Plate { Profile: Plate; From: -2mm; To: 2mm } }}""");diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentV2TemplateExpansionTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentV2TemplateExpansionTests.csindex 52d4d4a2..eb425327 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentV2TemplateExpansionTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentV2TemplateExpansionTests.cs@@ -4,6 +4,30 @@ namespace Aetheris.Kernel.Firmament.Tests;public sealed class FirmamentV2TemplateExpansionTests{+ [Fact]+ public void CanonicalFiniteFeatureTemplate_UsesAngleBrackets_AndLegacyCallFormRemainsCompatible()+ {+ const string canonical = """+ Model CanonicalFeatureTemplate {+ Units: mm+ Record MountSpec { Center: Point2 Diameter: Length }+ Static Mounts: MountSpec[] = [ MountSpec { Center: Point2(0mm, 0mm) Diameter: 6mm } ]+ Template<spec: MountSpec> MountHole {+ Hole<Shaft> Mount { On: +Z Center: spec.Center Diameter: spec.Diameter End: ThroughAll }+ }+ Box Plate { Size: [30mm, 20mm, 5mm] }+ Modify Plate { Pattern MountsPattern Over Mounts { MountHole<Current> } }+ }+ """;+ var parsed = FirmamentV2Parser.Parse(canonical);+ Assert.True(parsed.IsSuccess, string.Join(Environment.NewLine, parsed.Diagnostics));+ Assert.Equal("MountHole", Assert.Single(parsed.Document!.StaticAuthoring!.Templates).Name);++ var legacy = canonical.Replace("Template<spec: MountSpec> MountHole", "Template MountHole(MountSpec spec)", StringComparison.Ordinal)+ .Replace("MountHole<Current>", "MountHole(Current)", StringComparison.Ordinal);+ Assert.True(FirmamentV2Parser.Parse(legacy).IsSuccess);+ }+[Fact]public void TypedRecordParameter_BindsStaticRecordMembersAndRequireBeforeAir(){@@ -77,6 +101,7 @@ public sealed class FirmamentV2TemplateExpansionTests{var missing = FirmamentV2Parser.Parse(Source("Bad", "", "40mm", "20mm", "Compact"));Assert.Contains(missing.Diagnostics, d => d.StartsWith("firmament-template-missing-required-argument:Width", StringComparison.Ordinal));+ Assert.Contains(missing.Diagnostics, d => d.Contains("expected-signature:MountingBracket<", StringComparison.Ordinal));var unknown = FirmamentV2Parser.Parse(Source("Bad", "60mm", "40mm", "20mm", "Compact").Replace("Variant: Compact", "Nope: Compact", StringComparison.Ordinal));Assert.Contains(unknown.Diagnostics, d => d.StartsWith("firmament-template-unknown-argument:Nope", StringComparison.Ordinal));var mismatch = FirmamentV2Parser.Parse(Source("Bad", "60", "40mm", "20mm", "Compact"));@@ -85,6 +110,7 @@ public sealed class FirmamentV2TemplateExpansionTestsAssert.Contains(constraint.Diagnostics, d => d.StartsWith("firmament-template-type-argument-does-not-satisfy-concept:TBody", StringComparison.Ordinal));var require = FirmamentV2Parser.Parse(Source("Bad", "0mm", "40mm", "20mm", "Compact"));Assert.Contains(require.Diagnostics, d => d.StartsWith("firmament-template-require-failed:Bad.ValidDimensions", StringComparison.Ordinal));+ Assert.Contains(require.Diagnostics, d => d.Contains("template-signature:MountingBracket<", StringComparison.Ordinal));}[Fact]diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 70573ef7..3af47191 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -746,7 +746,7 @@ public static class FirmamentBuildAndExport: reimport.Diagnostics);}- var template = (document.Templates ?? []).Single(template => string.Equals(template.Process, "Additive", StringComparison.OrdinalIgnoreCase));+ var template = FirmamentManufacturingPolicyResolver.Resolve(document, "Additive").Single();var graph = realization.Value.Plan.Construction;var centroid = mass.Centroid.Value;var report = new FirmamentStandaloneLatticeReport(diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.csindex 7564c175..1ebe9e91 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs@@ -14,7 +14,7 @@ internal static class CanonicalStaticAuthoringpublic static Result? Expand(string source, List<string> diagnostics){var canonicalRoot = Regex.IsMatch(source, @"^\s*Model\s+[A-Za-z_]\w*\s*\{", RegexOptions.CultureInvariant);- var staticDeclaration = Regex.IsMatch(source, @"\b(?:Record|Static|Template\s+[A-Za-z_]\w*\s*\(|Pattern\s+\w+\s+Over)\b", RegexOptions.CultureInvariant);+ var staticDeclaration = Regex.IsMatch(source, @"\b(?:Record|Static|Template\s*(?:<|[A-Za-z_]\w*\s*\()|Pattern\s+\w+\s+Over)\b", RegexOptions.CultureInvariant);if (!staticDeclaration && !(canonicalRoot && Regex.IsMatch(source, @"\b(?:Require\s+[A-Za-z_]\w*\s*(?:=>|\{)|Pmi\s*\{[\s\S]*?\bFrom\s*:)", RegexOptions.CultureInvariant))) return new(source, null);var changes = new List<(int Start, int Length, string Text)>();var names = new HashSet<string>(StringComparer.Ordinal);@@ -110,13 +110,21 @@ internal static class CanonicalStaticAuthoring}var arrayByName = arrays.ToDictionary(x => x.Name, StringComparer.Ordinal);- foreach (Match header in Regex.Matches(source, @"\bTemplate\s+(?<name>[A-Za-z_]\w*)\s*\(\s*(?<type>[A-Za-z_]\w*)\s+(?<param>[A-Za-z_]\w*)\s*\)\s*\{", RegexOptions.CultureInvariant))+ // Canonical finite feature Template: Template<Parameter: RecordType> Name { ... }.+ // The former Template Name(RecordType parameter) spelling remains warning-free+ // compatibility syntax for persisted Preview sources.+ var featureTemplateHeaders = Regex.Matches(source,+ @"\bTemplate\s*<\s*(?<param>[A-Za-z_]\w*)\s*:\s*(?<type>[A-Za-z_]\w*)\s*>\s*(?<name>[A-Za-z_]\w*)\s*\{|\bTemplate\s+(?<legacyName>[A-Za-z_]\w*)\s*\(\s*(?<legacyType>[A-Za-z_]\w*)\s+(?<legacyParam>[A-Za-z_]\w*)\s*\)\s*\{",+ RegexOptions.CultureInvariant);+ foreach (Match header in featureTemplateHeaders){var close = MatchPair(source, source.IndexOf('{', header.Index), '{', '}');- var name = header.Groups["name"].Value;- if (close < 0 || !recordByName.ContainsKey(header.Groups["type"].Value)) { diagnostics.Add(Prefix + "template-malformed:" + name); continue; }+ var name = header.Groups["name"].Success ? header.Groups["name"].Value : header.Groups["legacyName"].Value;+ var type = header.Groups["type"].Success ? header.Groups["type"].Value : header.Groups["legacyType"].Value;+ var parameter = header.Groups["param"].Success ? header.Groups["param"].Value : header.Groups["legacyParam"].Value;+ if (close < 0 || !recordByName.ContainsKey(type)) { diagnostics.Add(Prefix + "template-malformed:" + name); continue; }if (!names.Add(name)) { diagnostics.Add(FirmamentV2Parser.DuplicateName + ":Template:" + name); continue; }- var template = new Template(name, header.Groups["type"].Value, header.Groups["param"].Value, source[(source.IndexOf('{', header.Index) + 1)..close], new(header.Index, close - header.Index + 1));+ var template = new Template(name, type, parameter, source[(source.IndexOf('{', header.Index) + 1)..close], new(header.Index, close - header.Index + 1));templates.Add(template); changes.Add((header.Index, close - header.Index + 1, string.Empty));}var templateByName = templates.ToDictionary(x => x.Name, StringComparer.Ordinal);@@ -140,7 +148,7 @@ internal static class CanonicalStaticAuthoring{var open = source.IndexOf('{', pattern.Index); var close = MatchPair(source, open, '{', '}');if (close < 0 || !arrayByName.TryGetValue(pattern.Groups["array"].Value, out var array)) { diagnostics.Add(Prefix + "pattern-source-invalid:" + pattern.Groups["name"].Value); continue; }- var invocation = Regex.Match(source[(open + 1)..close], @"^(?:\s)*(?<template>[A-Za-z_]\w*)\s*\(\s*Current\s*\)\s*$", RegexOptions.CultureInvariant);+ var invocation = Regex.Match(source[(open + 1)..close], @"^(?:\s)*(?<template>[A-Za-z_]\w*)\s*(?:<\s*Current\s*>|\(\s*Current\s*\))\s*$", RegexOptions.CultureInvariant);if (!invocation.Success || !templateByName.TryGetValue(invocation.Groups["template"].Value, out var template) || template.Type != array.ElementType) { diagnostics.Add(Prefix + "pattern-body-invalid:" + pattern.Groups["name"].Value); continue; }var generated = new List<string>(); var output = new List<string>();for (var index = 0; index < array.Elements.Count; index++)@@ -156,12 +164,14 @@ internal static class CanonicalStaticAuthoring// A direct invocation is the same static expansion route as Pattern, with an// explicit bounded element index. The declaration body is still erased before// material AIR; it is not a runtime call.- foreach (Match invocation in Regex.Matches(source, @"\b(?<template>[A-Za-z_]\w*)\s*\(\s*(?<array>[A-Za-z_]\w*)\s*\[\s*(?<index>\d+)\s*\]\s*\)", RegexOptions.CultureInvariant))+ foreach (Match invocation in Regex.Matches(source, @"\b(?<template>[A-Za-z_]\w*)\s*(?:<\s*(?<array>[A-Za-z_]\w*)\s*\[\s*(?<index>\d+)\s*\]\s*>|\(\s*(?<legacyArray>[A-Za-z_]\w*)\s*\[\s*(?<legacyIndex>\d+)\s*\]\s*\))", RegexOptions.CultureInvariant)){+ var arrayName = invocation.Groups["array"].Success ? invocation.Groups["array"].Value : invocation.Groups["legacyArray"].Value;+ var indexText = invocation.Groups["index"].Success ? invocation.Groups["index"].Value : invocation.Groups["legacyIndex"].Value;if (!templateByName.TryGetValue(invocation.Groups["template"].Value, out var template)- || !arrayByName.TryGetValue(invocation.Groups["array"].Value, out var array)+ || !arrayByName.TryGetValue(arrayName, out var array)|| template.Type != array.ElementType) continue;- var index = int.Parse(invocation.Groups["index"].Value, CultureInfo.InvariantCulture);+ var index = int.Parse(indexText, CultureInfo.InvariantCulture);if (index >= array.Elements.Count) { diagnostics.Add(Prefix + "array-index-out-of-range:" + array.Name); continue; }var generatedId = template.Name + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";var declaration = Instantiate(template, array.Elements[index], generatedId, false, diagnostics);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentManufacturingPolicyResolver.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentManufacturingPolicyResolver.csnew file mode 100644index 00000000..ef2214d8--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentManufacturingPolicyResolver.cs@@ -0,0 +1,62 @@+namespace Aetheris.Kernel.Firmament.FirmamentV2;++/// <summary>+/// Adapts canonical typed policy structs and the historical lowercase template syntax+/// to one DFM-facing representation. Canonical policy structs take precedence whenever+/// they are present; lowercase templates remain a compatibility input only.+/// </summary>+internal static class FirmamentManufacturingPolicyResolver+{+ internal sealed record Policy(+ string Name,+ string Process,+ IReadOnlyDictionary<string, ConceptIrValue> Members,+ string Source);++ public static IReadOnlyList<Policy> Resolve(FirmamentV2Document document, string process)+ {+ var contract = process.ToUpperInvariant() switch+ {+ "CNC" => "CncManufacturingPolicy",+ "FDM" => "FdmManufacturingPolicy",+ "ADDITIVE" => "AdditiveManufacturingPolicy",+ "SHEETMETAL" or "SHEET METAL" => "SheetMetalManufacturingPolicy",+ _ => process + "ManufacturingPolicy",+ };++ var canonical = (document.ConceptIr?.Structs ?? [])+ .Where(instance => instance.Satisfies.Contains(contract, StringComparer.Ordinal))+ .Select(instance => new Policy(instance.Name, process, instance.Members, $"Concept Struct {instance.Name}: {contract}"))+ .ToArray();+ if (canonical.Length > 0) return canonical;++ return (document.Templates ?? [])+ .Where(template => string.Equals(template.Process, process, StringComparison.OrdinalIgnoreCase))+ .Select(template => new Policy(+ template.Name,+ template.Process,+ template.Concepts.ToDictionary(+ concept => concept.Name,+ concept => (ConceptIrValue)new ConceptIrLengthValue(+ $"legacy-template:{template.Name}.{concept.Name}",+ concept.NumericValue,+ concept.Unit ?? string.Empty,+ $"template<{template.Process}> {template.Name}"),+ StringComparer.OrdinalIgnoreCase),+ $"template<{template.Process}> {template.Name}"))+ .ToArray();+ }++ public static bool TryLength(Policy policy, string member, string units, out double value)+ {+ var pair = policy.Members.FirstOrDefault(candidate => string.Equals(candidate.Key, member, StringComparison.OrdinalIgnoreCase));+ if (pair.Value is ConceptIrLengthValue length && string.Equals(length.Unit, units, StringComparison.OrdinalIgnoreCase))+ {+ value = length.Value;+ return true;+ }++ value = double.NaN;+ return false;+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.csindex 5d94b230..21105e49 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs@@ -4,7 +4,12 @@ namespace Aetheris.Kernel.Firmament.FirmamentV2;public sealed record FirmamentTemplateMetadata(string Name,string TargetKind,- IReadOnlyList<FirmamentTemplateParameterMetadata> Parameters);+ IReadOnlyList<FirmamentTemplateParameterMetadata> Parameters,+ IReadOnlyList<FirmamentTemplateConstraintMetadata> Constraints);++public sealed record FirmamentTemplateConstraintMetadata(+ string Name,+ string Expression);public sealed record FirmamentTemplateParameterMetadata(string Name,@@ -106,7 +111,10 @@ public static class FirmamentTemplateHostBridgeparameter.Kind == "Type" ? FirmamentTemplateParameterKind.Type : FirmamentTemplateParameterKind.Value,parameter.TypeName,parameter.DefaultExpression,- parameter.ConstraintConcept)).ToArray()))+ parameter.ConstraintConcept)).ToArray(),+ template.Constraints.Select(constraint => new FirmamentTemplateConstraintMetadata(+ constraint.Name,+ constraint.Expression)).ToArray())).ToArray();var records = FirmamentV2TemplateExpansion.InspectRecords(moduleSource, collected).Select(record => new FirmamentTemplateRecordMetadata(record.Name,diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2DfmEnforcement.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2DfmEnforcement.csindex 9e190750..8b3b7251 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2DfmEnforcement.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2DfmEnforcement.cs@@ -13,23 +13,20 @@ internal static class FirmamentV2DfmEnforcementArgumentNullException.ThrowIfNull(document);var diagnostics = new List<KernelDiagnostic>();- foreach (var template in document.Templates ?? [])+ foreach (var template in FirmamentManufacturingPolicyResolver.Resolve(document, "CNC")){- if (!string.Equals(template.Process, "CNC", StringComparison.Ordinal)) continue;- foreach (var concept in template.Concepts.Where(c => string.Equals(c.Name, "minimumToolRadius", StringComparison.Ordinal)))+ const string conceptName = "MinimumToolRadius";+ if (!FirmamentManufacturingPolicyResolver.TryLength(template, conceptName, document.Units, out var minimumToolRadius)){- if (!string.Equals(concept.Unit, document.Units, StringComparison.Ordinal))- {- diagnostics.Add(Error($"{FirmamentV2Parser.DfmConceptUnitMismatch}: template '{template.Name}' concept '{concept.Name}' expects length unit '{document.Units}' but found '{concept.Unit ?? "<unitless>"}' in '{concept.RawValue}'."));- continue;- }+ diagnostics.Add(Error($"{FirmamentV2Parser.DfmConceptUnitMismatch}: policy '{template.Name}' member '{conceptName}' expects Length in '{document.Units}'."));+ continue;+ }- foreach (var (featureName, radius) in EnumerateHoleRadii(document))+ foreach (var (featureName, radius) in EnumerateHoleRadii(document))+ {+ if (radius < minimumToolRadius){- if (radius < concept.NumericValue)- {- diagnostics.Add(Error($"{FirmamentV2Parser.DfmMinimumToolRadiusViolation}: template '{template.Name}' concept '{concept.Name}' requires minimum tool radius {concept.NumericValue:0.###}{document.Units}; feature '{featureName}' has radius {radius:0.###}{document.Units}."));- }+ diagnostics.Add(Error($"{FirmamentV2Parser.DfmMinimumToolRadiusViolation}: policy '{template.Name}' member '{conceptName}' requires minimum tool radius {minimumToolRadius:0.###}{document.Units}; feature '{featureName}' has radius {radius:0.###}{document.Units}."));}}}@@ -43,22 +40,22 @@ internal static class FirmamentV2DfmEnforcementcontinue;}- var template = (document.Templates ?? []).SingleOrDefault(t => string.Equals(t.Process, "Additive", StringComparison.OrdinalIgnoreCase));- if (template is null)+ var policies = FirmamentManufacturingPolicyResolver.Resolve(document, "Additive");+ if (policies.Count != 1){- diagnostics.Add(Error("additive-template-required: Lattice Fill requires one Template<Additive> manufacturing context."));+ diagnostics.Add(Error($"additive-template-required: Lattice Fill requires exactly one AdditiveManufacturingPolicy; found {policies.Count}."));continue;}+ var template = policies[0];double Concept(string name){- var concept = template.Concepts.SingleOrDefault(c => string.Equals(c.Name, name, StringComparison.OrdinalIgnoreCase));- if (concept is null || !string.Equals(concept.Unit, document.Units, StringComparison.OrdinalIgnoreCase))+ if (!FirmamentManufacturingPolicyResolver.TryLength(template, name, document.Units, out var value)){- diagnostics.Add(Error($"additive-concept-required: template '{template.Name}' requires typed length concept '{name}' in '{document.Units}'."));+ diagnostics.Add(Error($"additive-concept-required: policy '{template.Name}' requires typed Length member '{name}' in '{document.Units}'."));return double.NaN;}- return concept.NumericValue;+ return value;}var context = new AdditiveManufacturingContext(template.Name, template.Process,@@ -85,22 +82,22 @@ internal static class FirmamentV2DfmEnforcementforeach (var fill in document.StandaloneLatticeFills ?? []){- var template = (document.Templates ?? []).SingleOrDefault(t => string.Equals(t.Process, "Additive", StringComparison.OrdinalIgnoreCase));- if (template is null)+ var policies = FirmamentManufacturingPolicyResolver.Resolve(document, "Additive");+ if (policies.Count != 1){- diagnostics.Add(Error("additive-template-required: standalone CubicTruss requires one Template<Additive> context."));+ diagnostics.Add(Error($"additive-template-required: standalone CubicTruss requires exactly one AdditiveManufacturingPolicy; found {policies.Count}."));continue;}+ var template = policies[0];double Concept(string name){- var concept = template.Concepts.SingleOrDefault(c => string.Equals(c.Name, name, StringComparison.OrdinalIgnoreCase));- if (concept is null || !string.Equals(concept.Unit, document.Units, StringComparison.OrdinalIgnoreCase))+ if (!FirmamentManufacturingPolicyResolver.TryLength(template, name, document.Units, out var value)){- diagnostics.Add(Error($"additive-concept-required: template '{template.Name}' requires typed length concept '{name}' in '{document.Units}'."));+ diagnostics.Add(Error($"additive-concept-required: policy '{template.Name}' requires typed Length member '{name}' in '{document.Units}'."));return double.NaN;}- return concept.NumericValue;+ return value;}var minStrut = Concept("MinimumStrutDiameter");diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.csindex 2ea0ed18..de63eff8 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs@@ -83,7 +83,10 @@ internal static class FirmamentV2TemplateExpansioninternal sealed record HostTemplate(string Name,string TargetKind,- IReadOnlyList<HostParameter> Parameters);+ IReadOnlyList<HostParameter> Parameters,+ IReadOnlyList<HostConstraint> Constraints);++ internal sealed record HostConstraint(string Name, string Expression);internal sealed record HostRecord(string Name, IReadOnlyDictionary<string, string> Fields);@@ -97,10 +100,17 @@ internal static class FirmamentV2TemplateExpansionTemplateTypeParameterIr type => new HostParameter(type.Name, "Type", type.Name, null, type.ConstraintConcept),TemplateValueParameterIr value => new HostParameter(value.Name, "Value", value.TypeName, value.DefaultExpression, null),_ => throw new InvalidOperationException($"Unknown Template parameter IR '{parameter.GetType().Name}'."),- }).ToArray()))+ }).ToArray(),+ ParseRequires(template.Body))).OrderBy(template => template.Name, StringComparer.Ordinal).ToArray();+ private static IReadOnlyList<HostConstraint> ParseRequires(string body) =>+ Regex.Matches(body, @"\bRequire\s+(?<name>[A-Za-z_]\w*)\s*=>\s*(?<expression>[^\r\n}]+)", RegexOptions.CultureInvariant)+ .Cast<Match>()+ .Select(match => new HostConstraint(match.Groups["name"].Value, match.Groups["expression"].Value.Trim()))+ .ToArray();+internal static IReadOnlyList<HostRecord> InspectRecords(string source, List<string> diagnostics) =>ParseRecordTypes(source, diagnostics).Values.OrderBy(record => record.Name, StringComparer.Ordinal)@@ -188,7 +198,7 @@ internal static class FirmamentV2TemplateExpansionvar body = ResolveTemplateMatches(template.Body, bound, diagnostics, out var selectedMatches);if (body is null || !ValidateRecordMembers(body, bound, diagnostics)) return null;body = Substitute(body, bound);- if (!EvaluateRequires(body, application.InstanceName, diagnostics, out var requireResults)) return null;+ if (!EvaluateRequires(body, application.InstanceName, DisplaySignature(template), diagnostics, out var requireResults)) return null;body = RemoveRequires(body);var specialization = new TemplateSpecializationIr(@@ -286,7 +296,7 @@ internal static class FirmamentV2TemplateExpansionif (body is null) continue;if (!ValidateRecordMembers(body, bound, diagnostics)) continue;body = Substitute(body, bound);- if (!EvaluateRequires(body, application.InstanceName, diagnostics, out var requireResults)) continue;+ 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(@@ -307,6 +317,9 @@ internal static class FirmamentV2TemplateExpansion{var open = source.IndexOf('<', start.Index); var close = Matching(source, open, '<', '>');var header = close < 0 ? Match.Empty : Regex.Match(source[(close + 1)..], @"^\s*(?<kind>Concept\s+Struct|Struct|Model|Panel|SheetMetal|ProfileDelta)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)(?<tail>\s*:\s*[A-Za-z_][A-Za-z0-9_]*)?\s*\{", RegexOptions.CultureInvariant);+ if (close >= 0 && !header.Success+ && Regex.IsMatch(source[(close + 1)..], @"^\s*[A-Za-z_][A-Za-z0-9_]*\s*\{", RegexOptions.CultureInvariant))+ continue; // finite feature Template; CanonicalStaticAuthoring owns this bounded form.if (close < 0 || !header.Success) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); continue; }var brace = close + 1 + header.Index + header.Value.LastIndexOf('{'); var end = Matching(source, brace, '{', '}');if (end < 0) { diagnostics.Add(FirmamentV2Parser.UnsupportedConstruct); continue; }@@ -361,7 +374,8 @@ internal static class FirmamentV2TemplateExpansionIReadOnlyDictionary<string, TemplateRecordTypeIr> recordTypes, IReadOnlyDictionary<string, TemplateStaticRecordIr> staticRecords, List<string> diagnostics){var supplied = application.Arguments.ToDictionary(a => a.Name, a => a.Expression, StringComparer.Ordinal);- foreach (var unknown in supplied.Keys.Where(name => template.Parameters.All(p => p.Name != name))) diagnostics.Add(UnknownArgument + ":" + unknown);+ var expectedSignature = DisplaySignature(template);+ foreach (var unknown in supplied.Keys.Where(name => template.Parameters.All(p => p.Name != name))) diagnostics.Add(UnknownArgument + ":" + unknown + ":expected-signature:" + expectedSignature);var types = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.Ordinal); var values = ImmutableDictionary.CreateBuilder<string, string>(StringComparer.Ordinal);var records = ImmutableDictionary.CreateBuilder<string, BoundTemplateRecordIr>(StringComparer.Ordinal); var defaults = ImmutableArray.CreateBuilder<string>();var resolving = new List<string>();@@ -370,13 +384,13 @@ internal static class FirmamentV2TemplateExpansionif (values.TryGetValue(p.Name, out var existing)) return existing;if (resolving.Contains(p.Name, StringComparer.Ordinal)) { diagnostics.Add(DefaultCycle + ":" + string.Join(" -> ", resolving.Append(p.Name))); return null; }var expression = supplied.TryGetValue(p.Name, out var suppliedValue) ? suppliedValue : p.DefaultExpression;- if (expression is null) { diagnostics.Add(MissingArgument + ":" + p.Name); return null; }+ if (expression is null) { diagnostics.Add(MissingArgument + ":" + p.Name + ":expected-signature:" + expectedSignature); return null; }resolving.Add(p.Name);var referenced = template.Parameters.OfType<TemplateValueParameterIr>().SingleOrDefault(x => x.Name == expression);var value = referenced is null ? expression : Resolve(referenced);resolving.RemoveAt(resolving.Count - 1);if (value is null) return null;- if (!TypeMatches(value, p.TypeName, enums)) { diagnostics.Add((supplied.ContainsKey(p.Name) ? TypeMismatch : BadDefault) + $":{p.Name}:expected-{p.TypeName}:actual-{value}"); return null; }+ if (!TypeMatches(value, p.TypeName, enums)) { diagnostics.Add((supplied.ContainsKey(p.Name) ? TypeMismatch : BadDefault) + $":{p.Name}:expected-{p.TypeName}:actual-{value}:expected-signature:{expectedSignature}"); return null; }values[p.Name] = value;if (!supplied.ContainsKey(p.Name)) defaults.Add(p.Name);return value;@@ -385,9 +399,9 @@ internal static class FirmamentV2TemplateExpansion{if (parameter is TemplateTypeParameterIr type){- if (!supplied.TryGetValue(type.Name, out var value)) { diagnostics.Add(MissingArgument + ":" + type.Name); continue; }+ if (!supplied.TryGetValue(type.Name, out var value)) { diagnostics.Add(MissingArgument + ":" + type.Name + ":expected-signature:" + expectedSignature); continue; }if (!ConceptExists(type.ConstraintConcept, source)) diagnostics.Add(UnknownConstraint + ":" + type.ConstraintConcept);- else if (!Satisfies(value, type.ConstraintConcept, source)) diagnostics.Add(ConstraintFailure + $":{type.Name}:{value}:{type.ConstraintConcept}");+ else if (!Satisfies(value, type.ConstraintConcept, source)) diagnostics.Add(ConstraintFailure + $":{type.Name}:{value}:{type.ConstraintConcept}:expected-signature:{expectedSignature}");types[type.Name] = value;}else@@ -403,7 +417,7 @@ internal static class FirmamentV2TemplateExpansionvoid BindRecord(TemplateValueParameterIr parameter, TemplateRecordTypeIr recordType){var expression = supplied.TryGetValue(parameter.Name, out var suppliedValue) ? suppliedValue : parameter.DefaultExpression;- if (expression is null) { diagnostics.Add(MissingArgument + ":" + parameter.Name); return; }+ if (expression is null) { diagnostics.Add(MissingArgument + ":" + parameter.Name + ":expected-signature:" + expectedSignature); return; }if (!supplied.ContainsKey(parameter.Name)) defaults.Add(parameter.Name);if (Regex.IsMatch(source, $@"\bStatic\s+{Regex.Escape(expression)}\s*:\s*{Regex.Escape(recordType.Name)}\s*\[", RegexOptions.CultureInvariant)){ diagnostics.Add(RecordCollectionMismatch + $":{parameter.Name}:expected-{recordType.Name}:actual-collection"); return; }@@ -453,13 +467,15 @@ internal static class FirmamentV2TemplateExpansion"Date" => DateOnly.TryParseExact(value, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _),"ImportedStep" => Regex.IsMatch(value, @"^\$[A-Za-z_][A-Za-z0-9_]*$", RegexOptions.CultureInvariant),"ProfilePath" => Regex.IsMatch(value, @"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)+$", RegexOptions.CultureInvariant),- "int" => long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out _), "float" => double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out _), "bool" => value is "true" or "false",+ "Int" or "int" => long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out _),+ "Float" or "float" => double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out _),+ "Bool" or "bool" => value is "true" or "false",_ when enums.TryGetValue(type, out var variants) => variants.Contains(value),_ when recordTypes?.ContainsKey(type) == true && staticRecords?.TryGetValue(value, out var record) == true => record.TypeName == type,_ => false};private static bool IsBuiltInValueType(string type, IReadOnlyDictionary<string, ImmutableHashSet<string>> enums) =>- type is "Length" or "Angle" or "String" or "Version" or "Date" or "ImportedStep" or "ProfilePath" or "int" or "float" or "bool" || enums.ContainsKey(type);+ type is "Length" or "Angle" or "String" or "Version" or "Date" or "ImportedStep" or "ProfilePath" or "Int" or "Float" or "Bool" or "int" or "float" or "bool" || enums.ContainsKey(type);private static IReadOnlyDictionary<string, TemplateRecordTypeIr> ParseRecordTypes(string source, List<string> diagnostics){@@ -686,14 +702,14 @@ internal static class FirmamentV2TemplateExpansionif (end < 0 || end > enclosingClose) end = enclosingClose;return body[start..end].Trim();}- private static bool EvaluateRequires(string body, string instance, List<string> diagnostics, out IReadOnlyDictionary<string, string> results)+ private static bool EvaluateRequires(string body, string instance, string signature, List<string> diagnostics, out IReadOnlyDictionary<string, string> results){var evidence = new Dictionary<string, string>(StringComparer.Ordinal);foreach (Match require in Regex.Matches(body, @"\bRequire\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*=>\s*(?<expr>[^\r\n}]+)", RegexOptions.CultureInvariant)){var name = require.Groups["name"].Value; var expression = require.Groups["expr"].Value.Trim();- if (!TryBool(expression, out var value)) { diagnostics.Add(RequireNonBool + ":" + name); evidence[name] = "Invalid:" + expression; }- else if (!value) { diagnostics.Add(RequireFailed + $":{instance}.{name}:{expression}"); evidence[name] = "Failed:" + expression; }+ if (!TryBool(expression, out var value)) { diagnostics.Add(RequireNonBool + ":" + name + ":template-signature:" + signature); evidence[name] = "Invalid:" + expression; }+ else if (!value) { diagnostics.Add(RequireFailed + $":{instance}.{name}:{expression}:template-signature:{signature}"); evidence[name] = "Failed:" + expression; }else evidence[name] = "Passed:" + expression;}results = evidence;@@ -732,6 +748,12 @@ internal static class FirmamentV2TemplateExpansionvar input = template.Name + "|" + application.InstanceName + "|" + string.Join("|", args.TypeArguments.Concat(args.ValueArguments).OrderBy(x => x.Key).Select(x => x.Key + "=" + x.Value).Concat(recordInput));return "template:" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(input))).ToLowerInvariant()[..16];}+ private static string DisplaySignature(TemplateDeclarationIr template) => template.Name + "<" + string.Join(", ", template.Parameters.Select(parameter => parameter switch+ {+ TemplateTypeParameterIr type => $"type {type.Name} satisfies {type.ConstraintConcept}",+ TemplateValueParameterIr value => $"{value.Name}: {value.TypeName}" + (value.DefaultExpression is null ? string.Empty : $" = {value.DefaultExpression}"),+ _ => parameter.Name,+ })) + ">";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 bool HasErrors(IEnumerable<string> diagnostics) => diagnostics.Any(d => d.StartsWith(Prefix, StringComparison.Ordinal));diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.csindex 84801fac..9741c37d 100644--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs@@ -113,6 +113,7 @@ public static class PrismaticProfileCompositionParserprivate static readonly Regex PocketDepth = new(@"\bDepth\s*:\s*(?<value>[-+.\d]+)mm", RegexOptions.CultureInvariant);private static readonly Regex PocketMinimumFloor = new(@"\bMinimumFloorThickness\s*:\s*(?<value>[-+.\d]+)mm", RegexOptions.CultureInvariant);private static readonly Regex TemplateMinimumFloor = new(@"\bconcept\s+(?<name>minimumFloorThickness|minimumWallThickness)\s*:\s*(?<value>[-+.\d]+)\s*mm", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);+ private static readonly Regex CncPolicyHead = new(@"\bConcept\s+Struct\s+(?<name>[A-Za-z_]\w*)\s*:\s*CncManufacturingPolicy\s*\{", RegexOptions.CultureInvariant);private static readonly Regex HoleHeader = new(@"\bHole\s*<\s*(?<variant>\w+)\s*>\s+(?<n>\w+)\s*\{", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);private static readonly Regex HoleCenter = new(@"\bCenter\s*:\s*\[(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);private static readonly Regex HolePoint2Center = new(@"\bCenter\s*:\s*Point2\s*\(\s*(?<x>[-+.\d]+)mm\s*,\s*(?<y>[-+.\d]+)mm\s*\)", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);@@ -456,6 +457,22 @@ public static class PrismaticProfileCompositionParser{var local = PocketMinimumFloor.Match(pocketBody);if (local.Success) return (N(local, "value"), "Pocket.MinimumFloorThickness");++ var canonical = CncPolicyHead.Matches(source).Cast<Match>()+ .Select(match => (Match: match, Body: Block(source, source.IndexOf('{', match.Index))))+ .Where(candidate => candidate.Body is not null)+ .ToArray();+ if (canonical.Length > 1) return (double.NaN, "CncManufacturingPolicy:ambiguous-multiple-authorities");+ if (canonical.Length == 1)+ {+ var floor = PocketMinimumFloor.Match(canonical[0].Body!);+ if (floor.Success) return (N(floor, "value"), "CncManufacturingPolicy.MinimumFloorThickness");+ var wall = Regex.Match(canonical[0].Body!, @"\bMinimumWallThickness\s*:\s*(?<value>[-+.\d]+)mm", RegexOptions.CultureInvariant);+ if (wall.Success) return (N(wall, "value"), "CncManufacturingPolicy.MinimumWallThickness");+ }++ // Historical lowercase templates remain readable so persisted Preview sources+ // do not change behavior; new authoring uses the typed policy contract above.var concepts = TemplateMinimumFloor.Matches(source).Cast<Match>().ToArray();var floors = concepts.Where(match => string.Equals(match.Groups["name"].Value, "minimumFloorThickness", StringComparison.OrdinalIgnoreCase)).ToArray();if (floors.Length > 1) return (double.NaN, "Template.minimumFloorThickness:ambiguous-multiple-authorities");diff --git a/Aetheris.SheetMetal/Firmament/SheetMetalProductFamilies.firmament b/Aetheris.SheetMetal/Firmament/SheetMetalProductFamilies.firmamentindex 3364e978..f480e09f 100644--- a/Aetheris.SheetMetal/Firmament/SheetMetalProductFamilies.firmament+++ b/Aetheris.SheetMetal/Firmament/SheetMetalProductFamilies.firmament@@ -92,7 +92,7 @@ Record EnclosureSpec {ReliefPolicy: SheetMetalReliefPolicy}-Template < Spec: LBracketSpec >+Template<Spec: LBracketSpec>SheetMetal LBracket: SheetMetalPart {Require Positive => Spec.Width > 0mm && Spec.Depth > 0mm && Spec.FlangeHeight > 0mm && Spec.Thickness > 0mmThickness: Spec.Thickness;@@ -101,7 +101,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>SheetMetal UChannel: SheetMetalPart {Require Positive => Spec.Width > 0mm && Spec.Depth > 0mm && Spec.WallHeight > 0mm && Spec.Thickness > 0mmThickness: Spec.Thickness;@@ -111,7 +111,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>SheetMetal FourWallTray: Tray {Require Positive => Spec.Width > 0mm && Spec.Depth > 0mm && Spec.WallHeight > 0mm && Spec.Thickness > 0mmRequire ManufacturableWall => Spec.WallHeight > Spec.InsideRadius@@ -124,7 +124,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>SheetMetal RemovablePanLid: RemovableLid {Require Positive => Spec.Width > 0mm && Spec.Depth > 0mm && Spec.SkirtHeight > 0mm && Spec.Thickness > 0mmThickness: Spec.Thickness;@@ -136,7 +136,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>SheetMetal ElectronicsEnclosure: Enclosure {Require Positive => Spec.Width > 0mm && Spec.Depth > 0mm && Spec.Height > 0mm && Spec.Thickness > 0mmRequire LipFits => Spec.LidLipHeight > Spec.InsideRadiusdiff --git a/docs/development/firmament-language-inconsistencies.md b/docs/development/firmament-language-inconsistencies.mdindex aef9212a..41985292 100644--- a/docs/development/firmament-language-inconsistencies.md+++ b/docs/development/firmament-language-inconsistencies.md@@ -1,6 +1,6 @@# Firmament language reconciliation register-This A5c register classifies the language seams first exposed by A5b. The public dialect is defined by [`docs/public/firmament`](../public/firmament/overview.md), especially the [language-style contract](../public/firmament/language-style.md). Parser/lowering ownership is recorded in the [active grammar inventory](firmament-v2-grammar-inventory.md).+This A5d register classifies the language seams first exposed by A5b and completes the Template reconciliation begun in A5c. The public dialect is defined by [`docs/public/firmament`](../public/firmament/overview.md), especially the [language-style contract](../public/firmament/language-style.md) and [Templates guide](../public/firmament/templates.md). Parser/lowering ownership is recorded in the [active grammar inventory](firmament-v2-grammar-inventory.md).| Area | Final classification | Decision and evidence ||---|---|---|@@ -15,7 +15,18 @@ This A5c register classifies the language seams first exposed by A5b. The public| Assembly document families | RetainedCompatibility | V2 `Assembly` source is current. JSON-shaped `.firmasm` is explicitly deprecated compatibility; it is not merged into Model. || PMI declaration/value shapes | RetainedCompatibility | Canonical Model PMI is PascalCase. Bounded legacy spellings remain on the same semantic PMI/AP242 route; Sheet Metal manufacturing PMI stays domain-specific. || Edge finishing | ResolvedCanonical | Current V2 uses qualified `EdgeFinish`. V1 low-level operations are quarantined; future `.firmfixture` forms remain speculative. |-| Template / Record / `with` / Struct / Compose / Modify | ResolvedCanonical | Ownership is explicit in the grammar inventory: compile-time data/specialization, constructive body creation, and post-construction operations are distinct. |+| `Template<...>` | ResolvedCanonical | Angle brackets identify typed compile-time specialization. Modern product Templates have explicit output kinds; finite feature Templates use the same generic visual form. The old call-shaped feature declaration remains a compatibility alias. |+| `Record` | ResolvedCanonical | Defines immutable grouped engineering-data shape; it is not a materialized object or semantic capability. |+| language `Concept` | ResolvedCanonical | Structural semantic contract and compile-time Concept value vocabulary. Forge C# concept descriptors remain a separate runtime extension mechanism. |+| `Require` | IntentionalOwnerOverlap | In a modern Template, named boolean `Require` is specialization admissibility. Other domain-owned `Require` blocks remain semantic requirements with their documented schemas. |+| `with` | ResolvedCanonical | Immutable checked Record derivation; not inheritance, mutation, or source substitution. |+| `Static` | ResolvedCanonical | Finite compile-time binding erased before materialization. |+| `Table` | ResolvedCanonical | Finite checked columnar Record data and keyed/index lookup; no LINQ or database-query semantics. |+| `Pattern` | IntentionalOwnerOverlap | Static `Pattern ... Over` expands a bounded feature Template; geometry-domain Pattern operations retain their separately typed owners. |+| `Struct` | ResolvedCanonical | Named materialized construction intent, or `Concept Struct` for explicitly non-materialized semantic data according to the qualified declaration. |+| `Compose` | ResolvedCanonical | Creates an admitted profile-based body and material interval; it is neither generic specialization nor post-construction mutation. |+| `Modify` | ResolvedCanonical | Applies admitted semantic operations to an existing body after construction. |+| historical lowercase manufacturing `template<Process>` | ResolvedCompatibility | Persisted CNC/Additive syntax is adapted to the same DFM representation. CNC/FDM/SheetMetal examples are ported to canonical typed Record/Static/`with`/Template/Concept Struct families. Canonical policy wins when both forms occur; new source uses the modern form. || Boss / Pocket versus Add / Remove | RetainedCompatibility | Boss/Pocket preserve their first-class engineering contracts. Low-level Add/Remove remain bounded profile-composition compatibility, not coequal public feature design. || Units and literals | ResolvedCanonical | V2 uses `Units: mm` and unit-bearing engineering literals. Lowercase V2 input, external JSON, and unitless V1 arrays are separately classified compatibility forms. || Speculative keyword families | SpeculativeQuarantined | Future/not-implemented `.firmfixture` bodies remain untouched and do not define parser or documentation requirements. |diff --git a/docs/public/firmament/template-examples.md b/docs/public/firmament/template-examples.mdnew file mode 100644index 00000000..3904e951--- /dev/null+++ b/docs/public/firmament/template-examples.md@@ -0,0 +1,37 @@+# Engineering product families with Templates++These examples map the useful Preview 3 envelope. Every example uses an existing compiler or domain path; none adds geometry or a general programming construct.++## Fastener-aware mounting interface++[`generic-mounting-plate.firmament`](../../../fixtures/Templates/Canonical/generic-mounting-plate.firmament) is a complete product Template parameterized by width, height, thickness, and shaft-hole diameter. It enforces positive dimensions before materialization and produces a deterministic mounting plate through the ordinary semantic Hole path. [`record-array-pattern-holes.firmament`](../../../fixtures/Canonical/valid/record-array-pattern-holes.firmament) extends the idea to a finite `MountSpec` set. Counterbore and countersink families use the same existing `Hole<...>` semantics when that variant is fixed by the family.++## Process-aware machined part++[`cnc-dfm-policy.firmament`](../../../fixtures/Templates/Canonical/cnc-dfm-policy.firmament) is the complete modern port: typed policy Record, immutable shop defaults, `with` specialization, named positive-limit `Require`, a `CncManufacturingPolicy` Concept Struct, and real minimum-tool-radius enforcement against a semantic Hole. [`boss-pocket-mounting-block.firmament`](../../../fixtures/Canonical/valid/boss-pocket-mounting-block.firmament) demonstrates the existing Boss/Pocket vocabulary; Pocket's explicit `MinimumFloorThickness` remains the local final authority.++The matching [`fdm-dfm-policy.firmament`](../../../fixtures/Templates/Canonical/fdm-dfm-policy.firmament) and [`sheet-metal-dfm-policy.firmament`](../../../fixtures/Templates/Canonical/sheet-metal-dfm-policy.firmament) ports preserve the historical nozzle/wall/overhang/layer and thickness/bend/K-factor data as typed family contracts. Persisted lowercase process templates still parse through the compatibility adapter, but new source should use these canonical data-first forms.++## Derived enclosure family++The embedded [`SheetMetalProductFamilies.firmament`](../../../Aetheris.SheetMetal/Firmament/SheetMetalProductFamilies.firmament) is the flagship product-family implementation. `ElectronicsEnclosure<Spec: EnclosureSpec>` changes width, depth, height, thickness, bend radius, K-factor, lip height, and relief policy while retaining one body definition. Desktop and rugged configurations can be derived from one immutable Record with `with` before specialization.++## Table-driven plate family++[`table-template-concept-path-compose.firmament`](../../../fixtures/Canonical/valid/table-template-concept-path-compose.firmament) selects a `PlateStandard` from a keyed finite Table, nests it in `PlateSpec`, derives a thicker configuration with `with`, and specializes one profile/Compose family. Its generic parameter is a Record; positive dimensions are the constraint; the concrete plate bounds and thickness change.++## Pattern-specialized features++[`docs-four-hole-pattern.firmament`](../../../fixtures/Canonical/valid/docs-four-hole-pattern.firmament) combines `Static` Record data, `Template<spec: MountSpec>`, and `Pattern ... Over`. The same feature Template expands any bounded mounting list into deterministic semantic holes without recursion or a loop language.++## Semantic type specialization++The compiler's canonical Template tests exercise `Template<type TBody satisfies PrismaticBody, Width: Length, ...>`. The type-like parameter is visibly different from values and must satisfy a language Concept. A finite enum `Match` selects an already-supported chamfer distance; the selected branch is erased before Feature AIR.++## Forge automation++`Standard.SheetMetal.ElectronicsEnclosure` exposes the enclosure family through Forge Host Protocol v1. Python, Go, Rust, or TypeScript callers send the stable ID and a JSON `Spec` object; the author-facing generic signature is descriptive metadata, not protocol identity. The same invocation can deterministically emit formed STEP, flat STEP, and SVG.++## Where to stop++Move the problem to C# when it needs database access, catalog search, joins, algorithms, external I/O, unbounded iteration, optimization, or large strategy search. Templates should make engineering families legible, not make the compiler clever.diff --git a/docs/public/firmament/templates.md b/docs/public/firmament/templates.mdindex 35c53d1d..144fc999 100644--- a/docs/public/firmament/templates.md+++ b/docs/public/firmament/templates.md@@ -1,7 +1,145 @@-# Templates and static data+# Templates: typed engineering specialization-Templates are typed compile-time functions over engineering values and Records. `Static` binds immutable values, arrays, or Tables; `Pattern ... Over` repeats an admitted feature from finite static data. `Require` constraints fail before geometry when a specialization is inadmissible.+Firmament Templates do not render text, documents, web pages, or source files. They specialize typed engineering models at compile time.-Build [`record-array-pattern-holes.firmament`](../../../fixtures/Canonical/valid/record-array-pattern-holes.firmament) for the shortest array/Template/pattern example. [`table-template-concept-path-compose.firmament`](../../../fixtures/Canonical/valid/table-template-concept-path-compose.firmament) adds a keyed Table and profile composition. For Sheet Metal product families, see [`m5-four-wall-tray-template.firmament`](../../../fixtures/SheetMetal/m5-four-wall-tray-template.firmament).+The useful mental model is generic engineering programming: one finite definition accepts typed parameters, checks admissibility, and becomes an ordinary concrete Firmament declaration before geometry or another domain artifact is materialized. Firmament borrows that mental category from C++ templates, but intentionally omits arbitrary recursive metaprogramming, macros, open-ended algorithms, and C++-style instantiation machinery.-Unknown Templates, missing arguments, extra fields, wrong unit dimensions, and failed `Require` constraints are errors. Template expansion does not create a second geometry or diagnostic path: expanded source uses the same binder and materializers as direct source.+## Canonical syntax++Angle brackets are mandatory in canonical V2 source. A product-family Template declares parameters before its output declaration:++```firmament+Template<Width: Length, Height: Length, Thickness: Length>+Struct MountingPlate {+ Require Positive => Width > 0mm && Height > 0mm && Thickness > 0mm+ Box Plate { Size: [Width, Height, Thickness] }+}++Struct StandardPlate = MountingPlate<Width: 80mm, Height: 50mm, Thickness: 8mm>+```++The complete build-qualified version is [`generic-mounting-plate.firmament`](../../../fixtures/Templates/Canonical/generic-mounting-plate.firmament).++The explicit output keyword is significant: current Templates specialize `Struct`, `Model`, `Concept Struct`, `Panel`, `SheetMetal`, or `ProfileDelta` declarations. It is not inferred from the body.++A finite feature Template used by `Pattern ... Over` has the same generic visual form:++```text+Template<spec: MountSpec> MountHole {+ Hole<Shaft> Mount {+ On: +Z+ Center: spec.Center+ Diameter: spec.Diameter+ End: ThroughAll+ }+}++Pattern MountPattern Over Mounts { MountHole<Current> }+```++The older `Template MountHole(MountSpec spec)` and `MountHole(Current)` spellings remain warning-free compatibility aliases. Current docs, fixtures, and snippets use angle brackets.++`Template<>` is valid. It exists for uniform specialization and compatibility, but a declaration with no variable engineering input is usually clearer as an ordinary `Struct`.++## Parameters++Value parameters use `Name: Type`. Defaults use `Name: Type = Value`. A real semantic/type parameter is explicit:++```text+Template<type TBody satisfies PrismaticBody, Width: Length, Variant: BracketVariant = Standard>+Struct BracketFamily {+ // existing construction+}+```++`type TBody satisfies PrismaticBody` is not an ordinary string-valued choice. The binder verifies that the supplied declaration satisfies the named language `Concept`. All other current parameters are typed compile-time values.++| Parameter kind | Preview 3 | Declaration | Checking and defaults | Forge.Host |+|---|---|---|---|---|+| `Length` | Supported | `Width: Length` | `mm`; defaults supported | dimension `length`, unit `mm` |+| `Angle` | Supported | `Draft: Angle` | `deg`; defaults supported | dimension `angle`, unit `deg` |+| integer | Supported | `Count: Int` | integer literal; defaults supported; lowercase alias accepted | JSON integer |+| number | Supported | `Ratio: Float` | finite numeric literal; defaults supported; lowercase alias accepted | JSON number |+| boolean | Supported | `Enabled: Bool` | `true` / `false`; defaults supported; lowercase alias accepted | JSON boolean |+| string | Supported | `Label: String` | quoted literal; defaults supported | JSON string |+| enum choice | Supported | `Variant: BracketVariant` | declared cases; defaults supported | allowed values listed |+| `Record` | Supported | `Spec: BracketSpec` | immutable `Static` value; nested fields checked | JSON object and field schema |+| `ImportedStep` | Supported at host seam | `Source: ImportedStep` | typed host resource token | transported as a host resource |+| `ProfilePath` | Supported in the profile-delta lane | `Owner: ProfilePath` | qualified semantic path | typed string boundary |+| semantic/type parameter | Supported | `type T satisfies Concept` | language Concept conformance; no default | category and constraint exposed |+| material reference | Not a distinct Template type | use a supported semantic material identity in the consuming domain | resolution stays in Firmament/Forge/C# | no catalog query surface |+| arrays/lists | Not a direct product-Template parameter | consume finite `Static` arrays through feature Templates/Patterns | element Record checked | not exposed as a parameter |+| `Table` | Not a direct parameter | select a row into a `Static Record` first | key and row checked | selected Record can cross the host seam |+| `Force` and other quantities | Not supported by the generic binder | — | `Length` and `Angle` are the admitted dimensions | — |+| `Profile`, feature kind, or Template | Not supported as generic parameters | — | no higher-order Templates | — |++This matrix describes the compiler today. It is not a roadmap.++## Records, `with`, Static, Tables, and Patterns++`Record` defines grouped engineering-data shape. `Static` binds immutable compile-time data. `with` derives a new Record value by replacing checked fields; it is neither inheritance nor mutation. A keyed `Static Table` is finite engineering data, and a Table lookup produces a Record that can be passed to a Template. `Pattern ... Over` expands a finite static collection into admitted semantic features.++```text+Record EnclosureSpec {+ Width: Length+ Height: Length+ WallThickness: Length+}++Static Desktop: EnclosureSpec = EnclosureSpec {+ Width: 180mm+ Height: 60mm+ WallThickness: 1.5mm+}++Static Rugged = Desktop with {+ WallThickness: 2mm+}+```++The coherent flow is: Records, Static values, and Tables define finite data; `with` derives configurations; a Template specializes from them; `Require` rejects inadmissible combinations; Pattern expands finite features; the resulting ordinary declaration follows the normal compiler and materializer path.++## Concepts and Require++A language `Concept` is a compile-time structural semantic contract. `Concept Struct` is a non-materialized typed semantic value. This differs from Forge C# runtime concept descriptors, even though both carry engineering semantics.++Parameter types own structural and dimensional checking. Records own grouped data shape. Concepts own semantic conformance. `Require Name => BooleanExpression` owns specialization-specific admissibility. A failed `Require` stops specialization before geometry materialization and records the named check in specialization provenance.++`Require` is finite: comparisons and bounded boolean combinations over specialized data are supported. It is not a runtime script or a general constraint solver.++## DFM policy families++An LLM-friendly DFM family has four ordinary pieces: a named policy `Concept`, a typed policy `Record`, one immutable `Static` default plus optional `with` variants, and a product `Template<Policy: ...>` that materializes one policy `Concept Struct`. The LLM normally changes only the Static data or selects a derived policy.++Canonical policy contracts are `CncManufacturingPolicy`, `FdmManufacturingPolicy`, `AdditiveManufacturingPolicy`, and `SheetMetalManufacturingPolicy`. The CNC and additive contracts are consumed by the existing DFM enforcement paths. CNC Pocket policy precedence is explicit: a Pocket-local `MinimumFloorThickness` wins, then the canonical CNC policy's floor value, then its wall value. FDM and sheet-metal policy structs are typed portable family data for their consuming domains.++Copy-ready, CLI-validated ports of the historical policy examples are:++- [`cnc-dfm-policy.firmament`](../../../fixtures/Templates/Canonical/cnc-dfm-policy.firmament)+- [`fdm-dfm-policy.firmament`](../../../fixtures/Templates/Canonical/fdm-dfm-policy.firmament)+- [`sheet-metal-dfm-policy.firmament`](../../../fixtures/Templates/Canonical/sheet-metal-dfm-policy.firmament)++Persisted lowercase `template<CNC>`, `template<FDM>`, `template<Additive>`, and `template<SheetMetal>` sources remain compatibility inputs. When a canonical typed policy is present it is authoritative; new source should not emit the lowercase form.++## Termination and composition++Templates may not recursively specialize themselves, directly or through a cycle. Nested specialization is only useful when it is acyclic and lowers to the admitted concrete declarations; Templates are not first-class values, cannot be passed as parameters, and have no higher-order or recursive programming surface.++The practical complexity ceiling is deliberate:++- Use Firmament for finite declarative product families, typed configuration, dimensional checks, bounded semantic choice, and deterministic repetition.+- Use C# or Forge for algorithms, external I/O, material-database queries, joins/grouping, large search or optimization, and open-ended computation.++Firmament has no `Select`, `Where`, `GroupBy`, joins, query comprehensions, SQL surface, or arbitrary source generation. C# stays C#.++## Output boundary++The modern generic specializer admits `Struct`, `Model`, `Concept Struct`, `Panel`, `SheetMetal`, and `ProfileDelta` output declarations. Finite feature Templates admit the currently documented `Hole<Shaft>`, capsule/rounded-rectangle `Slot`, `Profile`, and `StandardPart` outputs. Templates can thereby influence existing geometry, Sheet Metal, semantic PMI inputs, and an Analysis contained in an admitted concrete model, but Preview 3 has no separate generic FEA or Drawing output contract and no new PMI feature kinds.++`Struct`, `Compose`, and `Modify` keep their ordinary meanings after specialization: `Struct` owns construction intent, `Compose` creates an admitted profile-based body, and `Modify` applies admitted post-construction semantic features. Template is not a geometry subsystem.++## Forge.Host++Protocol v1 keeps stable IDs such as `Standard.SheetMetal.ElectronicsEnclosure` separate from display signatures such as `ElectronicsEnclosure<Spec: EnclosureSpec>`. `ListTemplates` discovers stable IDs. `DescribeTemplate` exposes the signature, output kind, parameter category, units/dimensions, required/default state, enum cases, nested Record fields, named `Require` constraints, documentation, and artifacts. `InvokeTemplate` binds language-neutral values and returns deterministic artifacts and specialization identity; it never exposes compiler AST nodes.++Syntax cleanup therefore does not rename a public Template. See [Template engineering examples](template-examples.md) and the [Forge Host guide](../forge/interop.md).diff --git a/docs/public/forge/interop.md b/docs/public/forge/interop.mdindex 25bfc8ee..6de6db6f 100644--- a/docs/public/forge/interop.md+++ b/docs/public/forge/interop.md@@ -17,4 +17,35 @@ node .\samples\forge-interop-x1\typescript\client.ts $host .\samples\forge-interThese commands run from the extracted `Aetheris-win-x64` directory and require no source checkout. Repository developers can publish the same host from `Aetheris.Forge.Host`; the released NativeAOT executable above is the qualified product path.+The process command is `invoke <stable-template-id> --request - --out <directory>`. A minimal Python client can send the Protocol v1 JSON envelope directly:++```python+import json+import subprocess++host = r".\forge-host\Aetheris.Forge.Host.exe"+request = {+ "protocolVersion": 1,+ "arguments": {+ "width": "120 mm",+ "height": "40 mm",+ "depth": "80 mm",+ "thickness": "1.5 mm",+ "lidLipHeight": "8 mm",+ "insideRadius": "2 mm",+ "kFactor": 0.42,+ "reliefPolicy": "Rectangular",+ },+ "artifacts": ["StepAp242", "FlatStep", "Svg"],+}+completed = subprocess.run(+ [host, "invoke", "Standard.SheetMetal.ElectronicsEnclosure", "--request", "-", "--out", r".\out\forge-python"],+ input=json.dumps(request), text=True, capture_output=True, check=True,+)+response = json.loads(completed.stdout)+assert response["success"]+```++`describe` is the authority for argument names, categories, units, required/default state, enum cases, nested Record fields, named constraints, output kind, and artifacts. The stable ID is the invocation identity; the human-readable generic signature is descriptive metadata. Protocol callers never send Firmament source or compiler AST nodes.+The shared production request is [`request.json`](../../../samples/forge-interop-x1/request.json), and the tiny clients are under [`samples/forge-interop-x1`](../../../samples/forge-interop-x1). Protocol v1 is language-neutral. The shipped NativeAOT binary and release bundle are qualified only for `win-x64`; framework-dependent tests on other operating systems establish protocol logic, not release-binary qualification.diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.mdindex 2b31a41b..e76a4611 100644--- a/docs/public/reference/supported-features.md+++ b/docs/public/reference/supported-features.md@@ -28,3 +28,22 @@| General loft, helix, and freeform surface features | Not in Preview 3 | No public native V2 authoring and qualification route || Through profile removal | Bounded semantic operations | Use qualified `Hole`, `Slot`, or another documented opening feature; Pocket never means through-all || Arbitrary solid Boolean subtraction / hemispherical cavity | Not in Preview 3 | No public `Union`, `Subtract`, `Intersect`, CSG tree, Sphere-from-Block subtraction, or hemisphere special case |++## Template capability matrix++| Capability | Status | Boundary |+|---|---|---|+| Typed value parameters and defaults | Supported | `Length`, `Angle`, `Int`, `Float`, `Bool`, `String`, enums, `Version`, `Date`, bounded `ImportedStep`/`ProfilePath` seams; lowercase scalar aliases remain accepted |+| Records and `with` | Supported | immutable checked values and finite derivation; no mutation or inheritance |+| DFM policy families | Supported | typed CNC/FDM/SheetMetal policy Records and Concept Structs; canonical CNC/Additive policies feed existing enforcement, lowercase process templates remain compatibility-only |+| Language Concept constraint | Supported | explicit `type T satisfies Concept`; distinct from an ordinary value parameter |+| `Require` | Supported | finite specialization-time boolean admissibility; no runtime scripting |+| Static arrays, Tables, Pattern | Bounded | finite checked data and admitted feature expansion; no query language |+| Materials | Bounded by consuming domain | semantic identity can flow through existing Firmament/Forge paths; no SQLite or catalog queries in Templates |+| Sheet Metal product families | Supported | five embedded public families and Forge Protocol v1 exposure |+| Nested Templates | Bounded | acyclic concrete specialization only; Templates are not values |+| Recursive or higher-order metaprogramming | Not in Preview 3 | cycles are rejected; Template parameters are unsupported |+| Direct array/Table parameters | Not in Preview 3 | select/derive a finite Record or use bounded feature Pattern data |+| FEA specialization | Bounded by concrete Model output | an admitted specialized Model can contain existing Analysis; no generic Analysis output family |+| PMI specialization | Bounded by existing concrete semantics | specialized dimensions can feed existing PMI; no new PMI kinds |+| Forge introspection | Supported | stable ID plus generic display signature, categories, units, defaults, enum cases, Record fields, constraints, output kind, artifacts |diff --git a/docs/release/PREVIEW3-HARDEN-A5d.md b/docs/release/PREVIEW3-HARDEN-A5d.mdnew file mode 100644index 00000000..15a50efc--- /dev/null+++ b/docs/release/PREVIEW3-HARDEN-A5d.md@@ -0,0 +1,107 @@+# PREVIEW3-HARDEN-A5d — Firmament Template metaprogramming reconciliation++## Executive verdict++Yes. Firmament Templates now present as bounded typed generic engineering specialization: canonical declarations and specializations use angle brackets, types and engineering values are checked before materialization, named `Require` constraints reject inadmissible specializations, and Forge exposes a language-neutral generic contract without exposing compiler AST.++This remains deliberately smaller than C++ template metaprogramming. There are no text macros, arbitrary source generation, recursive compile-time programming, higher-order Templates, LINQ/query syntax, or general database access.++## Canonical syntax++Current source uses `Template<...>`. Product-family Templates retain an explicit output declaration, for example `Template<Spec: PlateSpec>` followed by `Struct PlateFamily { ... }`; the output kind is semantic, not inferred. Bounded feature Templates use `Template<spec: MountSpec> MountHole { ... }` and specialize as `MountHole<Current>`.++The former feature-helper spelling `Template MountHole(MountSpec spec)` remains a warning-free compatibility alias on the same finite expansion path. Historical lowercase process templates remain compatibility inputs, now adapted to the canonical DFM representation; new CNC, FDM, and SheetMetal authoring uses typed policy families. `Template<>` remains valid and cycle-tested, though an ordinary `Struct` is clearer when no specialization input exists.++## Verified capability inventory++The authoritative modern path is `FirmamentV2TemplateExpansion`: immutable declaration/parameter/application IR, typed binding, Record flattening, finite enum Match selection, `Require` evaluation, recursion/cycle detection, deterministic identity, source expansion, then the ordinary domain parser and materializer. `FirmamentTemplateHostBridge` projects that IR to stable Forge metadata. `CanonicalStaticAuthoring` owns the smaller finite feature Template/Static array/Pattern path. The older process metadata parser and Pocket minimum-floor compatibility lookup are separate bounded legacy owners, not modern generic specialization.++| Parameter kind | Status | Syntax/checking | Defaults | Forge.Host |+|---|---|---|---|---|+| `Length` / `Angle` | Supported | `Name: Length` (`mm`), `Name: Angle` (`deg`) | yes | dimension and canonical unit |+| `Int` / `Float` / `Bool` / `String` | Supported | typed literal; lowercase scalar aliases remain accepted | yes | JSON integer/number/boolean/string |+| declared enum | Supported | `Variant: EnumName`; case checked | yes | allowed values |+| Record | Supported | `Spec: RecordName`; immutable Static Record, nested fields checked | yes | JSON object with field schema |+| semantic/type parameter | Supported | `type T satisfies Concept`; actual Concept conformance | no | category `type` and constraint |+| `Version`, `Date` | Supported binder values | canonical literal forms | yes | string transport |+| `ImportedStep` | Supported bounded host seam | typed resource token | yes | host resource transport |+| `ProfilePath` | Supported profile-delta seam | qualified path | yes | typed string boundary |+| material identity | Not a distinct generic type | consumed through the existing domain/Forge material route | — | no catalog query API |+| Force/other dimensions | Unsupported | no binder type | — | — |+| array/list or Table | Unsupported as direct product parameters | use finite Static/Pattern data or select a Table row into a Record | — | — |+| Profile, feature kind, or Template | Unsupported | no higher-order parameter surface | — | — |++The complete public matrix and notes are in [Templates: typed engineering specialization](../public/firmament/templates.md).++## Record, Concept, Require, `with`, Static, Table, and Pattern doctrine++- Parameter types own literal, structural, and dimensional admission.+- `Record` owns grouped immutable engineering-data shape.+- A language `Concept` owns structural semantic contracts; `Concept Struct` owns non-materialized semantic values. Forge C# runtime concept descriptors remain a separate extension boundary.+- `Require Name => BooleanExpression` owns specialization-specific admissibility and runs before geometry materialization.+- `with` derives a checked immutable Record; it is not inheritance, mutation, or a macro.+- `Static` binds finite compile-time data; `Table` holds finite checked rows and keyed/index lookup; `Pattern ... Over` performs bounded admitted feature expansion.+- `Struct`, `Compose`, and `Modify` keep construction, profile-body creation, and post-construction semantic-operation ownership after specialization.++Recursive and mutually recursive specialization cycles are rejected. Templates are not first-class values. Acyclic nested specialization may only produce the existing admitted concrete declaration families. Rich algorithms, I/O, database queries, joins, optimization, and open-ended computation remain C#/Forge work.++## DFM and manufacturing reconciliation++The historical `.firmfixture` forms `template<CNC>`, `template<FDM>`, and `template<SheetMetal>` are preserved as migration evidence. Their canonical ports are buildable policy families under `fixtures/Templates/Canonical/`: each uses a typed Record, immutable Static defaults, `with` overrides, a policy-parameterized product Template, named `Require` checks, and a typed policy Concept Struct. `Int`, `Float`, and `Bool` are now accepted in canonical Record schemas alongside their lowercase compatibility aliases.++Canonical CNC and Additive policy Concept Structs now feed the real DFM enforcement paths; the lowercase templates are adapted only when no canonical policy exists. Boss/Pocket keep their existing A3b DFM ownership. Pocket's local `MinimumFloorThickness` remains the final explicit feature policy, followed by canonical CNC floor policy, canonical wall policy, then the historical compatibility lookup. Sheet Metal product-family policy continues to use ordinary `Template<Spec: ...>` Records, enum relief policy, and `Require`. Material catalog querying stays in C#/Forge; specialization consumes semantic identity or resolved data through existing paths.++## Output and domain boundary++Modern product specialization currently admits `Struct`, `Model`, `Concept Struct`, `Panel`, `SheetMetal`, and `ProfileDelta`. Finite feature Templates admit the implemented Shaft Hole, capsule/rounded-rectangle Slot, Profile, and StandardPart outputs. Existing semantic values can affect existing PMI and Analysis contained in a concrete output, but Preview 3 has no separate generic Drawing/Analysis output family, no new PMI kinds, no new physics, and no new geometry.++## Forge.Host Protocol v1++Stable IDs are unchanged: for example `Standard.SheetMetal.ElectronicsEnclosure`. `DescribeTemplate` now adds the human-readable `ElectronicsEnclosure<Spec: EnclosureSpec>` signature, output kind, parameter category, language Concept constraint, and named `Require` constraints to the existing units/dimensions, required/default state, enum cases, nested Record fields, documentation, and artifact list. This is additive Protocol v1 data; invocation identity does not depend on display spelling.++`list`, `describe`, and Python invocation were exercised against the production host. Python produced formed STEP, flat STEP, and SVG for the stable enclosure ID with specialization `template:94546352d5d67afa`; the artifact hashes were `51aa1f...3223`, `832775...cff`, and `1657e3...519` respectively.++## Flagship examples++The new build-qualified [`generic-mounting-plate.firmament`](../../fixtures/Templates/Canonical/generic-mounting-plate.firmament) specializes four typed dimensions, checks them, resolves a compile-time mounting point, lowers a semantic shaft Hole, exports STEP, and reimports it. The CNC, FDM, and SheetMetal canonical DFM fixtures port the historical process data into copy-ready typed families; the CNC fixture is enforcement-tested against a real semantic Hole. The existing current corpus supplies Record/`with`/Table profile specialization, finite patterned holes and slots, ProfileDelta specialization, Assembly and Sheet Metal product families. The public [engineering product-family showcase](../public/firmament/template-examples.md) organizes mounting, process/DFM, enclosure, table, pattern, semantic-type, and Forge examples by engineering purpose rather than parser tricks.++## Fresh-agent mental-model test++The first clean-room agent saw only `docs/public/` and current canonical fixtures. It immediately classified Template as generic compile-time engineering specialization and never inferred text/web templating. It found two real usability gaps: no single product Template plus semantic-Hole fixture, and no inline Python Protocol v1 request envelope. Both were repaired. A final restricted re-probe then answered all four authoring tasks without implementation access: generic mounting plate 0.97 confidence, Record/`with` configurations 0.94, explicit DFM policy 0.84, and exact Python Forge invocation 0.99. Its only caution was that public docs intentionally promise bounded comparisons/booleans rather than arbitrary arithmetic in `Require`.++## Diagnostics++Missing, unknown, wrong-type, Concept-constraint, non-boolean `Require`, and failed-`Require` diagnostics now include the expected generic Template signature while preserving their stable diagnostic prefixes. Existing diagnostics cover Record type/field/membership errors, `with` base/field errors, Table schema/key/index errors, missing Templates, defaults/default cycles, and recursive/application cycles. Successful builds retain concise specialization identity, Record arguments, selected finite Match arms, named `Require` results, and generated declaration paths; no unbounded instantiation trace is emitted.++## Validation++- Release build: pass, 0 warnings, 0 errors.+- Focused Template/DFM/canonical tests pass, including five canonical-policy/legacy-compatibility tests and canonical Pocket precedence; Forge.Host: 24/24 pass.+- Full active .NET suite: 3,032/3,032 tests pass after the policy ports.+- Canonical Template CLI corpus: the migrated fixtures and new mounting Template validate; CNC, FDM, and SheetMetal policy families each build STEP with resolved typed policy Concept IR, specialization provenance, semantic Hole evidence, and STEP reimport success.+- Forge `list`/`describe`/`invoke`: pass; Python foreign-language invocation: pass.+- VS Code: TSPack format/check, typecheck, 13 tests, build, and VSIX package pass. Known acknowledged dependency-version and blocked lifecycle-script notices remain.+- Cadmata: TSPack check, typecheck, 81 tests, build, and lint pass with the same acknowledged notices.+- NuGet CLI pack, NativeAOT Forge publish, Windows x64 ZIP, extracted packaged CLI/Forge/fixture smoke: pass.+- Checksums: 3/3 recomputed; two complete release runs produced byte-identical hashes.+- `git diff --check`: pass.++## Release artifacts++Generated outputs remain ignored under `artifacts/local/a5d/release/`.++| Artifact | Bytes | SHA-256 |+|---|---:|---|+| Windows x64 ZIP | 107,820,280 | `00886c8c646e3118760b02bd5f3cb9439e9c013f75a7b92f762d17d4a8d10eef` |+| Firmament VSIX | 12,480 | `05b58a6a06a7d77637166f0fba3c5ec1bbfe274297e83789d338ada3d5494a7f` |+| CLI NuGet package | 33,416,699 | `4cbe40706d2d9827e0df1c8ac52d7ceff293c40267559976d364cd44f4005f30` |++Repeated release packaging exposed and fixed one convergence issue: a pre-existing VSIX in `dist/` could be selected as input while `vsce` overwrote it. The release script now removes that exact generated file before packaging; consecutive full releases are byte-identical.++## Remaining limitations++Direct array/Table parameters, Force and arbitrary quantity parameters, material catalog queries, Template parameters, higher-order specialization, recursion, arbitrary source generation, and general query/algorithm syntax remain unsupported. Feature Templates are a smaller bounded output family than product Templates. FEA and PMI can consume specialized existing intent but have no new standalone Template output contract. Historical lowercase manufacturing syntax remains compatibility-only; canonical typed policy structs are authoritative.++## Feature freeze++Preview 3 feature freeze remains intact. A5d reconciles syntax, generic metadata, diagnostics, documentation, fixtures, tooling, and release reproducibility around existing capability. It adds no geometry, Sheet Metal operation, hole family, FEA physics, PMI kind, Forge verb, database query language, or general-purpose programming construct.diff --git a/fixtures/Canonical/valid/docs-four-hole-pattern.firmament b/fixtures/Canonical/valid/docs-four-hole-pattern.firmamentindex d3dd92c7..2e74a268 100644--- a/fixtures/Canonical/valid/docs-four-hole-pattern.firmament+++ b/fixtures/Canonical/valid/docs-four-hole-pattern.firmament@@ -8,7 +8,7 @@ Model FourHolePlate {MountSpec { Center: Point2(30mm, 15mm) Diameter: 6mm }MountSpec { Center: Point2(-30mm, 15mm) Diameter: 6mm }]- Template MountHole(MountSpec spec) {+ Template<spec: MountSpec> MountHole {Hole<Shaft> Mount {On: +ZCenter: spec.Center@@ -19,6 +19,6 @@ Model FourHolePlate {Box Plate { Size: [80mm, 50mm, 8mm] }Modify Plate {- Pattern MountPattern Over Mounts { MountHole(Current) }+ Pattern MountPattern Over Mounts { MountHole<Current> }}}diff --git a/fixtures/Canonical/valid/profile-compose-l-bracket-counterbore-pmi.firmament b/fixtures/Canonical/valid/profile-compose-l-bracket-counterbore-pmi.firmamentindex c4fd858f..daedb8e6 100644--- a/fixtures/Canonical/valid/profile-compose-l-bracket-counterbore-pmi.firmament+++ b/fixtures/Canonical/valid/profile-compose-l-bracket-counterbore-pmi.firmament@@ -6,7 +6,7 @@ Model ProfileComposeLBracketCounterborePmi {MountSpec { Center: Point2(20mm, -10mm) Diameter: 6mm }MountSpec { Center: Point2(-30mm, 20mm) Diameter: 6mm }]- Template ShaftHole(MountSpec spec) {+ Template<spec: MountSpec> ShaftHole {Hole<Shaft> Mount {On: +ZCenter: spec.Center@@ -33,7 +33,7 @@ Model ProfileComposeLBracketCounterborePmi {Struct BracketBody {Compose BracketBody {Base Stock { Profile: Bracket; From: 0mm; To: 12mm; Role: Stock }- Pattern MountPattern Over Mounts { ShaftHole(Current) }+ Pattern MountPattern Over Mounts { ShaftHole<Current> }Hole<Counterbore> CounterboredMount {On: +ZCenter: Point2(-30mm, -10mm)diff --git a/fixtures/Canonical/valid/profile-compose-l-bracket-external-modify-counterbore.firmament b/fixtures/Canonical/valid/profile-compose-l-bracket-external-modify-counterbore.firmamentindex 7a852b87..15a4e532 100644--- a/fixtures/Canonical/valid/profile-compose-l-bracket-external-modify-counterbore.firmament+++ b/fixtures/Canonical/valid/profile-compose-l-bracket-external-modify-counterbore.firmament@@ -6,7 +6,7 @@ Model ProfileComposeLBracketExternalModifyCounterbore {MountSpec { Center: Point2(20mm, -10mm) Diameter: 6mm }MountSpec { Center: Point2(-30mm, 20mm) Diameter: 6mm }]- Template BoltHole(MountSpec spec) {+ Template<spec: MountSpec> BoltHole {Hole<Shaft> Mount {On: +ZCenter: spec.Center@@ -37,7 +37,7 @@ Model ProfileComposeLBracketExternalModifyCounterbore {}Modify BracketBody {- Pattern BoltPattern Over Mounts { BoltHole(Current) }+ Pattern BoltPattern Over Mounts { BoltHole<Current> }Hole<Counterbore> LocatingPin {On: +ZCenter: Point2(-30mm, -10mm)diff --git a/fixtures/Canonical/valid/profile-template-delta-extrusion.firmament b/fixtures/Canonical/valid/profile-template-delta-extrusion.firmamentindex 39e97096..8a043dee 100644--- a/fixtures/Canonical/valid/profile-template-delta-extrusion.firmament+++ b/fixtures/Canonical/valid/profile-template-delta-extrusion.firmament@@ -2,7 +2,7 @@ Model ProfileDeltaPlate {Units: mmRecord LocalRecessSpec { Center: Length Lead: Length Run: Length Depth: Length Land: Length }- Template < P: LocalRecessSpec, Owner: ProfilePath >+ Template<P: LocalRecessSpec, Owner: ProfilePath>ProfileDelta LocalRecess {On: Owner;Anchor: CenteredAt P.Center;diff --git a/fixtures/Canonical/valid/record-array-pattern-holes.firmament b/fixtures/Canonical/valid/record-array-pattern-holes.firmamentindex cf7af3db..e4090973 100644--- a/fixtures/Canonical/valid/record-array-pattern-holes.firmament+++ b/fixtures/Canonical/valid/record-array-pattern-holes.firmament@@ -6,7 +6,7 @@ Model GeneratedMounts {MountSpec { Center: Point2(20mm, 0mm) Diameter: 8mm }]Require ValidDiameter => 8mm > 0mm- Template MountHole(MountSpec spec) {+ Template<spec: MountSpec> MountHole {Hole<Shaft> Mount {On: +ZCenter: spec.Center@@ -16,6 +16,6 @@ Model GeneratedMounts {}Box Base { Size: [80mm, 40mm, 10mm] }Modify Base {- Pattern MountPattern Over Mounts { MountHole(Current) }+ Pattern MountPattern Over Mounts { MountHole<Current> }}}diff --git a/fixtures/Canonical/valid/record-array-pattern-slots.firmament b/fixtures/Canonical/valid/record-array-pattern-slots.firmamentindex fc7ae42a..36c860fe 100644--- a/fixtures/Canonical/valid/record-array-pattern-slots.firmament+++ b/fixtures/Canonical/valid/record-array-pattern-slots.firmament@@ -11,7 +11,7 @@ Model GeneratedSlots {}]- Template Vent(SlotSpec spec) {+ Template<spec: SlotSpec> Vent {Slot<Capsule> Vent {Center: spec.CenterDirection: spec.Direction@@ -36,7 +36,7 @@ Model GeneratedSlots {Struct Plate {Compose Body {Base Stock { Profile: Plate; From: -10mm; To: 10mm; Role: Stock }- Pattern SlotPattern Over Vents { Vent(Current) }+ Pattern SlotPattern Over Vents { Vent<Current> }}}}diff --git a/fixtures/Canonical/valid/record-array-template-profile.firmament b/fixtures/Canonical/valid/record-array-template-profile.firmamentindex d9ece9c5..708b05be 100644--- a/fixtures/Canonical/valid/record-array-template-profile.firmament+++ b/fixtures/Canonical/valid/record-array-template-profile.firmament@@ -4,7 +4,7 @@ Model GeneratedProfile {Record ProfileSpec { Center: Point2 }Static Specs: ProfileSpec[] = [ ProfileSpec { Center: Point2(0mm, 0mm) } ]- Template PlateProfile(ProfileSpec spec) {+ Template<spec: ProfileSpec> PlateProfile {Profile Plate Using Layout {Loop Outer {Segment South { Trace: Stock.Bottom; From: Stock.BottomLeft; To: Stock.BottomRight }@@ -18,6 +18,6 @@ Model GeneratedProfile {Concept Struct Layout On XY {Rect2 Stock { Center: Specs[0].Center; Size: [20mm, 10mm] }}- PlateProfile(Specs[0])+ PlateProfile<Specs[0]>Struct PlateBody { Extrude Plate { Profile: Plate; From: -2mm; To: 2mm } }}diff --git a/fixtures/Canonical/valid/table-template-concept-path-compose.firmament b/fixtures/Canonical/valid/table-template-concept-path-compose.firmamentindex 28acca6e..bf17248a 100644--- a/fixtures/Canonical/valid/table-template-concept-path-compose.firmament+++ b/fixtures/Canonical/valid/table-template-concept-path-compose.firmament@@ -23,7 +23,7 @@ Model TableTemplateConceptPathCompose {Static ThickSmall = BaseSpec with {Thickness: 10mm}- Template < Spec: PlateSpec >+ Template<Spec: PlateSpec>Struct PlateTemplate {Require Positive => Spec.Standard.Width > 0mm && Spec.Standard.Height > 0mm && Spec.Thickness > 0mmConcept Path Outline {@@ -44,5 +44,5 @@ Model TableTemplateConceptPathCompose {Require: ClosedLoop}}- Struct Plate = PlateTemplate < Spec: ThickSmall >+ Struct Plate = PlateTemplate<Spec: ThickSmall>}diff --git a/fixtures/Templates/Canonical/cnc-dfm-policy.firmament b/fixtures/Templates/Canonical/cnc-dfm-policy.firmamentnew file mode 100644index 00000000..7d0991e5--- /dev/null+++ b/fixtures/Templates/Canonical/cnc-dfm-policy.firmament@@ -0,0 +1,63 @@+Concept CncManufacturingPolicy {+ MinimumToolRadius: Length+ MinimumWallThickness: Length+ MinimumFloorThickness: Length+ MinimumHoleDiameter: Length+}++Concept CncCouponContract {+ Bounds: Box3+ TopPlane: Plane+ ProbePoints: Point3[]+}++Record CncPolicySpec {+ MinimumToolRadius: Length+ MinimumWallThickness: Length+ MinimumFloorThickness: Length+ MinimumHoleDiameter: Length+}++Static CncShopDefaults: CncPolicySpec = CncPolicySpec {+ MinimumToolRadius: 0.5mm+ MinimumWallThickness: 0.8mm+ MinimumFloorThickness: 1.0mm+ MinimumHoleDiameter: 1.0mm+}++Static CncAluminum: CncPolicySpec = CncShopDefaults with {+ MinimumToolRadius: 0.75mm+ MinimumFloorThickness: 1.5mm+}++Template<Policy: CncPolicySpec>+Struct CncCoupon: CncCouponContract {+ Require PositiveLimits => Policy.MinimumToolRadius > 0mm && Policy.MinimumWallThickness > 0mm && Policy.MinimumFloorThickness > 0mm && Policy.MinimumHoleDiameter > 0mm+ Concept Struct Dfm: CncManufacturingPolicy {+ MinimumToolRadius: Policy.MinimumToolRadius+ MinimumWallThickness: Policy.MinimumWallThickness+ MinimumFloorThickness: Policy.MinimumFloorThickness+ MinimumHoleDiameter: Policy.MinimumHoleDiameter+ }+ Concept Struct Layout: CncCouponContract {+ Bounds: Box3 { Size: [30mm, 20mm, 6mm] }+ TopPlane: Bounds.Face(+Z)+ ProbePoints: Grid { Within: Bounds.Face(+Z).Inset(5mm); Columns: 1; Rows: 1 }+ }+ Box Coupon { Bounds: Layout.Bounds }+ Modify Coupon {+ Hole<Shaft> Probe {+ On: Coupon.Top+ Center: Layout.ProbePoints[0]+ Diameter: 4mm+ End: ThroughAll+ }+ }+ Expose {+ Bounds: Layout.Bounds+ TopPlane: Coupon.Top+ ProbePoints: Layout.ProbePoints+ }+}++Struct AluminumCoupon = CncCoupon<Policy: CncAluminum>diff --git a/fixtures/Templates/Canonical/fdm-dfm-policy.firmament b/fixtures/Templates/Canonical/fdm-dfm-policy.firmamentnew file mode 100644index 00000000..82e692da--- /dev/null+++ b/fixtures/Templates/Canonical/fdm-dfm-policy.firmament@@ -0,0 +1,62 @@+Concept FdmManufacturingPolicy {+ NozzleDiameter: Length+ MinimumWallThickness: Length+ MaximumUnsupportedOverhang: Angle+ LayerHeight: Length+}++Concept FdmCouponContract {+ Bounds: Box3+ TopPlane: Plane+ ProbePoints: Point3[]+}++Record FdmPolicySpec {+ NozzleDiameter: Length+ MinimumWallThickness: Length+ MaximumUnsupportedOverhang: Angle+ LayerHeight: Length+}++Static PrinterDefaults: FdmPolicySpec = FdmPolicySpec {+ NozzleDiameter: 0.4mm+ MinimumWallThickness: 0.8mm+ MaximumUnsupportedOverhang: 45deg+ LayerHeight: 0.2mm+}++Static BalancedSettings: FdmPolicySpec = PrinterDefaults with {+ LayerHeight: 0.12mm+}++Template<Policy: FdmPolicySpec>+Struct FdmCoupon: FdmCouponContract {+ Require PositiveLengths => Policy.NozzleDiameter > 0mm && Policy.MinimumWallThickness > 0mm && Policy.LayerHeight > 0mm+ Concept Struct Dfm: FdmManufacturingPolicy {+ NozzleDiameter: Policy.NozzleDiameter+ MinimumWallThickness: Policy.MinimumWallThickness+ MaximumUnsupportedOverhang: Policy.MaximumUnsupportedOverhang+ LayerHeight: Policy.LayerHeight+ }+ Concept Struct Layout: FdmCouponContract {+ Bounds: Box3 { Size: [20mm, 20mm, 4mm] }+ TopPlane: Bounds.Face(+Z)+ ProbePoints: Grid { Within: Bounds.Face(+Z).Inset(5mm); Columns: 1; Rows: 1 }+ }+ Box Coupon { Bounds: Layout.Bounds }+ Modify Coupon {+ Hole<Shaft> Probe {+ On: Coupon.Top+ Center: Layout.ProbePoints[0]+ Diameter: 4mm+ End: ThroughAll+ }+ }+ Expose {+ Bounds: Layout.Bounds+ TopPlane: Coupon.Top+ ProbePoints: Layout.ProbePoints+ }+}++Struct PrintedCoupon = FdmCoupon<Policy: BalancedSettings>diff --git a/fixtures/Templates/Canonical/generic-mounting-plate.firmament b/fixtures/Templates/Canonical/generic-mounting-plate.firmamentnew file mode 100644index 00000000..763cf193--- /dev/null+++ b/fixtures/Templates/Canonical/generic-mounting-plate.firmament@@ -0,0 +1,40 @@+Concept MountingPlateContract {+ Bounds: Box3+ TopPlane: Plane+ MountPoints: Point3[]+}++Template<Width: Length, Height: Length, Thickness: Length, HoleDiameter: Length>+Struct MountingPlate: MountingPlateContract {+ Require Positive => Width > 0mm && Height > 0mm && Thickness > 0mm && HoleDiameter > 0mm+ Concept Struct Design: MountingPlateContract {+ Bounds: Box3 { Size: [Width, Height, Thickness] }+ TopPlane: Bounds.Face(+Z)+ MountPoints: Grid {+ Within: Bounds.Face(+Z).Inset(10mm)+ Columns: 1+ Rows: 1+ }+ }+ Box Plate { Bounds: Design.Bounds }+ Modify Plate {+ Hole<Shaft> CenterMount {+ On: Plate.Top+ Center: Design.MountPoints[0]+ Diameter: HoleDiameter+ End: ThroughAll+ }+ }+ Expose {+ Bounds: Design.Bounds+ TopPlane: Plate.Top+ MountPoints: Design.MountPoints+ }+}++Struct StandardMountingPlate = MountingPlate<+ Width: 80mm,+ Height: 50mm,+ Thickness: 8mm,+ HoleDiameter: 8.5mm+>diff --git a/fixtures/Templates/Canonical/sheet-metal-dfm-policy.firmament b/fixtures/Templates/Canonical/sheet-metal-dfm-policy.firmamentnew file mode 100644index 00000000..f83eb178--- /dev/null+++ b/fixtures/Templates/Canonical/sheet-metal-dfm-policy.firmament@@ -0,0 +1,59 @@+Concept SheetMetalManufacturingPolicy {+ Thickness: Length+ MinimumBendRadius: Length+ KFactor: Float+}++Concept SheetMetalCouponContract {+ Bounds: Box3+ TopPlane: Plane+ ProbePoints: Point3[]+}++Record SheetMetalPolicySpec {+ Thickness: Length+ MinimumBendRadius: Length+ KFactor: Float+}++Static BrakeDefaults: SheetMetalPolicySpec = SheetMetalPolicySpec {+ Thickness: 1.5mm+ MinimumBendRadius: 1.5mm+ KFactor: 0.42+}++Static TightBend: SheetMetalPolicySpec = BrakeDefaults with {+ MinimumBendRadius: 2.0mm+}++Template<Policy: SheetMetalPolicySpec>+Struct SheetMetalCoupon: SheetMetalCouponContract {+ Require PositiveGeometry => Policy.Thickness > 0mm && Policy.MinimumBendRadius > 0mm+ Require PhysicalKFactor => Policy.KFactor > 0 && Policy.KFactor < 1+ Concept Struct Dfm: SheetMetalManufacturingPolicy {+ Thickness: Policy.Thickness+ MinimumBendRadius: Policy.MinimumBendRadius+ KFactor: Policy.KFactor+ }+ Concept Struct Layout: SheetMetalCouponContract {+ Bounds: Box3 { Size: [40mm, 20mm, Policy.Thickness] }+ TopPlane: Bounds.Face(+Z)+ ProbePoints: Grid { Within: Bounds.Face(+Z).Inset(5mm); Columns: 1; Rows: 1 }+ }+ Box Coupon { Bounds: Layout.Bounds }+ Modify Coupon {+ Hole<Shaft> Probe {+ On: Coupon.Top+ Center: Layout.ProbePoints[0]+ Diameter: 4mm+ End: ThroughAll+ }+ }+ Expose {+ Bounds: Layout.Bounds+ TopPlane: Coupon.Top+ ProbePoints: Layout.ProbePoints+ }+}++Struct TightBendCoupon = SheetMetalCoupon<Policy: TightBend>diff --git a/fixtures/Templates/valid/cnc-template-min-tool-radius-v2.valid.firmfixture b/fixtures/Templates/valid/cnc-template-min-tool-radius-v2.valid.firmfixtureindex b5d93190..dbc76aef 100644--- a/fixtures/Templates/valid/cnc-template-min-tool-radius-v2.valid.firmfixture+++ b/fixtures/Templates/valid/cnc-template-min-tool-radius-v2.valid.firmfixture@@ -7,7 +7,7 @@// expected: valid// expected-stage: not-implemented// expected-diagnostic: firmament-v2-parser-not-ready-// notes: AIR-FIRMAMENT-A2.3 metadata-only CNC template/concept fixture; not parser-backed.+// notes: Historical lowercase compatibility specimen. Canonical port: fixtures/Templates/Canonical/cnc-dfm-policy.firmament.template<CNC> ShopDefault {concept minimumToolRadius: 0.1 mmdiff --git a/fixtures/Templates/valid/fdm-template-wall-overhang-v2.valid.firmfixture b/fixtures/Templates/valid/fdm-template-wall-overhang-v2.valid.firmfixtureindex 87a9ded2..831806bf 100644--- a/fixtures/Templates/valid/fdm-template-wall-overhang-v2.valid.firmfixture+++ b/fixtures/Templates/valid/fdm-template-wall-overhang-v2.valid.firmfixture@@ -7,7 +7,7 @@// expected: valid// expected-stage: not-implemented// expected-diagnostic: firmament-v2-parser-not-ready-// notes: AIR-FIRMAMENT-A2.3 metadata-only FDM template/concept fixture; not parser-backed.+// notes: Historical lowercase compatibility specimen. Canonical port: fixtures/Templates/Canonical/fdm-dfm-policy.firmament.template<FDM> PrinterDefault {concept nozzleDiameter: 0.4 mmdiff --git a/fixtures/Templates/valid/sheet-metal-template-v2.valid.firmfixture b/fixtures/Templates/valid/sheet-metal-template-v2.valid.firmfixtureindex 7d2253cd..ee2cecb3 100644--- a/fixtures/Templates/valid/sheet-metal-template-v2.valid.firmfixture+++ b/fixtures/Templates/valid/sheet-metal-template-v2.valid.firmfixture@@ -7,7 +7,7 @@// expected: valid// expected-stage: not-implemented// expected-diagnostic: firmament-v2-parser-not-ready-// notes: AIR-FIRMAMENT-A2.3 metadata-only sheet metal template/concept fixture; not parser-backed.+// notes: Historical lowercase compatibility specimen. Canonical port: fixtures/Templates/Canonical/sheet-metal-dfm-policy.firmament.template<SheetMetal> ShopDefault {concept thickness: 1.5 mmdiff --git a/scripts/package-release.ps1 b/scripts/package-release.ps1index c65b0337..c5e4f0f4 100644--- a/scripts/package-release.ps1+++ b/scripts/package-release.ps1@@ -145,6 +145,10 @@ $publicExamples = @('fixtures/Canonical/valid/profile-compose-l-bracket-counterbore-pmi.firmament','fixtures/Canonical/valid/record-array-pattern-holes.firmament','fixtures/Canonical/valid/table-template-concept-path-compose.firmament',+ 'fixtures/Templates/Canonical/generic-mounting-plate.firmament',+ 'fixtures/Templates/Canonical/cnc-dfm-policy.firmament',+ 'fixtures/Templates/Canonical/fdm-dfm-policy.firmament',+ 'fixtures/Templates/Canonical/sheet-metal-dfm-policy.firmament','fixtures/FEA/cantilever.firmament','fixtures/FEA/inline-step-through-hole.firmament','fixtures/InlineStep/testdata/canonical-through-hole.step',@@ -174,6 +178,9 @@ $extensionRoot = Join-Path $repoRoot 'tools/vscode-firmament'$extensionArtifact = Join-Path $output 'aetheris-firmament-0.3.0-preview.3.vsix'Push-Location $extensionRoottry {+ # A prior local package must not be selected as input while vsce overwrites+ # that same path. This keeps repeated release qualification reproducible.+ Remove-Item -LiteralPath (Join-Path $extensionRoot 'dist/aetheris-firmament-0.3.0-preview.3.vsix') -Force -ErrorAction SilentlyContinuetspack synctspack checktspack run typecheckdiff --git a/tools/vscode-firmament/README.md b/tools/vscode-firmament/README.mdindex 860fa358..85ba09d3 100644--- a/tools/vscode-firmament/README.md+++ b/tools/vscode-firmament/README.md@@ -21,7 +21,7 @@ Structured CLI diagnostics populate VS Code Problems. Validate and build remain## Snippets-Use `model`, `box`, `cylinder`, `concept-path`, `profile-from-path`, `hole-shaft`, `hole-counterbore`, `hole-countersink`, `slot-capsule`, `edgefinish-chamfer`, `edgefinish-fillet`, `require`, `pmi-projection`, `assert-volume`, and `inline-step`.+Use `model`, `template`, `box`, `cylinder`, `concept-path`, `profile-from-path`, `hole-shaft`, `hole-counterbore`, `hole-countersink`, `slot-capsule`, `edgefinish-chamfer`, `edgefinish-fillet`, `require`, `pmi-projection`, `assert-volume`, and `inline-step`. The Template snippet always emits canonical `Template<...>` generic syntax.## Preview 3 limitsdiff --git a/tools/vscode-firmament/manifest.tsx b/tools/vscode-firmament/manifest.tsxindex 79d895c7..b1dbdc07 100644--- a/tools/vscode-firmament/manifest.tsx+++ b/tools/vscode-firmament/manifest.tsx@@ -88,13 +88,7 @@ export default define({name: "package",runtime: "node",- command: [- "vsce",- "package",- "--no-dependencies",- "--out",- "dist/aetheris-firmament-0.3.0-preview.3.vsix",- ],+ command: ["vsce", "package", "--no-dependencies", "--out", "dist/aetheris-firmament-0.3.0-preview.3.vsix"],},]}/>diff --git a/tools/vscode-firmament/snippets/firmament.json b/tools/vscode-firmament/snippets/firmament.jsonindex fa7b65c7..31e3f5e0 100644--- a/tools/vscode-firmament/snippets/firmament.json+++ b/tools/vscode-firmament/snippets/firmament.json@@ -172,6 +172,17 @@],"description": "Semantic requirement"},+ "Template": {+ "prefix": "template",+ "body": [+ "Template<${1:Spec}: ${2:PartSpec}>",+ "Struct ${3:PartFamily} {",+ " Require ${4:Admissible} => ${1:Spec}.${5:Width} > 0mm",+ " $0",+ "}"+ ],+ "description": "Typed compile-time engineering Template specialization"+ },"PMI Projection": {"prefix": "pmi-projection","body": [diff --git a/tools/vscode-firmament/tests/grammar.test.ts b/tools/vscode-firmament/tests/grammar.test.tsindex 86a4ba00..39526678 100644--- a/tools/vscode-firmament/tests/grammar.test.ts+++ b/tools/vscode-firmament/tests/grammar.test.ts@@ -31,6 +31,7 @@ async function grammar() {test("critical canonical syntax receives stable TextMate scopes", async () => {const loaded = await grammar();const source = `Model Plate {+ Template<Spec: PlateSpec> PlateFamily { }Sphere Ball { Radius: 5mm }Analysis LinearElastic Check { Body: Ball }Concept Path Outline On XY { Start: Point2(0mm, 0mm) }@@ -57,6 +58,7 @@ test("critical canonical syntax receives stable TextMate scopes", async () => {return token.scopes;};assert.ok(scopeAt("Model").includes("keyword.declaration.firmament"));+ assert.ok(scopeAt("Template").includes("keyword.declaration.firmament"));assert.ok(scopeAt("Sphere").includes("keyword.declaration.firmament"));assert.ok(scopeAt("Analysis").includes("keyword.declaration.firmament"));assert.ok(scopeAt("Boss").includes("keyword.declaration.firmament"));