Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add host-driven template expansion and Forge projects

Yuechen Li0eb1df9d7457
diff --git a/Aetheris.Forge.SampleExtension.Bindings/Aetheris.Forge.SampleExtension.Bindings.csproj b/Aetheris.Forge.SampleExtension.Bindings/Aetheris.Forge.SampleExtension.Bindings.csproj
new file mode 100644
index 00000000..8cb1e722
--- /dev/null
+++ b/Aetheris.Forge.SampleExtension.Bindings/Aetheris.Forge.SampleExtension.Bindings.csproj
@@ -0,0 +1,11 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>net10.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ </PropertyGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\Aetheris.Forge.Sdk\Aetheris.Forge.Sdk.csproj" />
+ <ProjectReference Include="..\Aetheris.Forge.SampleExtension\Aetheris.Forge.SampleExtension.csproj" />
+ </ItemGroup>
+</Project>
diff --git a/Aetheris.Forge.SampleExtension.Bindings/ForgeTemplates.g.cs b/Aetheris.Forge.SampleExtension.Bindings/ForgeTemplates.g.cs
new file mode 100644
index 00000000..b4cae557
--- /dev/null
+++ b/Aetheris.Forge.SampleExtension.Bindings/ForgeTemplates.g.cs
@@ -0,0 +1,24 @@
+using Aetheris.Forge.Sdk;
+
+namespace MyCompany.SecretGeometry.Generated;
+
+// Focused M1 generated-binding proof. A future generator owns this deterministic shape.
+public sealed record SecretCouponSpec(double WidthMillimeters, double DepthMillimeters, double HeightMillimeters);
+
+public static class ForgeTemplates
+{
+ public static ForgeInvocation SecretCoupon(
+ ForgeModule module,
+ SecretCouponSpec spec,
+ string instanceName = "SecretCoupon") =>
+ module.ResolveTemplate("SecretCoupon")
+ .Invoke(instanceName)
+ .Bind("Spec", new ForgeRecord(
+ "SecretCouponSpec",
+ new Dictionary<string, ForgeValue>(StringComparer.Ordinal)
+ {
+ ["Width"] = new ForgeLength(spec.WidthMillimeters),
+ ["Depth"] = new ForgeLength(spec.DepthMillimeters),
+ ["Height"] = new ForgeLength(spec.HeightMillimeters),
+ }));
+}
diff --git a/Aetheris.Forge.SampleExtension/Aetheris.Forge.SampleExtension.csproj b/Aetheris.Forge.SampleExtension/Aetheris.Forge.SampleExtension.csproj
new file mode 100644
index 00000000..f82bf369
--- /dev/null
+++ b/Aetheris.Forge.SampleExtension/Aetheris.Forge.SampleExtension.csproj
@@ -0,0 +1,13 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>net10.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ </PropertyGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\Aetheris.Forge\Aetheris.Forge.csproj" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="Templates\SecretGeometry.firmament" Pack="true" PackagePath="contentFiles\any\any\Templates" />
+ </ItemGroup>
+</Project>
diff --git a/Aetheris.Forge.SampleExtension/SecretGeometryExtension.cs b/Aetheris.Forge.SampleExtension/SecretGeometryExtension.cs
new file mode 100644
index 00000000..b16c2454
--- /dev/null
+++ b/Aetheris.Forge.SampleExtension/SecretGeometryExtension.cs
@@ -0,0 +1,78 @@
+using System.Globalization;
+using Aetheris.Forge.Extensions;
+using Aetheris.Kernel.Core.Construction;
+using Aetheris.Kernel.Core.Math;
+
+namespace MyCompany.SecretGeometry;
+
+public sealed class SecretGeometryExtension : IForgeExtension
+{
+ public const string ExtensionId = "MyCompany.SecretGeometry";
+ public static readonly Version ExtensionVersion = new(1, 0, 0);
+ public string Id => ExtensionId;
+ public Version Version => ExtensionVersion;
+ public void Register(ForgeExtensionRegistry registry) => registry.RegisterCapability(new SecretCouponCapability());
+}
+
+public sealed class SecretCouponCapability : IForgeCapability
+{
+ public static readonly ForgeCapabilityId CapabilityId = new("MyCompany.SecretGeometry.SecretCoupon");
+
+ public ForgeCapabilityDescriptorV1 Descriptor { get; } = new(
+ CapabilityId,
+ new Version(1, 0, 0),
+ SecretGeometryExtension.ExtensionId,
+ SecretGeometryExtension.ExtensionVersion,
+ "Private coupon sizing policy lowered to Aetheris standard prismatic ConstructionIR.",
+ [
+ new("Width", ForgeCapabilityParameterType.Length, Description: "Finished coupon width."),
+ new("Depth", ForgeCapabilityParameterType.Length, Description: "Finished coupon depth."),
+ new("Height", ForgeCapabilityParameterType.Length, Description: "Finished coupon height."),
+ ],
+ ForgeOutputClassification.ConstructionIr,
+ new HashSet<ForgeLoweringTarget> { ForgeLoweringTarget.ConstructionIr, ForgeLoweringTarget.Brep, ForgeLoweringTarget.Cir },
+ ForgeCapabilityDeterminism.Deterministic,
+ "Exact planar, linear, closed manifold prism; no mesh-derived geometry.",
+ "Width, Depth, and Height must be finite positive millimetre values.",
+ "MyCompany.SecretGeometry/SecretCoupon/v1");
+
+ public ForgeCapabilityExecutionResult Execute(ForgeCapabilityInvocationContext context, ForgeCapabilityArguments arguments)
+ {
+ var width = Positive(arguments.RequiredNumber("Width", ForgeCapabilityParameterType.Length), "Width");
+ var depth = Positive(arguments.RequiredNumber("Depth", ForgeCapabilityParameterType.Length), "Depth");
+ var height = Positive(arguments.RequiredNumber("Height", ForgeCapabilityParameterType.Length), "Height");
+ var profile = new[]
+ {
+ new Point3D(-width / 2d, -depth / 2d, 0d),
+ new Point3D(width / 2d, -depth / 2d, 0d),
+ new Point3D(width / 2d, depth / 2d, 0d),
+ new Point3D(-width / 2d, depth / 2d, 0d),
+ };
+ var signature = string.Join("x", new[] { width, depth, height }.Select(value => value.ToString("R", CultureInfo.InvariantCulture)));
+ var sourceIdentity = $"{CapabilityId.Value}@1.0.0:{signature}";
+ var descriptor = new ContinuumConstructionDescriptor(
+ sourceIdentity,
+ context.InvocationIdentity,
+ [new(-height / 2d, profile), new(height / 2d, profile)],
+ [0, 1, 2, 3],
+ ["PrismaticExtrude"],
+ [context.SourceIdentity, context.TemplateIdentity, CapabilityId.Value, SecretGeometryExtension.ExtensionId + "@1.0.0"]);
+ return ForgeCapabilityExecutionResult.Success(new ForgeCapabilityOutput(
+ descriptor,
+ ContinuumConstruction: descriptor,
+ Provenance: new Dictionary<string, string>(StringComparer.Ordinal)
+ {
+ ["capability"] = CapabilityId.Value + "@1.0.0",
+ ["extension"] = SecretGeometryExtension.ExtensionId + "@1.0.0",
+ ["source"] = context.SourceIdentity,
+ ["template"] = context.TemplateIdentity,
+ ["construction"] = sourceIdentity,
+ }));
+ }
+
+ private static double Positive(double value, string name)
+ {
+ if (!double.IsFinite(value) || value <= 0d) throw new ForgeCapabilityAdmissionException($"{name} must be finite and greater than zero.");
+ return value;
+ }
+}
diff --git a/Aetheris.Forge.SampleExtension/Templates/SecretGeometry.firmament b/Aetheris.Forge.SampleExtension/Templates/SecretGeometry.firmament
new file mode 100644
index 00000000..7b3f57ae
--- /dev/null
+++ b/Aetheris.Forge.SampleExtension/Templates/SecretGeometry.firmament
@@ -0,0 +1,14 @@
+Record SecretCouponSpec {
+ Width: Length
+ Depth: Length
+ Height: Length
+}
+
+Template < Spec: SecretCouponSpec >
+Struct SecretCoupon {
+ Construct MyCompany.SecretGeometry.SecretCoupon SecretBody {
+ Width: Spec.Width
+ Depth: Spec.Depth
+ Height: Spec.Height
+ }
+}
diff --git a/Aetheris.Forge.Sdk.Tests/Aetheris.Forge.Sdk.Tests.csproj b/Aetheris.Forge.Sdk.Tests/Aetheris.Forge.Sdk.Tests.csproj
new file mode 100644
index 00000000..efe86dd0
--- /dev/null
+++ b/Aetheris.Forge.Sdk.Tests/Aetheris.Forge.Sdk.Tests.csproj
@@ -0,0 +1,23 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>net10.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ <IsPackable>false</IsPackable>
+ </PropertyGroup>
+ <ItemGroup>
+ <PackageReference Include="coverlet.collector" Version="6.0.0" />
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
+ <PackageReference Include="xunit" Version="2.9.2" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
+ </ItemGroup>
+ <ItemGroup>
+ <Using Include="Xunit" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\Aetheris.Forge.Sdk\Aetheris.Forge.Sdk.csproj" />
+ <ProjectReference Include="..\Aetheris.Forge.SampleExtension\Aetheris.Forge.SampleExtension.csproj" />
+ <ProjectReference Include="..\Aetheris.Forge.SampleExtension.Bindings\Aetheris.Forge.SampleExtension.Bindings.csproj" />
+ <ProjectReference Include="..\Aetheris.Forge.Testing\Aetheris.Forge.Testing.csproj" />
+ </ItemGroup>
+</Project>
diff --git a/Aetheris.Forge.Sdk.Tests/ForgeSdkM1Tests.cs b/Aetheris.Forge.Sdk.Tests/ForgeSdkM1Tests.cs
new file mode 100644
index 00000000..53c034cb
--- /dev/null
+++ b/Aetheris.Forge.Sdk.Tests/ForgeSdkM1Tests.cs
@@ -0,0 +1,230 @@
+using Aetheris.Forge.Abstractions;
+using Aetheris.Forge.Extensions;
+using Aetheris.Forge.Sdk;
+using Aetheris.Forge.Testing;
+using MyCompany.SecretGeometry;
+using MyCompany.SecretGeometry.Generated;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.Forge.Sdk.Tests;
+
+public sealed class ForgeSdkM1Tests
+{
+ private static readonly string ModulePath = Path.Combine(
+ FindRepositoryRoot(),
+ "Aetheris.Forge.SampleExtension",
+ "Templates",
+ "SecretGeometry.firmament");
+
+ [Fact]
+ public void GeneratedBindingInvokesTemplateCapabilityAndValidatesBrepCirAndProvenance()
+ {
+ var host = Host();
+ var module = host.LoadModule(ModulePath);
+ var invocation = ForgeTemplates.SecretCoupon(module, new SecretCouponSpec(24d, 16d, 6d), "PrivateCoupon")
+ .WithTargets(ForgeLoweringTarget.Brep, ForgeLoweringTarget.Cir);
+
+ var first = invocation.Compile();
+ var second = ForgeTemplates.SecretCoupon(module, new SecretCouponSpec(24d, 16d, 6d), "PrivateCoupon")
+ .WithTargets(ForgeLoweringTarget.Brep, ForgeLoweringTarget.Cir)
+ .Compile();
+
+ ForgeExtensionAssertions.RequireDeterministic(first, second);
+ ForgeExtensionAssertions.RequireValidBrep(first.Artifact!.Body!);
+ ForgeExtensionAssertions.RequireStepRoundTrip(first.Artifact.StepText);
+ ForgeExtensionAssertions.RequireCompleteProvenance(first.Artifact);
+ ForgeExtensionAssertions.RequireCirAssociation(first.Artifact);
+ Assert.Single(first.Artifact.Capabilities);
+ Assert.Equal(SecretCouponCapability.CapabilityId.Value, first.Artifact.Capabilities[0].CapabilityId);
+ Assert.Contains("record-arguments=Spec", first.Artifact.Provenance[1].Evidence, StringComparison.Ordinal);
+ Assert.True(first.Artifact.Body!.Topology.Faces.Count() >= 6);
+ }
+
+ [Fact]
+ public void TemplateMetadataIsStableAndBindingMismatchStopsBeforeLowering()
+ {
+ var host = Host();
+ var module = host.LoadModule(ModulePath);
+ var template = module.ResolveTemplate("SecretCoupon");
+ Assert.Equal("SecretCoupon", template.Metadata.GeneratedBindingName);
+ var parameter = Assert.Single(template.Metadata.Parameters);
+ Assert.Equal("Spec", parameter.Name);
+ Assert.Equal("SecretCouponSpec", parameter.TypeName);
+
+ var result = template.Invoke("BadCoupon").Bind("Spec", new ForgeLength(10)).Compile();
+ Assert.False(result.IsSuccess);
+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == "forge-template-parameter-mismatch");
+ Assert.Equal(TimeSpan.Zero, result.ExtensionLoweringTime);
+ }
+
+ [Fact]
+ public void MissingExtensionProducesTypedDiagnostic()
+ {
+ var host = new ForgeHost(
+ manifest: new ForgeExtensionManifest([new(SecretGeometryExtension.ExtensionId, SecretGeometryExtension.ExtensionVersion)]));
+ var result = ForgeTemplates.SecretCoupon(host.LoadModule(ModulePath), new SecretCouponSpec(20, 12, 4)).Compile();
+ Assert.False(result.IsSuccess);
+ Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == "forge-extension-missing");
+ }
+
+ [Fact]
+ public void RegistryOrdersMultipleExtensionsAndRejectsCapabilityCollisions()
+ {
+ var registry = new ForgeExtensionRegistry();
+ registry.RegisterExtension(new NamedExtension("Zeta.Extension", "Zeta.Capability"));
+ registry.RegisterExtension(new NamedExtension("Alpha.Extension", "Alpha.Capability"));
+ Assert.Equal(new[] { "Alpha.Capability", "Zeta.Capability" }, registry.InspectCapabilities().Select(descriptor => descriptor.Id.Value));
+
+ var collision = Assert.Throws<ForgeExtensionRegistrationException>(() => registry.RegisterExtension(new NamedExtension("Collision.Extension", "Alpha.Capability")));
+ Assert.Equal("forge-capability-id-collision", collision.Code);
+ Assert.Equal(new[] { "Alpha.Capability", "Zeta.Capability" }, registry.InspectCapabilities().Select(descriptor => descriptor.Id.Value));
+ }
+
+ [Fact]
+ public void VersionConflictAndNonDeterministicCapabilitiesAreRejected()
+ {
+ var registry = new ForgeExtensionRegistry();
+ registry.RegisterExtension(new NamedExtension("Versioned.Extension", "Versioned.One"));
+ var conflict = Assert.Throws<ForgeExtensionRegistrationException>(() => registry.RegisterExtension(new NamedExtension("Versioned.Extension", "Versioned.Two", new Version(2, 0, 0))));
+ Assert.Equal("forge-extension-version-conflict", conflict.Code);
+
+ var nondeterministic = Assert.Throws<ForgeExtensionRegistrationException>(() => new ForgeExtensionRegistry().RegisterExtension(new NamedExtension("Random.Extension", "Random.Capability", determinism: ForgeCapabilityDeterminism.ExperimentalNonDeterministic)));
+ Assert.Equal("forge-capability-nondeterministic", nondeterministic.Code);
+ }
+
+ [Fact]
+ public void HostReportsRegistrationConflictAndExecutorWrapsPluginException()
+ {
+ var host = new ForgeHost([
+ new NamedExtension("First.Extension", SecretCouponCapability.CapabilityId.Value),
+ new NamedExtension("Second.Extension", SecretCouponCapability.CapabilityId.Value),
+ ]);
+ var compile = ForgeTemplates.SecretCoupon(host.LoadModule(ModulePath), new SecretCouponSpec(20, 12, 4)).Compile();
+ Assert.Contains(compile.Diagnostics, diagnostic => diagnostic.Code == "forge-capability-id-collision");
+
+ var registry = new ForgeExtensionRegistry();
+ registry.RegisterExtension(new ThrowingExtension());
+ var execution = ForgeCapabilityExecutor.Execute(
+ registry,
+ new ForgeCapabilityId("Throwing.Capability"),
+ new ForgeCapabilityInvocationContext("test", "test", "test", new HashSet<ForgeLoweringTarget> { ForgeLoweringTarget.ConstructionIr }),
+ new ForgeCapabilityArguments(new Dictionary<string, ForgeCapabilityValue>()));
+ Assert.False(execution.IsSuccess);
+ Assert.Contains(execution.Diagnostics, diagnostic => diagnostic.Code == "forge-capability-exception" && diagnostic.CapabilityId == "Throwing.Capability");
+ }
+
+ [Fact]
+ public void ImportedStepResourceUsesCanonicalStepPipelineEvidence()
+ {
+ var path = Path.Combine(FindRepositoryRoot(), "fixtures", "FirmamentV2", "InlineStep", "testdata", "canonical-box-10x8x6.step");
+ var resource = ImportedStepResource.Load("VendorPart", path);
+ Assert.True(resource.Canonical);
+ Assert.Equal(Path.GetFullPath(path), resource.Path);
+ Assert.Equal(64, resource.ContentHash.Length);
+ }
+
+ [Fact]
+ public void HostInvokesNativeFirmamentTemplateWithoutApplicationSourceGeneration()
+ {
+ const string source = """
+ Concept HostBoxConcept {
+ Bounds: Box3
+ TopPlane: Plane
+ ChamferDistance: Length
+ }
+ Template < Width: Length, Depth: Length, Height: Length >
+ Struct HostBox: HostBoxConcept {
+ Concept Struct Design: HostBoxConcept {
+ Bounds: Box3 {
+ Size: [Width, Depth, Height]
+ }
+ TopPlane: Bounds.Face(+Z)
+ ChamferDistance: 1mm
+ }
+ Box Body {
+ Bounds: Design.Bounds
+ }
+ Modify Body {
+ EdgeFinish TopBreak {
+ Face: Design.TopPlane
+ Target: Boundary
+ Kind: Chamfer
+ Distance: Design.ChamferDistance
+ }
+ }
+ Expose {
+ Bounds: Design.Bounds
+ TopPlane: Body.Top
+ ChamferDistance: Design.ChamferDistance
+ }
+ }
+ """;
+ var expanded = FirmamentTemplateHostBridge.Expand(source, "HostBox", "SdkBox", new Dictionary<string, FirmamentHostArgument>
+ {
+ ["Width"] = new("20mm"), ["Depth"] = new("12mm"), ["Height"] = new("5mm"),
+ }, out var bridgeDiagnostics);
+ Assert.NotNull(expanded);
+ var parsed = FirmamentV2Parser.Parse(expanded!.ExpandedSource);
+ Assert.True(parsed.IsSuccess, string.Join(Environment.NewLine, parsed.Diagnostics) + Environment.NewLine + expanded.ExpandedSource);
+ var result = new ForgeHost()
+ .LoadModule("NativeBox", source)
+ .ResolveTemplate("HostBox")
+ .Invoke("SdkBox")
+ .Bind("Width", new ForgeLength(20))
+ .Bind("Depth", new ForgeLength(12))
+ .Bind("Height", new ForgeLength(5))
+ .Compile();
+ ForgeExtensionAssertions.RequireSuccessfulCompilation(result);
+ ForgeExtensionAssertions.RequireStepRoundTrip(result.Artifact!.StepText);
+ Assert.Empty(result.Artifact.Capabilities);
+ }
+
+ private static ForgeHost Host() => new(
+ [new SecretGeometryExtension()],
+ new ForgeExtensionManifest([new(SecretGeometryExtension.ExtensionId, SecretGeometryExtension.ExtensionVersion)]));
+
+ private static string FindRepositoryRoot()
+ {
+ var directory = new DirectoryInfo(AppContext.BaseDirectory);
+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;
+ return directory?.FullName ?? throw new DirectoryNotFoundException("Aetheris repository root not found.");
+ }
+
+ private sealed class NamedExtension : IForgeExtension
+ {
+ private readonly string capabilityId;
+ private readonly ForgeCapabilityDeterminism determinism;
+ public NamedExtension(string id, string capabilityId, Version? version = null, ForgeCapabilityDeterminism determinism = ForgeCapabilityDeterminism.Deterministic)
+ { Id = id; this.capabilityId = capabilityId; Version = version ?? new Version(1, 0, 0); this.determinism = determinism; }
+ public string Id { get; }
+ public Version Version { get; }
+ public void Register(ForgeExtensionRegistry registry) => registry.RegisterCapability(new StubCapability(Id, Version, capabilityId, determinism));
+ }
+
+ private sealed class StubCapability : IForgeCapability
+ {
+ public StubCapability(string extension, Version extensionVersion, string id, ForgeCapabilityDeterminism determinism) => Descriptor = new(
+ new(id), new Version(1, 0, 0), extension, extensionVersion, "test", [], ForgeOutputClassification.SemanticOnly,
+ new HashSet<ForgeLoweringTarget> { ForgeLoweringTarget.ConstructionIr }, determinism, "semantic", "test", extension + "/" + id);
+ public ForgeCapabilityDescriptorV1 Descriptor { get; }
+ public ForgeCapabilityExecutionResult Execute(ForgeCapabilityInvocationContext context, ForgeCapabilityArguments arguments) =>
+ ForgeCapabilityExecutionResult.Failure(new ForgeExtensionDiagnostic("not-invoked", ForgeDiagnosticSeverity.Error, "test"));
+ }
+
+ private sealed class ThrowingExtension : IForgeExtension
+ {
+ public string Id => "Throwing.Extension";
+ public Version Version => new(1, 0, 0);
+ public void Register(ForgeExtensionRegistry registry) => registry.RegisterCapability(new ThrowingCapability());
+ }
+
+ private sealed class ThrowingCapability : IForgeCapability
+ {
+ public ForgeCapabilityDescriptorV1 Descriptor { get; } = new(
+ new("Throwing.Capability"), new Version(1, 0, 0), "Throwing.Extension", new Version(1, 0, 0), "test", [],
+ ForgeOutputClassification.ConstructionIr, new HashSet<ForgeLoweringTarget> { ForgeLoweringTarget.ConstructionIr },
+ ForgeCapabilityDeterminism.Deterministic, "exact", "test", "throwing/test");
+ public ForgeCapabilityExecutionResult Execute(ForgeCapabilityInvocationContext context, ForgeCapabilityArguments arguments) =>
+ throw new InvalidOperationException("private implementation detail");
+ }
+}
diff --git a/Aetheris.Forge.Sdk/Aetheris.Forge.Sdk.csproj b/Aetheris.Forge.Sdk/Aetheris.Forge.Sdk.csproj
new file mode 100644
index 00000000..c4f89247
--- /dev/null
+++ b/Aetheris.Forge.Sdk/Aetheris.Forge.Sdk.csproj
@@ -0,0 +1,12 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>net10.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ </PropertyGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\Aetheris.Forge\Aetheris.Forge.csproj" />
+ <ProjectReference Include="..\Aetheris.Kernel.Firmament\Aetheris.Kernel.Firmament.csproj" />
+ <ProjectReference Include="..\Aetheris.Continuum\Aetheris.Continuum.csproj" />
+ </ItemGroup>
+</Project>
diff --git a/Aetheris.Forge.Sdk/ForgeHost.cs b/Aetheris.Forge.Sdk/ForgeHost.cs
new file mode 100644
index 00000000..54a9d421
--- /dev/null
+++ b/Aetheris.Forge.Sdk/ForgeHost.cs
@@ -0,0 +1,484 @@
+using System.Diagnostics;
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.RegularExpressions;
+using Aetheris.Continuum.Boundaries;
+using Aetheris.Continuum.Cir;
+using Aetheris.Continuum.Regions.Analytic;
+using Aetheris.Forge.Abstractions;
+using Aetheris.Forge.Extensions;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.Forge.Sdk;
+
+public sealed class ForgeHost
+{
+ private readonly ForgeExtensionRegistry registry;
+ private readonly ForgeExtensionManifest manifest;
+ private readonly TimeSpan registrationTime;
+ private readonly IReadOnlyList<ForgeDiagnostic> registrationDiagnostics;
+
+ public ForgeHost(
+ IEnumerable<IForgeExtension>? extensions = null,
+ ForgeExtensionManifest? manifest = null)
+ {
+ registry = new ForgeExtensionRegistry();
+ var start = Stopwatch.GetTimestamp();
+ var registrationFailures = new List<ForgeDiagnostic>();
+ foreach (var extension in extensions ?? [])
+ {
+ try { registry.RegisterExtension(extension); }
+ catch (ForgeExtensionRegistrationException exception)
+ {
+ registrationFailures.Add(Error(exception.Code, exception.Message, extension.Id));
+ }
+ }
+ registrationTime = Stopwatch.GetElapsedTime(start);
+ registrationDiagnostics = registrationFailures;
+ this.manifest = manifest ?? new ForgeExtensionManifest();
+ }
+
+ public IReadOnlyList<ForgeCapabilityDescriptorV1> Capabilities => registry.InspectCapabilities();
+
+ public ForgeModule LoadModule(string path)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(path);
+ var fullPath = Path.GetFullPath(path);
+ return LoadModule(Path.GetFileNameWithoutExtension(fullPath), File.ReadAllText(fullPath), fullPath);
+ }
+
+ public ForgeModule LoadModule(string name, string source, string? sourcePath = null)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(name);
+ ArgumentNullException.ThrowIfNull(source);
+ var metadata = FirmamentTemplateHostBridge.Inspect(source, out var diagnostics);
+ return new ForgeModule(
+ this,
+ name,
+ source,
+ sourcePath,
+ metadata.Select(template => new ForgeTemplateMetadata(
+ name,
+ template.Name,
+ template.TargetKind,
+ template.Parameters.Select(parameter => new ForgeTemplateParameter(
+ parameter.Name,
+ parameter.TypeName,
+ parameter.Kind == FirmamentTemplateParameterKind.Type,
+ parameter.DefaultExpression,
+ parameter.ConstraintConcept)).ToArray(),
+ ForgeGeneratedNames.TemplateMethod(template.Name))).ToArray(),
+ diagnostics.Select(code => Error(code, code, sourcePath)).ToArray());
+ }
+
+ internal ForgeCompilationResult Compile(ForgeInvocation invocation)
+ {
+ var diagnostics = new List<ForgeDiagnostic>();
+ diagnostics.AddRange(invocation.Module.LoadDiagnostics);
+ diagnostics.AddRange(registrationDiagnostics);
+ diagnostics.AddRange(registry.ValidateManifest(manifest).Select(FromExtensionDiagnostic));
+ if (diagnostics.Any(diagnostic => diagnostic.Severity == ForgeDiagnosticSeverity.Error))
+ return Failure(diagnostics);
+
+ var bindDiagnostics = ValidateTemplateBindings(invocation);
+ diagnostics.AddRange(bindDiagnostics);
+ if (bindDiagnostics.Count > 0) return Failure(diagnostics);
+
+ var hostArguments = invocation.Bindings.ToDictionary(
+ pair => pair.Key,
+ pair => pair.Value is ForgeRecord record
+ ? new FirmamentHostArgument(
+ record.RecordType,
+ record.RecordType,
+ record.Fields.ToDictionary(field => field.Key, field => field.Value.CanonicalLiteral, StringComparer.Ordinal))
+ : new FirmamentHostArgument(pair.Value.CanonicalLiteral),
+ StringComparer.Ordinal);
+ var invocationStart = Stopwatch.GetTimestamp();
+ var expansion = FirmamentTemplateHostBridge.Expand(
+ invocation.Module.Source,
+ invocation.Template.Metadata.Name,
+ invocation.InstanceName,
+ hostArguments,
+ out var expansionDiagnostics);
+ var invocationTime = Stopwatch.GetElapsedTime(invocationStart);
+ diagnostics.AddRange(expansionDiagnostics.Select(code => Error(code, code, invocation.Module.SourcePath)));
+ if (expansion is null) return Failure(diagnostics, invocationTime: invocationTime);
+
+ var constructs = ForgeConstructParser.Parse(expansion.ExpandedSource, diagnostics);
+ if (diagnostics.Any(diagnostic => diagnostic.Severity == ForgeDiagnosticSeverity.Error))
+ return Failure(diagnostics, invocationTime: invocationTime);
+ if (constructs.Count == 0)
+ return CompileNative(invocation, expansion, diagnostics, invocationTime);
+ if (constructs.Count != 1)
+ {
+ diagnostics.Add(Error("forge-m1-multiple-construction-outputs-unsupported", "M1 admits exactly one materialized Construct output per host invocation.", invocation.Module.SourcePath));
+ return Failure(diagnostics, invocationTime: invocationTime);
+ }
+
+ var resolutionStart = Stopwatch.GetTimestamp();
+ var construct = constructs[0];
+ var id = new ForgeCapabilityId(construct.CapabilityId);
+ var resolved = registry.TryResolve(id, out var capability);
+ var resolutionTime = Stopwatch.GetElapsedTime(resolutionStart);
+ if (!resolved)
+ {
+ diagnostics.Add(Error("forge-capability-missing", $"Capability '{id}' required by Template '{invocation.Template.Metadata.Name}' is not registered.", invocation.Module.SourcePath, id.Value));
+ return Failure(diagnostics, invocationTime, resolutionTime);
+ }
+
+ var arguments = BindCapabilityArguments(capability.Descriptor, construct, invocation.Resources, diagnostics);
+ if (arguments is null) return Failure(diagnostics, invocationTime, resolutionTime);
+ var context = new ForgeCapabilityInvocationContext(
+ construct.InstanceName,
+ invocation.Module.SourcePath ?? invocation.Module.Name,
+ expansion.SpecializationIdentity,
+ invocation.RequestedTargets);
+ var extensionStart = Stopwatch.GetTimestamp();
+ var execution = ForgeCapabilityExecutor.Execute(registry, id, context, arguments);
+ var extensionTime = Stopwatch.GetElapsedTime(extensionStart);
+ diagnostics.AddRange(execution.Diagnostics.Select(FromExtensionDiagnostic));
+ if (!execution.IsSuccess || execution.Output is null)
+ return Failure(diagnostics, invocationTime, resolutionTime, extensionTime);
+
+ var compilerStart = Stopwatch.GetTimestamp();
+ BrepBody body;
+ try
+ {
+ body = execution.Output.ExactBrep
+ ?? ForgeCapabilityExecutor.MaterializeConstruction(execution.Output.Construction
+ ?? throw new ForgeCapabilityAdmissionException("Capability emitted neither standard ConstructionIR nor ExactBRep."));
+ }
+ catch (Exception exception) when (exception is ForgeCapabilityAdmissionException or ArgumentException or InvalidOperationException)
+ {
+ diagnostics.Add(Error("forge-capability-output-invalid", exception.Message, invocation.Module.SourcePath, id.Value));
+ return Failure(diagnostics, invocationTime, resolutionTime, extensionTime);
+ }
+ var bindingValidation = BrepBindingValidator.Validate(body, true);
+ if (!bindingValidation.IsSuccess)
+ {
+ diagnostics.Add(Error("forge-capability-brep-invalid", string.Join("; ", bindingValidation.Diagnostics.Select(item => item.Message)), invocation.Module.SourcePath, id.Value));
+ return Failure(diagnostics, invocationTime, resolutionTime, extensionTime);
+ }
+ var exported = Step242Exporter.ExportBody(body, new Step242ExportOptions { ProductName = construct.InstanceName });
+ if (!exported.IsSuccess)
+ {
+ diagnostics.Add(Error("forge-capability-step-export-failed", string.Join("; ", exported.Diagnostics.Select(item => item.Message)), invocation.Module.SourcePath, id.Value));
+ return Failure(diagnostics, invocationTime, resolutionTime, extensionTime);
+ }
+ var reimport = Step242Importer.ImportBody(exported.Value);
+ if (!reimport.IsSuccess || reimport.Value is null)
+ {
+ diagnostics.Add(Error("forge-capability-step-reimport-failed", string.Join("; ", reimport.Diagnostics.Select(item => item.Message)), invocation.Module.SourcePath, id.Value));
+ return Failure(diagnostics, invocationTime, resolutionTime, extensionTime);
+ }
+
+ ForgeCirEvidence? cir = null;
+ if (invocation.RequestedTargets.Contains(ForgeLoweringTarget.Cir))
+ {
+ cir = ValidateBoxCir(execution.Output.ContinuumConstruction ?? execution.Output.Construction, body, construct.InstanceName, diagnostics);
+ if (cir is null) return Failure(diagnostics, invocationTime, resolutionTime, extensionTime);
+ }
+ var compilerTime = Stopwatch.GetElapsedTime(compilerStart);
+ var descriptor = capability.Descriptor;
+ var capabilityEvidence = new ForgeCapabilityEvidence(
+ descriptor.Id.Value,
+ descriptor.Version.ToString(),
+ descriptor.ExtensionId,
+ descriptor.ExtensionVersion.ToString(),
+ descriptor.OutputClassification.ToString(),
+ descriptor.SupportedTargets.OrderBy(target => target).Select(target => target.ToString()).ToArray());
+ var provenance = new[]
+ {
+ new ForgeProvenanceEntry("host", invocation.Module.SourcePath ?? invocation.Module.Name, invocation.InstanceName),
+ new ForgeProvenanceEntry("template", invocation.Template.Metadata.Name, expansion.SpecializationIdentity + ";record-arguments=" + string.Join(",", expansion.RecordArguments.Keys.Order(StringComparer.Ordinal))),
+ new ForgeProvenanceEntry("capability", descriptor.Id.Value, $"{descriptor.ExtensionId}@{descriptor.ExtensionVersion};{descriptor.ProvenanceIdentity}"),
+ new ForgeProvenanceEntry("construction", execution.Output.Construction?.SourceIdentity ?? "exact-brep", execution.Output.Construction?.SemanticRegionIdentity ?? construct.InstanceName),
+ new ForgeProvenanceEntry("artifact", construct.InstanceName, "STEP AP242 export and reimport validated"),
+ };
+ var hash = ArtifactHash(exported.Value, expansion.SpecializationIdentity, [capabilityEvidence], provenance);
+ return new ForgeCompilationResult(
+ new ForgeCompilationArtifact(exported.Value, hash, body, cir, [capabilityEvidence], provenance),
+ diagnostics,
+ registrationTime,
+ resolutionTime,
+ invocationTime,
+ extensionTime,
+ compilerTime);
+ }
+
+ private ForgeCompilationResult CompileNative(
+ ForgeInvocation invocation,
+ FirmamentHostTemplateExpansion expansion,
+ List<ForgeDiagnostic> diagnostics,
+ TimeSpan invocationTime)
+ {
+ var start = Stopwatch.GetTimestamp();
+ var result = FirmamentBuildAndExport.CompileSource(expansion.ExpandedSource, invocation.Module.SourcePath is null ? null : Path.GetDirectoryName(invocation.Module.SourcePath));
+ var compilerTime = Stopwatch.GetElapsedTime(start);
+ diagnostics.AddRange(result.Diagnostics.Select(item => new ForgeDiagnostic(
+ item.Code.ToString(),
+ item.Severity == Aetheris.Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error ? ForgeDiagnosticSeverity.Error : ForgeDiagnosticSeverity.Warning,
+ item.Message,
+ item.Source)));
+ if (!result.IsSuccess) return Failure(diagnostics, invocationTime: invocationTime, compilerTime: compilerTime);
+ var provenance = new[]
+ {
+ new ForgeProvenanceEntry("host", invocation.Module.SourcePath ?? invocation.Module.Name, invocation.InstanceName),
+ new ForgeProvenanceEntry("template", invocation.Template.Metadata.Name, expansion.SpecializationIdentity + ";record-arguments=" + string.Join(",", expansion.RecordArguments.Keys.Order(StringComparer.Ordinal))),
+ new ForgeProvenanceEntry("artifact", result.Value.ExportedFeatureId, result.Value.ExportedFeatureKind ?? result.Value.ExportedBodyCategory),
+ };
+ var hash = ArtifactHash(result.Value.StepText, expansion.SpecializationIdentity, [], provenance);
+ return new ForgeCompilationResult(
+ new ForgeCompilationArtifact(result.Value.StepText, hash, null, null, [], provenance),
+ diagnostics,
+ registrationTime,
+ TimeSpan.Zero,
+ invocationTime,
+ TimeSpan.Zero,
+ compilerTime);
+ }
+
+ private static IReadOnlyList<ForgeDiagnostic> ValidateTemplateBindings(ForgeInvocation invocation)
+ {
+ var diagnostics = new List<ForgeDiagnostic>();
+ var schema = invocation.Template.Metadata.Parameters.ToDictionary(parameter => parameter.Name, StringComparer.Ordinal);
+ foreach (var parameter in schema.Values.Where(parameter => parameter.DefaultValue is null))
+ if (!invocation.Bindings.ContainsKey(parameter.Name)) diagnostics.Add(Error("forge-template-parameter-missing", $"Template parameter '{parameter.Name}' is required.", invocation.Module.SourcePath));
+ foreach (var binding in invocation.Bindings)
+ {
+ if (!schema.TryGetValue(binding.Key, out var parameter))
+ diagnostics.Add(Error("forge-template-parameter-unknown", $"Template parameter '{binding.Key}' is not declared.", invocation.Module.SourcePath));
+ else if (parameter.IsTypeParameter && binding.Value is not ForgeType)
+ diagnostics.Add(Error("forge-template-parameter-mismatch", $"Template parameter '{binding.Key}' requires a type argument.", invocation.Module.SourcePath));
+ else if (!parameter.IsTypeParameter && binding.Value is ForgeRecord record && !string.Equals(record.RecordType, parameter.TypeName, StringComparison.Ordinal))
+ diagnostics.Add(Error("forge-template-parameter-mismatch", $"Template parameter '{binding.Key}' expects Record '{parameter.TypeName}' but received '{record.RecordType}'.", invocation.Module.SourcePath));
+ else if (!parameter.IsTypeParameter && binding.Value is not ForgeRecord && !string.Equals(binding.Value.TypeName, parameter.TypeName, StringComparison.Ordinal))
+ diagnostics.Add(Error("forge-template-parameter-mismatch", $"Template parameter '{binding.Key}' expects '{parameter.TypeName}' but received '{binding.Value.TypeName}'.", invocation.Module.SourcePath));
+ }
+ return diagnostics;
+ }
+
+ private static ForgeCapabilityArguments? BindCapabilityArguments(
+ ForgeCapabilityDescriptorV1 descriptor,
+ ForgeConstruct construct,
+ IReadOnlyDictionary<string, ForgeResource> resources,
+ ICollection<ForgeDiagnostic> diagnostics)
+ {
+ var result = new Dictionary<string, ForgeCapabilityValue>(StringComparer.Ordinal);
+ var schema = descriptor.Inputs.ToDictionary(input => input.Name, StringComparer.Ordinal);
+ foreach (var pair in construct.Fields)
+ {
+ if (!schema.TryGetValue(pair.Key, out var parameter))
+ {
+ diagnostics.Add(Error("forge-capability-parameter-unknown", $"Capability '{descriptor.Id}' has no parameter '{pair.Key}'.", null, descriptor.Id.Value));
+ continue;
+ }
+ if (!TryParseCapabilityValue(parameter.Type, pair.Value, resources, out var value, out var message))
+ diagnostics.Add(Error("forge-capability-parameter-mismatch", $"Parameter '{pair.Key}': {message}", null, descriptor.Id.Value));
+ else result[pair.Key] = value;
+ }
+ foreach (var parameter in descriptor.Inputs.Where(input => input.Required && input.DefaultValue is null))
+ if (!result.ContainsKey(parameter.Name)) diagnostics.Add(Error("forge-capability-parameter-missing", $"Capability parameter '{parameter.Name}' is required.", null, descriptor.Id.Value));
+ return diagnostics.Any(diagnostic => diagnostic.Severity == ForgeDiagnosticSeverity.Error) ? null : new ForgeCapabilityArguments(result);
+ }
+
+ private static bool TryParseCapabilityValue(
+ ForgeCapabilityParameterType type,
+ string text,
+ IReadOnlyDictionary<string, ForgeResource> resources,
+ out ForgeCapabilityValue value,
+ out string message)
+ {
+ text = text.Trim();
+ if (type == ForgeCapabilityParameterType.ImportedStepResource)
+ {
+ var name = text.TrimStart('$');
+ if (resources.TryGetValue(name, out var resource) && resource is ImportedStepResource step && step.Canonical)
+ {
+ value = new(type, step, step.ContentHash); message = string.Empty; return true;
+ }
+ value = null!; message = $"resource '{name}' is missing or is not canonical Aetheris STEP"; return false;
+ }
+ if (type == ForgeCapabilityParameterType.String && text.StartsWith('"') && text.EndsWith('"'))
+ {
+ value = new(type, text[1..^1], text); message = string.Empty; return true;
+ }
+ if (type == ForgeCapabilityParameterType.Boolean && bool.TryParse(text, out var boolean))
+ {
+ value = new(type, boolean, boolean ? "true" : "false"); message = string.Empty; return true;
+ }
+ var numericText = type switch
+ {
+ ForgeCapabilityParameterType.Length when text.EndsWith("mm", StringComparison.Ordinal) => text[..^2],
+ ForgeCapabilityParameterType.Angle when text.EndsWith("deg", StringComparison.Ordinal) => text[..^3],
+ _ => text,
+ };
+ if (double.TryParse(numericText, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) && double.IsFinite(number))
+ {
+ value = new(type, number, text); message = string.Empty; return true;
+ }
+ value = null!; message = $"'{text}' is not a valid {type} value"; return false;
+ }
+
+ private static ForgeCirEvidence? ValidateBoxCir(
+ Aetheris.Kernel.Core.Construction.ContinuumConstructionDescriptor? descriptor,
+ BrepBody body,
+ string identity,
+ ICollection<ForgeDiagnostic> diagnostics)
+ {
+ if (descriptor is null || descriptor.Sections.Count != 2)
+ {
+ diagnostics.Add(Error("forge-capability-cir-output-missing", "CIR was requested but the capability did not emit a supported continuum construction descriptor.", null));
+ return null;
+ }
+ var points = descriptor.Sections.SelectMany(section => section.ProfileVertices.Select(point => new Point3D(point.X, point.Y, section.AxialPosition))).ToArray();
+ var bounds = new BoundingBox3D(
+ new Point3D(points.Min(point => point.X), points.Min(point => point.Y), points.Min(point => point.Z)),
+ new Point3D(points.Max(point => point.X), points.Max(point => point.Y), points.Max(point => point.Z)));
+ var region = new AxisAlignedBoxRegion(new RegionId(identity + ":cir"), bounds);
+ var association = new CirBrepAssociation(
+ region.Id,
+ identity,
+ body.ShellRepresentation!.OuterShellId.Value.ToString(CultureInfo.InvariantCulture),
+ identity,
+ descriptor.SourceIdentity);
+ var shell = new WholeShellBoundaryQuery(body, association, Transform3D.Identity);
+ var consistency = BrepCirConsistencyChecker.Check(region, shell);
+ if (!consistency.Passed)
+ {
+ diagnostics.Add(Error("forge-capability-cir-brep-inconsistent", consistency.Summary, null));
+ return null;
+ }
+ return new ForgeCirEvidence(association, consistency);
+ }
+
+ private ForgeCompilationResult Failure(
+ IReadOnlyList<ForgeDiagnostic> diagnostics,
+ TimeSpan invocationTime = default,
+ TimeSpan resolutionTime = default,
+ TimeSpan extensionTime = default,
+ TimeSpan compilerTime = default) =>
+ new(null, diagnostics, registrationTime, resolutionTime, invocationTime, extensionTime, compilerTime);
+
+ private static ForgeDiagnostic Error(string code, string message, string? source, string? capabilityId = null) =>
+ new(code, ForgeDiagnosticSeverity.Error, message, source, capabilityId);
+
+ private static ForgeDiagnostic FromExtensionDiagnostic(ForgeExtensionDiagnostic diagnostic) =>
+ new(diagnostic.Code, diagnostic.Severity, diagnostic.Message, diagnostic.SourceIdentity, diagnostic.CapabilityId);
+
+ private static string ArtifactHash(
+ string step,
+ string specialization,
+ IReadOnlyList<ForgeCapabilityEvidence> capabilities,
+ IReadOnlyList<ForgeProvenanceEntry> provenance)
+ {
+ var canonical = new StringBuilder(step).Append('\n').Append(specialization).Append('\n');
+ foreach (var capability in capabilities.OrderBy(item => item.CapabilityId, StringComparer.Ordinal))
+ canonical.Append(capability.CapabilityId).Append('@').Append(capability.CapabilityVersion).Append('|').Append(capability.ExtensionId).Append('@').Append(capability.ExtensionVersion).Append('\n');
+ foreach (var entry in provenance) canonical.Append(entry.Stage).Append('|').Append(entry.Identity).Append('|').Append(entry.Evidence).Append('\n');
+ return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(canonical.ToString())));
+ }
+}
+
+public sealed class ForgeModule
+{
+ internal ForgeModule(ForgeHost host, string name, string source, string? sourcePath, IReadOnlyList<ForgeTemplateMetadata> templates, IReadOnlyList<ForgeDiagnostic> loadDiagnostics)
+ {
+ Host = host; Name = name; Source = source; SourcePath = sourcePath; Templates = templates; LoadDiagnostics = loadDiagnostics;
+ }
+ internal ForgeHost Host { get; }
+ public string Name { get; }
+ public string Source { get; }
+ public string? SourcePath { get; }
+ public IReadOnlyList<ForgeTemplateMetadata> Templates { get; }
+ internal IReadOnlyList<ForgeDiagnostic> LoadDiagnostics { get; }
+ public ForgeTemplate ResolveTemplate(string name)
+ {
+ var metadata = Templates.SingleOrDefault(template => template.Name == name)
+ ?? throw new KeyNotFoundException($"Template '{name}' was not found in module '{Name}'.");
+ return new ForgeTemplate(this, metadata);
+ }
+}
+
+public sealed record ForgeTemplate(ForgeModule Module, ForgeTemplateMetadata Metadata)
+{
+ public ForgeInvocation Invoke(string instanceName) => new(Module.Host, Module, this, instanceName);
+}
+
+public sealed class ForgeInvocation
+{
+ private readonly Dictionary<string, ForgeValue> bindings = new(StringComparer.Ordinal);
+ private readonly Dictionary<string, ForgeResource> resources = new(StringComparer.Ordinal);
+ internal ForgeInvocation(ForgeHost host, ForgeModule module, ForgeTemplate template, string instanceName)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(instanceName);
+ Host = host; Module = module; Template = template; InstanceName = instanceName;
+ }
+ internal ForgeHost Host { get; }
+ public ForgeModule Module { get; }
+ public ForgeTemplate Template { get; }
+ public string InstanceName { get; }
+ internal IReadOnlyDictionary<string, ForgeValue> Bindings => bindings;
+ internal IReadOnlyDictionary<string, ForgeResource> Resources => resources;
+ internal IReadOnlySet<ForgeLoweringTarget> RequestedTargets { get; private set; } = new HashSet<ForgeLoweringTarget> { ForgeLoweringTarget.Brep };
+ public ForgeInvocation Bind(string name, ForgeValue value) { ArgumentNullException.ThrowIfNull(value); bindings[name] = value; return this; }
+ public ForgeInvocation AddResource(ForgeResource resource) { ArgumentNullException.ThrowIfNull(resource); resources[resource.Name] = resource; return this; }
+ public ForgeInvocation WithTargets(params ForgeLoweringTarget[] targets) { RequestedTargets = targets.ToHashSet(); return this; }
+ public ForgeCompilationResult Compile() => Host.Compile(this);
+}
+
+public static class ForgeGeneratedNames
+{
+ public static string TemplateMethod(string templateName)
+ {
+ var cleaned = Regex.Replace(templateName, "[^A-Za-z0-9_]", "_", RegexOptions.CultureInvariant);
+ return char.IsDigit(cleaned[0]) ? "Template_" + cleaned : cleaned;
+ }
+}
+
+internal sealed record ForgeConstruct(string CapabilityId, string InstanceName, IReadOnlyDictionary<string, string> Fields);
+
+internal static class ForgeConstructParser
+{
+ private static readonly Regex Header = new(@"\bConstruct\s+(?<capability>[A-Za-z_][A-Za-z0-9_.-]*)\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*\{", RegexOptions.CultureInvariant);
+ private static readonly Regex Field = new(@"(?m)^\s*(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<value>[^\r\n}]+)\s*$", RegexOptions.CultureInvariant);
+
+ public static IReadOnlyList<ForgeConstruct> Parse(string source, ICollection<ForgeDiagnostic> diagnostics)
+ {
+ var result = new List<ForgeConstruct>();
+ foreach (Match header in Header.Matches(source))
+ {
+ var open = source.IndexOf('{', header.Index);
+ var close = MatchingBrace(source, open);
+ if (close < 0)
+ {
+ diagnostics.Add(new ForgeDiagnostic("forge-construct-malformed", ForgeDiagnosticSeverity.Error, "Construct block is missing its closing brace."));
+ continue;
+ }
+ var fields = new Dictionary<string, string>(StringComparer.Ordinal);
+ foreach (Match field in Field.Matches(source[(open + 1)..close]))
+ {
+ if (!fields.TryAdd(field.Groups["name"].Value, field.Groups["value"].Value.Trim()))
+ diagnostics.Add(new ForgeDiagnostic("forge-construct-parameter-duplicate", ForgeDiagnosticSeverity.Error, $"Construct parameter '{field.Groups["name"].Value}' is duplicated."));
+ }
+ result.Add(new ForgeConstruct(header.Groups["capability"].Value, header.Groups["name"].Value, fields));
+ }
+ return result;
+ }
+
+ private static int MatchingBrace(string source, int open)
+ {
+ var depth = 0;
+ for (var index = open; index < source.Length; index++)
+ {
+ if (source[index] == '{') depth++;
+ else if (source[index] == '}' && --depth == 0) return index;
+ }
+ return -1;
+ }
+}
diff --git a/Aetheris.Forge.Sdk/ForgeSdkModels.cs b/Aetheris.Forge.Sdk/ForgeSdkModels.cs
new file mode 100644
index 00000000..23a314c6
--- /dev/null
+++ b/Aetheris.Forge.Sdk/ForgeSdkModels.cs
@@ -0,0 +1,61 @@
+using Aetheris.Continuum.Boundaries;
+using Aetheris.Forge.Abstractions;
+using Aetheris.Forge.Extensions;
+using Aetheris.Kernel.Core.Brep;
+
+namespace Aetheris.Forge.Sdk;
+
+public sealed record ForgeDiagnostic(
+ string Code,
+ ForgeDiagnosticSeverity Severity,
+ string Message,
+ string? Source = null,
+ string? CapabilityId = null);
+
+public sealed record ForgeTemplateParameter(
+ string Name,
+ string TypeName,
+ bool IsTypeParameter,
+ string? DefaultValue,
+ string? ConstraintConcept);
+
+public sealed record ForgeTemplateMetadata(
+ string ModuleName,
+ string Name,
+ string TargetKind,
+ IReadOnlyList<ForgeTemplateParameter> Parameters,
+ string GeneratedBindingName);
+
+public sealed record ForgeCapabilityEvidence(
+ string CapabilityId,
+ string CapabilityVersion,
+ string ExtensionId,
+ string ExtensionVersion,
+ string OutputClassification,
+ IReadOnlyList<string> LoweringTargets);
+
+public sealed record ForgeProvenanceEntry(string Stage, string Identity, string Evidence);
+
+public sealed record ForgeCirEvidence(
+ CirBrepAssociation Association,
+ BrepCirConsistencyResult Consistency);
+
+public sealed record ForgeCompilationArtifact(
+ string StepText,
+ string ArtifactHash,
+ BrepBody? Body,
+ ForgeCirEvidence? Cir,
+ IReadOnlyList<ForgeCapabilityEvidence> Capabilities,
+ IReadOnlyList<ForgeProvenanceEntry> Provenance);
+
+public sealed record ForgeCompilationResult(
+ ForgeCompilationArtifact? Artifact,
+ IReadOnlyList<ForgeDiagnostic> Diagnostics,
+ TimeSpan RegistrationTime,
+ TimeSpan ResolutionTime,
+ TimeSpan TemplateInvocationTime,
+ TimeSpan ExtensionLoweringTime,
+ TimeSpan CompilerLoweringTime)
+{
+ public bool IsSuccess => Artifact is not null && Diagnostics.All(diagnostic => diagnostic.Severity != ForgeDiagnosticSeverity.Error);
+}
diff --git a/Aetheris.Forge.Sdk/ForgeValues.cs b/Aetheris.Forge.Sdk/ForgeValues.cs
new file mode 100644
index 00000000..f43e38ab
--- /dev/null
+++ b/Aetheris.Forge.Sdk/ForgeValues.cs
@@ -0,0 +1,74 @@
+using System.Globalization;
+
+namespace Aetheris.Forge.Sdk;
+
+public abstract record ForgeValue(string TypeName)
+{
+ internal abstract string CanonicalLiteral { get; }
+}
+
+public sealed record ForgeLength(double Millimeters) : ForgeValue("Length")
+{
+ internal override string CanonicalLiteral => Millimeters.ToString("R", CultureInfo.InvariantCulture) + "mm";
+}
+
+public sealed record ForgeAngle(double Degrees) : ForgeValue("Angle")
+{
+ internal override string CanonicalLiteral => Degrees.ToString("R", CultureInfo.InvariantCulture) + "deg";
+}
+
+public sealed record ForgeInteger(int Value) : ForgeValue("Int")
+{
+ internal override string CanonicalLiteral => Value.ToString(CultureInfo.InvariantCulture);
+}
+
+public sealed record ForgeReal(double Value) : ForgeValue("Float")
+{
+ internal override string CanonicalLiteral => Value.ToString("R", CultureInfo.InvariantCulture);
+}
+
+public sealed record ForgeBoolean(bool Value) : ForgeValue("Bool")
+{
+ internal override string CanonicalLiteral => Value ? "true" : "false";
+}
+
+public sealed record ForgeString(string Value) : ForgeValue("String")
+{
+ internal override string CanonicalLiteral => "\"" + Value.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal) + "\"";
+}
+
+public sealed record ForgeType(string Name) : ForgeValue("Type")
+{
+ internal override string CanonicalLiteral => Name;
+}
+
+public sealed record ForgeRecord(string RecordType, IReadOnlyDictionary<string, ForgeValue> Fields) : ForgeValue(RecordType)
+{
+ internal override string CanonicalLiteral => RecordType;
+}
+
+public abstract record ForgeResource(string Name, string ContentHash);
+
+public sealed record ImportedStepResource(
+ string Name,
+ string Path,
+ string ContentHash,
+ bool Canonical,
+ Aetheris.Kernel.Core.Brep.BrepBody Body) : ForgeResource(Name, ContentHash)
+{
+ public static ImportedStepResource Load(string name, string path)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(name);
+ ArgumentException.ThrowIfNullOrWhiteSpace(path);
+ var fullPath = System.IO.Path.GetFullPath(path);
+ var bytes = File.ReadAllBytes(fullPath);
+ var text = System.Text.Encoding.UTF8.GetString(bytes);
+ var canonical = text.Contains("AETHERIS", StringComparison.OrdinalIgnoreCase)
+ && text.Contains("ISO-10303-21", StringComparison.Ordinal);
+ if (!canonical) throw new InvalidDataException("Imported STEP resource must be an Aetheris-canonical AP242 artifact. Canonicalize it through the ordinary InlineStep pipeline first.");
+ var imported = Aetheris.Kernel.Core.Step242.Step242Importer.ImportBody(text);
+ if (!imported.IsSuccess || imported.Value is null)
+ throw new InvalidDataException("Imported STEP resource failed the ordinary Aetheris STEP importer: " + string.Join("; ", imported.Diagnostics.Select(diagnostic => diagnostic.Message)));
+ return new(name, fullPath, Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(bytes)), canonical, imported.Value);
+ }
+}
diff --git a/Aetheris.Forge.Testing/Aetheris.Forge.Testing.csproj b/Aetheris.Forge.Testing/Aetheris.Forge.Testing.csproj
new file mode 100644
index 00000000..45e92569
--- /dev/null
+++ b/Aetheris.Forge.Testing/Aetheris.Forge.Testing.csproj
@@ -0,0 +1,10 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>net10.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ </PropertyGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\Aetheris.Forge.Sdk\Aetheris.Forge.Sdk.csproj" />
+ </ItemGroup>
+</Project>
diff --git a/Aetheris.Forge.Testing/ForgeExtensionAssertions.cs b/Aetheris.Forge.Testing/ForgeExtensionAssertions.cs
new file mode 100644
index 00000000..eb86e1d8
--- /dev/null
+++ b/Aetheris.Forge.Testing/ForgeExtensionAssertions.cs
@@ -0,0 +1,51 @@
+using Aetheris.Forge.Sdk;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Step242;
+
+namespace Aetheris.Forge.Testing;
+
+public static class ForgeExtensionAssertions
+{
+ public static void RequireSuccessfulCompilation(ForgeCompilationResult result)
+ {
+ if (!result.IsSuccess || result.Artifact is null)
+ throw new InvalidOperationException("Forge compilation failed: " + string.Join("; ", result.Diagnostics.Select(diagnostic => diagnostic.Code + ":" + diagnostic.Message)));
+ }
+
+ public static void RequireValidBrep(BrepBody body)
+ {
+ var validation = BrepBindingValidator.Validate(body, true);
+ if (!validation.IsSuccess)
+ throw new InvalidOperationException("BRep validation failed: " + string.Join("; ", validation.Diagnostics.Select(diagnostic => diagnostic.Message)));
+ }
+
+ public static void RequireStepRoundTrip(string stepText)
+ {
+ var imported = Step242Importer.ImportBody(stepText);
+ if (!imported.IsSuccess || imported.Value is null)
+ throw new InvalidOperationException("STEP round trip failed: " + string.Join("; ", imported.Diagnostics.Select(diagnostic => diagnostic.Message)));
+ RequireValidBrep(imported.Value);
+ }
+
+ public static void RequireDeterministic(ForgeCompilationResult first, ForgeCompilationResult second)
+ {
+ RequireSuccessfulCompilation(first);
+ RequireSuccessfulCompilation(second);
+ if (!string.Equals(first.Artifact!.ArtifactHash, second.Artifact!.ArtifactHash, StringComparison.Ordinal)
+ || !string.Equals(first.Artifact.StepText, second.Artifact.StepText, StringComparison.Ordinal))
+ throw new InvalidOperationException("Repeated Forge compilation did not preserve artifact identity.");
+ }
+
+ public static void RequireCompleteProvenance(ForgeCompilationArtifact artifact)
+ {
+ string[] stages = ["host", "template", "capability", "construction", "artifact"];
+ var missing = stages.Where(stage => artifact.Provenance.All(entry => entry.Stage != stage)).ToArray();
+ if (missing.Length > 0) throw new InvalidOperationException("Forge provenance is missing: " + string.Join(", ", missing));
+ }
+
+ public static void RequireCirAssociation(ForgeCompilationArtifact artifact)
+ {
+ if (artifact.Cir is null || !artifact.Cir.Consistency.Passed)
+ throw new InvalidOperationException("Forge CIR/BRep association is absent or invalid.");
+ }
+}
diff --git a/Aetheris.Forge/Extensions/ForgeCapabilityExecutor.cs b/Aetheris.Forge/Extensions/ForgeCapabilityExecutor.cs
new file mode 100644
index 00000000..a14d4d5c
--- /dev/null
+++ b/Aetheris.Forge/Extensions/ForgeCapabilityExecutor.cs
@@ -0,0 +1,116 @@
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Forge.Abstractions;
+using Aetheris.Kernel.Core.Brep.Features;
+using Aetheris.Kernel.Core.Construction;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Forge.Extensions;
+
+public static class ForgeCapabilityExecutor
+{
+ public static ForgeCapabilityExecutionResult Execute(
+ ForgeExtensionRegistry registry,
+ ForgeCapabilityId id,
+ ForgeCapabilityInvocationContext context,
+ ForgeCapabilityArguments arguments)
+ {
+ if (!registry.TryResolve(id, out var capability))
+ return ForgeCapabilityExecutionResult.Failure(Error("forge-capability-missing", $"Capability '{id}' is not registered.", id, context));
+ var binding = ValidateArguments(capability.Descriptor, arguments, context);
+ if (binding.Count > 0) return new ForgeCapabilityExecutionResult(null, binding);
+ if (!context.RequestedTargets.All(capability.Descriptor.SupportedTargets.Contains))
+ return ForgeCapabilityExecutionResult.Failure(Error("forge-capability-lowering-target-unsupported", $"Capability '{id}' does not support all requested lowering targets.", id, context));
+ try
+ {
+ var result = capability.Execute(context, arguments);
+ if (!result.IsSuccess) return result;
+ var contractDiagnostic = ValidateOutputContract(capability.Descriptor, result.Output!);
+ if (contractDiagnostic is not null)
+ return ForgeCapabilityExecutionResult.Failure(Error("forge-capability-output-contract-violation", contractDiagnostic, id, context));
+ if (result.Output?.Construction is { } construction)
+ {
+ try { construction.Validate(); }
+ catch (Exception exception) when (exception is ArgumentException or InvalidOperationException)
+ {
+ return ForgeCapabilityExecutionResult.Failure(Error("forge-capability-construction-invalid", exception.Message, id, context));
+ }
+ }
+ if (result.Output?.ExactBrep is { } exact)
+ {
+ var validation = BrepBindingValidator.Validate(exact, requireAllEdgeAndFaceBindings: true);
+ if (!validation.IsSuccess)
+ return ForgeCapabilityExecutionResult.Failure(Error("forge-capability-brep-invalid", string.Join("; ", validation.Diagnostics.Select(diagnostic => diagnostic.Message)), id, context));
+ }
+ if (result.Output?.Provenance is null || !result.Output.Provenance.ContainsKey("capability"))
+ return ForgeCapabilityExecutionResult.Failure(Error("forge-capability-provenance-missing", $"Capability '{id}' did not emit required capability provenance.", id, context));
+ return result;
+ }
+ catch (ForgeCapabilityAdmissionException exception)
+ {
+ return ForgeCapabilityExecutionResult.Failure(Error("forge-capability-admission-rejected", exception.Message, id, context));
+ }
+ catch (Exception exception)
+ {
+ return ForgeCapabilityExecutionResult.Failure(Error("forge-capability-exception", $"Capability '{id}' failed: {exception.GetType().Name}: {exception.Message}", id, context));
+ }
+ }
+
+ private static string? ValidateOutputContract(ForgeCapabilityDescriptorV1 descriptor, ForgeCapabilityOutput output) =>
+ descriptor.OutputClassification switch
+ {
+ ForgeOutputClassification.ConstructionIr when output.Construction is null => "ConstructionIR capability did not emit a construction descriptor.",
+ ForgeOutputClassification.ExactBrep when output.ExactBrep is null => "ExactBRep capability did not emit an exact BRep.",
+ ForgeOutputClassification.SurfaceMeshDerived when output.ExactBrep is not null => "SurfaceMeshDerived output cannot masquerade as ExactBRep.",
+ _ when output.ExactBrep is not null && string.IsNullOrWhiteSpace(descriptor.ExactnessContract) => "Exact BRep output requires a non-empty exactness contract.",
+ _ => null,
+ };
+
+ public static BrepBody MaterializeConstruction(ContinuumConstructionDescriptor descriptor)
+ {
+ descriptor.Validate();
+ if (descriptor.Sections.Count != 2)
+ throw new ForgeCapabilityAdmissionException("M1 standard ConstructionIR materialization requires exactly two prismatic sections.");
+ var lower = descriptor.Sections[0];
+ var upper = descriptor.Sections[1];
+ if (lower.ProfileVertices.Count != upper.ProfileVertices.Count
+ || lower.ProfileVertices.Zip(upper.ProfileVertices).Any(pair => double.Abs(pair.First.X - pair.Second.X) > 1e-12d || double.Abs(pair.First.Y - pair.Second.Y) > 1e-12d))
+ throw new ForgeCapabilityAdmissionException("M1 standard ConstructionIR materialization requires identical lower and upper profiles.");
+ var profile = PolylineProfile2D.Create(lower.ProfileVertices.Select(point => new ProfilePoint2D(point.X, point.Y)).ToArray());
+ if (!profile.IsSuccess) throw new ForgeCapabilityAdmissionException(string.Join("; ", profile.Diagnostics.Select(diagnostic => diagnostic.Message)));
+ var height = upper.AxialPosition - lower.AxialPosition;
+ var body = BrepExtrude.Create(
+ profile.Value,
+ new ExtrudeFrame3D(
+ new Point3D(0d, 0d, lower.AxialPosition),
+ Direction3D.Create(new Vector3D(0d, 0d, 1d)),
+ Direction3D.Create(new Vector3D(1d, 0d, 0d))),
+ height);
+ if (!body.IsSuccess) throw new ForgeCapabilityAdmissionException(string.Join("; ", body.Diagnostics.Select(diagnostic => diagnostic.Message)));
+ var validation = BrepBindingValidator.Validate(body.Value, true);
+ if (!validation.IsSuccess) throw new ForgeCapabilityAdmissionException(string.Join("; ", validation.Diagnostics.Select(diagnostic => diagnostic.Message)));
+ return body.Value;
+ }
+
+ private static IReadOnlyList<ForgeExtensionDiagnostic> ValidateArguments(
+ ForgeCapabilityDescriptorV1 descriptor,
+ ForgeCapabilityArguments arguments,
+ ForgeCapabilityInvocationContext context)
+ {
+ var diagnostics = new List<ForgeExtensionDiagnostic>();
+ var schema = descriptor.Inputs.ToDictionary(input => input.Name, StringComparer.Ordinal);
+ foreach (var required in descriptor.Inputs.Where(input => input.Required && input.DefaultValue is null))
+ if (!arguments.Values.ContainsKey(required.Name)) diagnostics.Add(Error("forge-capability-parameter-missing", $"Required parameter '{required.Name}' is missing.", descriptor.Id, context));
+ foreach (var argument in arguments.Values)
+ {
+ if (!schema.TryGetValue(argument.Key, out var parameter))
+ diagnostics.Add(Error("forge-capability-parameter-unknown", $"Parameter '{argument.Key}' is not declared by capability '{descriptor.Id}'.", descriptor.Id, context));
+ else if (parameter.Type != argument.Value.Type)
+ diagnostics.Add(Error("forge-capability-parameter-mismatch", $"Parameter '{argument.Key}' expects {parameter.Type} but received {argument.Value.Type}.", descriptor.Id, context));
+ }
+ return diagnostics;
+ }
+
+ private static ForgeExtensionDiagnostic Error(string code, string message, ForgeCapabilityId id, ForgeCapabilityInvocationContext context) =>
+ new(code, ForgeDiagnosticSeverity.Error, message, id.Value, context.SourceIdentity);
+}
diff --git a/Aetheris.Forge/Extensions/ForgeExtensionContracts.cs b/Aetheris.Forge/Extensions/ForgeExtensionContracts.cs
new file mode 100644
index 00000000..b7310db7
--- /dev/null
+++ b/Aetheris.Forge/Extensions/ForgeExtensionContracts.cs
@@ -0,0 +1,246 @@
+using System.Collections.ObjectModel;
+using Aetheris.Forge.Abstractions;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Construction;
+
+namespace Aetheris.Forge.Extensions;
+
+public enum ForgeOutputClassification
+{
+ SemanticOnly = 1,
+ ConstructionIr = 2,
+ ExactBrep = 3,
+ ContinuumRegion = 4,
+ SurfaceMeshDerived = 5,
+ Analysis = 6,
+}
+
+public enum ForgeLoweringTarget
+{
+ ConstructionIr = 1,
+ Brep = 2,
+ Cir = 3,
+ Analysis = 4,
+}
+
+public enum ForgeCapabilityDeterminism
+{
+ Deterministic = 1,
+ ExperimentalNonDeterministic = 2,
+}
+
+public enum ForgeCapabilityParameterType
+{
+ Length = 1,
+ Angle = 2,
+ Integer = 3,
+ Real = 4,
+ Boolean = 5,
+ String = 6,
+ ImportedStepResource = 7,
+}
+
+public sealed record ForgeCapabilityId(string Value)
+{
+ public override string ToString() => Value;
+}
+
+public sealed record ForgeCapabilityParameter(
+ string Name,
+ ForgeCapabilityParameterType Type,
+ bool Required = true,
+ string? DefaultValue = null,
+ string? Description = null);
+
+public sealed record ForgeCapabilityDescriptorV1(
+ ForgeCapabilityId Id,
+ Version Version,
+ string ExtensionId,
+ Version ExtensionVersion,
+ string Description,
+ IReadOnlyList<ForgeCapabilityParameter> Inputs,
+ ForgeOutputClassification OutputClassification,
+ IReadOnlySet<ForgeLoweringTarget> SupportedTargets,
+ ForgeCapabilityDeterminism Determinism,
+ string ExactnessContract,
+ string AdmissionContract,
+ string ProvenanceIdentity);
+
+public sealed record ForgeCapabilityValue(
+ ForgeCapabilityParameterType Type,
+ object Value,
+ string CanonicalValue);
+
+public sealed class ForgeCapabilityArguments
+{
+ private readonly IReadOnlyDictionary<string, ForgeCapabilityValue> values;
+
+ public ForgeCapabilityArguments(IReadOnlyDictionary<string, ForgeCapabilityValue> values)
+ {
+ ArgumentNullException.ThrowIfNull(values);
+ this.values = new ReadOnlyDictionary<string, ForgeCapabilityValue>(
+ values.OrderBy(pair => pair.Key, StringComparer.Ordinal)
+ .ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal));
+ }
+
+ public IReadOnlyDictionary<string, ForgeCapabilityValue> Values => values;
+
+ public double RequiredNumber(string name, ForgeCapabilityParameterType expectedType)
+ {
+ if (!values.TryGetValue(name, out var value) || value.Type != expectedType || value.Value is not double number)
+ throw new ForgeCapabilityAdmissionException($"Parameter '{name}' must be {expectedType}.");
+ return number;
+ }
+
+ public string RequiredString(string name)
+ {
+ if (!values.TryGetValue(name, out var value) || value.Type != ForgeCapabilityParameterType.String || value.Value is not string text)
+ throw new ForgeCapabilityAdmissionException($"Parameter '{name}' must be String.");
+ return text;
+ }
+}
+
+public sealed record ForgeCapabilityInvocationContext(
+ string InvocationIdentity,
+ string SourceIdentity,
+ string TemplateIdentity,
+ IReadOnlySet<ForgeLoweringTarget> RequestedTargets);
+
+public sealed record ForgeCapabilityOutput(
+ ContinuumConstructionDescriptor? Construction,
+ BrepBody? ExactBrep = null,
+ ContinuumConstructionDescriptor? ContinuumConstruction = null,
+ IReadOnlyDictionary<string, string>? Provenance = null);
+
+public sealed record ForgeExtensionDiagnostic(
+ string Code,
+ ForgeDiagnosticSeverity Severity,
+ string Message,
+ string? CapabilityId = null,
+ string? SourceIdentity = null);
+
+public sealed record ForgeCapabilityExecutionResult(
+ ForgeCapabilityOutput? Output,
+ IReadOnlyList<ForgeExtensionDiagnostic> Diagnostics)
+{
+ public bool IsSuccess => Output is not null && Diagnostics.All(diagnostic => diagnostic.Severity != ForgeDiagnosticSeverity.Error);
+ public static ForgeCapabilityExecutionResult Success(ForgeCapabilityOutput output, params ForgeExtensionDiagnostic[] diagnostics) => new(output, diagnostics);
+ public static ForgeCapabilityExecutionResult Failure(params ForgeExtensionDiagnostic[] diagnostics) => new(null, diagnostics);
+}
+
+public interface IForgeCapability
+{
+ ForgeCapabilityDescriptorV1 Descriptor { get; }
+ ForgeCapabilityExecutionResult Execute(ForgeCapabilityInvocationContext context, ForgeCapabilityArguments arguments);
+}
+
+public interface IForgeExtension
+{
+ string Id { get; }
+ Version Version { get; }
+ void Register(ForgeExtensionRegistry registry);
+}
+
+public sealed record ForgeExtensionRequirement(string ExtensionId, Version Version);
+
+public sealed class ForgeExtensionManifest
+{
+ public ForgeExtensionManifest(IEnumerable<ForgeExtensionRequirement>? requirements = null)
+ {
+ Requirements = (requirements ?? [])
+ .OrderBy(requirement => requirement.ExtensionId, StringComparer.Ordinal)
+ .ThenBy(requirement => requirement.Version)
+ .ToArray();
+ }
+
+ public IReadOnlyList<ForgeExtensionRequirement> Requirements { get; }
+}
+
+public sealed class ForgeExtensionRegistry
+{
+ private readonly SortedDictionary<string, IForgeCapability> capabilities = new(StringComparer.Ordinal);
+ private readonly SortedDictionary<string, Version> extensions = new(StringComparer.Ordinal);
+
+ public void RegisterExtension(IForgeExtension extension)
+ {
+ ArgumentNullException.ThrowIfNull(extension);
+ if (extensions.TryGetValue(extension.Id, out var existing))
+ throw new ForgeExtensionRegistrationException(
+ existing == extension.Version ? "forge-extension-duplicate" : "forge-extension-version-conflict",
+ $"Extension '{extension.Id}' is already registered at version {existing}; version {extension.Version} cannot be added.");
+ extensions.Add(extension.Id, extension.Version);
+ try
+ {
+ extension.Register(this);
+ }
+ catch (Exception exception)
+ {
+ extensions.Remove(extension.Id);
+ foreach (var capability in capabilities.Where(pair => pair.Value.Descriptor.ExtensionId == extension.Id).Select(pair => pair.Key).ToArray())
+ capabilities.Remove(capability);
+ if (exception is ForgeExtensionRegistrationException) throw;
+ throw new ForgeExtensionRegistrationException(
+ "forge-extension-initialization-failed",
+ $"Extension '{extension.Id}' version {extension.Version} failed during explicit initialization: {exception.GetType().Name}: {exception.Message}",
+ exception);
+ }
+ }
+
+ public void RegisterCapability(IForgeCapability capability)
+ {
+ ArgumentNullException.ThrowIfNull(capability);
+ ValidateDescriptor(capability.Descriptor);
+ if (!extensions.TryGetValue(capability.Descriptor.ExtensionId, out var extensionVersion)
+ || extensionVersion != capability.Descriptor.ExtensionVersion)
+ throw new ForgeExtensionRegistrationException(
+ "forge-capability-extension-identity-mismatch",
+ $"Capability '{capability.Descriptor.Id}' does not name the extension currently being registered.");
+ if (capabilities.TryGetValue(capability.Descriptor.Id.Value, out var existing))
+ throw new ForgeExtensionRegistrationException(
+ existing.Descriptor.Version == capability.Descriptor.Version ? "forge-capability-id-collision" : "forge-capability-version-conflict",
+ $"Capability '{capability.Descriptor.Id}' is already registered at version {existing.Descriptor.Version}; version {capability.Descriptor.Version} cannot be added.");
+ capabilities.Add(capability.Descriptor.Id.Value, capability);
+ }
+
+ public bool TryResolve(ForgeCapabilityId id, out IForgeCapability capability) => capabilities.TryGetValue(id.Value, out capability!);
+
+ public IReadOnlyList<ForgeCapabilityDescriptorV1> InspectCapabilities() => capabilities.Values.Select(capability => capability.Descriptor).ToArray();
+
+ public IReadOnlyList<ForgeExtensionDiagnostic> ValidateManifest(ForgeExtensionManifest manifest)
+ {
+ ArgumentNullException.ThrowIfNull(manifest);
+ return manifest.Requirements.SelectMany(requirement =>
+ {
+ if (!extensions.TryGetValue(requirement.ExtensionId, out var version))
+ return new[] { Error("forge-extension-missing", $"Required extension '{requirement.ExtensionId}' version {requirement.Version} is not registered.") };
+ return version == requirement.Version
+ ? Array.Empty<ForgeExtensionDiagnostic>()
+ : new[] { Error("forge-extension-version-conflict", $"Required extension '{requirement.ExtensionId}' version {requirement.Version} conflicts with registered version {version}.") };
+ }).ToArray();
+ }
+
+ private static void ValidateDescriptor(ForgeCapabilityDescriptorV1 descriptor)
+ {
+ if (string.IsNullOrWhiteSpace(descriptor.Id.Value) || string.IsNullOrWhiteSpace(descriptor.ExtensionId)
+ || string.IsNullOrWhiteSpace(descriptor.ProvenanceIdentity) || string.IsNullOrWhiteSpace(descriptor.AdmissionContract))
+ throw new ForgeExtensionRegistrationException("forge-capability-descriptor-invalid", "Capability identity, extension identity, provenance, and admission contracts are required.");
+ if (descriptor.Determinism != ForgeCapabilityDeterminism.Deterministic)
+ throw new ForgeExtensionRegistrationException("forge-capability-nondeterministic", $"Capability '{descriptor.Id}' is non-deterministic and cannot enter the M1 compiler registry.");
+ var duplicate = descriptor.Inputs.GroupBy(input => input.Name, StringComparer.Ordinal).FirstOrDefault(group => group.Count() > 1);
+ if (duplicate is not null)
+ throw new ForgeExtensionRegistrationException("forge-capability-parameter-collision", $"Capability '{descriptor.Id}' declares parameter '{duplicate.Key}' more than once.");
+ }
+
+ private static ForgeExtensionDiagnostic Error(string code, string message) => new(code, ForgeDiagnosticSeverity.Error, message);
+}
+
+public sealed class ForgeCapabilityAdmissionException : Exception
+{
+ public ForgeCapabilityAdmissionException(string message) : base(message) { }
+}
+
+public sealed class ForgeExtensionRegistrationException : Exception
+{
+ public ForgeExtensionRegistrationException(string code, string message, Exception? innerException = null) : base(message, innerException) => Code = code;
+ public string Code { get; }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
index cb8d28f7..503ed345 100644
--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs
@@ -63,6 +63,24 @@ public static class FirmamentBuildAndExport
export));
}
+ /// <summary>
+ /// Compiles an already-resolved in-memory module through the same materialization and
+ /// validation path as file builds. Forge uses this after typed Template specialization.
+ /// </summary>
+ public static KernelResult<FirmamentStepExportResult> CompileSource(
+ string sourceText,
+ string? sourceDirectory = null)
+ {
+ ArgumentNullException.ThrowIfNull(sourceText);
+ var normalized = NormalizeLf(sourceText);
+ var export = ExportSource(normalized, sourceDirectory);
+ if (!export.IsSuccess) return export;
+ var assertions = EvaluateVolumeAssertions(normalized, sourceDirectory, export.Value);
+ return assertions.IsSuccess
+ ? KernelResult<FirmamentStepExportResult>.Success(export.Value with { Assertions = assertions.Value }, export.Diagnostics)
+ : KernelResult<FirmamentStepExportResult>.Failure(assertions.Diagnostics);
+ }
+
private static KernelResult<IReadOnlyList<FirmamentV2VolumeAssertionResult>> EvaluateVolumeAssertions(string source, string? sourceDirectory, FirmamentStepExportResult export)
{
var parsed = FirmamentV2Parser.Parse(source, sourceDirectory);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs
new file mode 100644
index 00000000..ade3aeee
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs
@@ -0,0 +1,101 @@
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+/// <summary>Stable compiler metadata consumed by Forge and generated host bindings.</summary>
+public sealed record FirmamentTemplateMetadata(
+ string Name,
+ string TargetKind,
+ IReadOnlyList<FirmamentTemplateParameterMetadata> Parameters);
+
+public sealed record FirmamentTemplateParameterMetadata(
+ string Name,
+ FirmamentTemplateParameterKind Kind,
+ string TypeName,
+ string? DefaultExpression,
+ string? ConstraintConcept);
+
+public enum FirmamentTemplateParameterKind
+{
+ Value = 1,
+ Type = 2,
+}
+
+/// <summary>
+/// Representation-neutral value admitted at the Forge/Firmament boundary. Literal text is
+/// canonical Firmament value notation (for example 12mm or true), not arbitrary source.
+/// </summary>
+public sealed record FirmamentHostArgument(
+ string Literal,
+ string? RecordType = null,
+ IReadOnlyDictionary<string, string>? RecordFields = null);
+
+public sealed record FirmamentHostTemplateExpansion(
+ string ExpandedSource,
+ string TemplateName,
+ string InstanceName,
+ string SpecializationIdentity,
+ IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>> RecordArguments);
+
+/// <summary>
+/// Narrow public seam for Forge. Template declarations are parsed once into compiler IR and host
+/// invocations enter the existing typed binder directly; this is not a general source-rewrite API.
+/// </summary>
+public static class FirmamentTemplateHostBridge
+{
+ public static IReadOnlyList<FirmamentTemplateMetadata> Inspect(
+ string moduleSource,
+ out IReadOnlyList<string> diagnostics)
+ {
+ ArgumentNullException.ThrowIfNull(moduleSource);
+ var collected = new List<string>();
+ var templates = FirmamentV2TemplateExpansion.Inspect(moduleSource, collected)
+ .Select(template => new FirmamentTemplateMetadata(
+ template.Name,
+ template.TargetKind,
+ template.Parameters.Select(parameter => new FirmamentTemplateParameterMetadata(
+ parameter.Name,
+ parameter.Kind == "Type" ? FirmamentTemplateParameterKind.Type : FirmamentTemplateParameterKind.Value,
+ parameter.TypeName,
+ parameter.DefaultExpression,
+ parameter.ConstraintConcept)).ToArray()))
+ .ToArray();
+ diagnostics = collected.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();
+ return templates;
+ }
+
+ public static FirmamentHostTemplateExpansion? Expand(
+ string moduleSource,
+ string templateName,
+ string instanceName,
+ IReadOnlyDictionary<string, FirmamentHostArgument> arguments,
+ out IReadOnlyList<string> diagnostics)
+ {
+ ArgumentNullException.ThrowIfNull(moduleSource);
+ ArgumentNullException.ThrowIfNull(arguments);
+ var collected = new List<string>();
+ var expansion = FirmamentV2TemplateExpansion.ExpandHostInvocation(
+ moduleSource,
+ templateName,
+ instanceName,
+ arguments.ToDictionary(
+ pair => pair.Key,
+ pair => new FirmamentV2TemplateExpansion.HostArgument(
+ pair.Value.Literal,
+ pair.Value.RecordType,
+ pair.Value.RecordFields),
+ StringComparer.Ordinal),
+ collected);
+ diagnostics = collected.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();
+ if (expansion is null) return null;
+ var instance = expansion.Instantiations.Single();
+ return new FirmamentHostTemplateExpansion(
+ expansion.Source,
+ templateName,
+ instanceName,
+ instance.SpecializationIdentity,
+ (instance.RecordArguments ?? new Dictionary<string, ConceptIrTemplateRecordArgument>())
+ .ToDictionary(
+ pair => pair.Key,
+ pair => (IReadOnlyDictionary<string, string>)pair.Value.Members,
+ StringComparer.Ordinal));
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
index 3d6ce9de..7a243746 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs
@@ -65,6 +65,149 @@ internal static class FirmamentV2TemplateExpansion
internal sealed record Result(string Source, IReadOnlyList<ConceptIrTemplateInstantiation> Instantiations);
+ internal sealed record HostArgument(
+ string Expression,
+ string? RecordType = null,
+ IReadOnlyDictionary<string, string>? RecordFields = null);
+
+ internal sealed record HostParameter(
+ string Name,
+ string Kind,
+ string TypeName,
+ string? DefaultExpression,
+ string? ConstraintConcept);
+
+ internal sealed record HostTemplate(
+ string Name,
+ string TargetKind,
+ IReadOnlyList<HostParameter> Parameters);
+
+ internal static IReadOnlyList<HostTemplate> Inspect(string source, List<string> diagnostics) =>
+ ParseDeclarations(source, diagnostics)
+ .Select(template => new HostTemplate(
+ template.Name,
+ template.TargetKind,
+ template.Parameters.Select(parameter => parameter switch
+ {
+ TemplateTypeParameterIr 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()))
+ .OrderBy(template => template.Name, StringComparer.Ordinal)
+ .ToArray();
+
+ /// <summary>
+ /// Expands one host-supplied Template invocation from typed arguments. The invocation is
+ /// admitted directly as binder IR; callers never need to manufacture Firmament application
+ /// source, and host Record values are supplied as immutable synthetic static records.
+ /// </summary>
+ internal static Result? ExpandHostInvocation(
+ string source,
+ string templateName,
+ string instanceName,
+ IReadOnlyDictionary<string, HostArgument> hostArguments,
+ List<string> diagnostics)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(templateName);
+ ArgumentException.ThrowIfNullOrWhiteSpace(instanceName);
+ ArgumentNullException.ThrowIfNull(hostArguments);
+
+ var declarations = ParseDeclarations(source, diagnostics);
+ var byName = declarations.ToDictionary(declaration => declaration.Name, StringComparer.Ordinal);
+ DetectTemplateCycles(declarations, byName, diagnostics);
+ if (!byName.TryGetValue(templateName, out var template))
+ {
+ diagnostics.Add(Prefix + "not-found:" + templateName);
+ return null;
+ }
+
+ if (!Regex.IsMatch(instanceName, @"^[A-Za-z_][A-Za-z0-9_]*$", RegexOptions.CultureInvariant))
+ {
+ diagnostics.Add(Prefix + "invalid-instance-name:" + instanceName);
+ return null;
+ }
+
+ var enums = ParseEnums(source);
+ var recordTypes = ParseRecordTypes(source, diagnostics);
+ var tables = ParseStaticTables(source, recordTypes, enums, diagnostics);
+ var staticRecords = ParseStaticRecords(source, recordTypes, enums, tables, diagnostics).ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal);
+ var arguments = ImmutableArray.CreateBuilder<TemplateArgumentIr>();
+ foreach (var pair in hostArguments.OrderBy(pair => pair.Key, StringComparer.Ordinal))
+ {
+ var expression = pair.Value.Expression;
+ if (pair.Value.RecordFields is not null)
+ {
+ var recordName = $"__forge_{instanceName}_{pair.Key}";
+ var recordType = pair.Value.RecordType ?? string.Empty;
+ staticRecords[recordName] = new TemplateStaticRecordIr(
+ recordName,
+ recordType,
+ pair.Value.RecordFields.ToImmutableDictionary(StringComparer.Ordinal),
+ new FirmamentV2SourceSpan(source.Length, 0),
+ "ForgeHostRecord");
+ expression = recordName;
+ }
+ arguments.Add(new TemplateArgumentIr(pair.Key, expression, new FirmamentV2SourceSpan(source.Length, 0)));
+ }
+
+ var application = new TemplateApplicationIr(
+ template.TargetKind,
+ instanceName,
+ templateName,
+ arguments.ToImmutable(),
+ new FirmamentV2SourceSpan(source.Length, 0));
+ var bound = Bind(template, application, source, enums, recordTypes, staticRecords, diagnostics);
+ if (bound is null || HasErrors(diagnostics)) return null;
+
+ var 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;
+ body = RemoveRequires(body);
+
+ var specialization = new TemplateSpecializationIr(
+ template,
+ application,
+ bound,
+ Identity(template, application, bound),
+ GeneratedPaths(template.Body, application.InstanceName));
+ var recordArguments = bound.RecordArguments.ToDictionary(
+ pair => pair.Key,
+ pair => new ConceptIrTemplateRecordArgument(
+ pair.Value.TypeName,
+ pair.Value.StaticName,
+ pair.Value.Fields,
+ pair.Value.SourceSpan,
+ pair.Value.Provenance),
+ StringComparer.Ordinal);
+ var instantiation = new ConceptIrTemplateInstantiation(
+ template.Name,
+ application.InstanceName,
+ bound.TypeArguments,
+ bound.ValueArguments,
+ bound.DefaultedArguments,
+ specialization.SpecializationIdentity,
+ specialization.GeneratedDeclarationPaths,
+ template.SourceSpan,
+ application.SourceSpan,
+ SelectedMatchArms: selectedMatches,
+ RecordArguments: recordArguments,
+ RequireResults: requireResults);
+
+ var changes = declarations
+ .Select(declaration => (
+ Start: declaration.SourceSpan.Start,
+ Length: declaration.SourceSpan.Length,
+ Text: string.Equals(declaration.Name, template.Name, StringComparison.Ordinal)
+ ? $"{template.TargetKind} {instanceName}{template.HeaderTail} {{{body}}}"
+ : string.Empty))
+ .OrderByDescending(change => change.Start)
+ .ToArray();
+ foreach (var change in changes)
+ source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);
+ return HasErrors(diagnostics) ? null : new Result(source, [instantiation]);
+ }
+
public static Result? Expand(string source, List<string> diagnostics)
{
var declarations = ParseDeclarations(source, diagnostics);
diff --git a/Aetheris.slnx b/Aetheris.slnx
index 1c158d72..a0376ee7 100644
--- a/Aetheris.slnx
+++ b/Aetheris.slnx
@@ -10,9 +10,15 @@
<Project Path="tools/Aetheris.Continuum.M4/Aetheris.Continuum.M4.csproj" />
<Project Path="tools/Aetheris.Continuum.M4B/Aetheris.Continuum.M4B.csproj" />
<Project Path="tools/Aetheris.Continuum.M4C/Aetheris.Continuum.M4C.csproj" />
+ <Project Path="tools/Aetheris.Forge.M1Evidence/Aetheris.Forge.M1Evidence.csproj" />
<Project Path="tools/Aetheris.Continuum.AttentionE0/Aetheris.Continuum.AttentionE0.csproj" />
<Project Path="tools/Aetheris.Continuum.AttentionE1/Aetheris.Continuum.AttentionE1.csproj" />
<Project Path="Aetheris.Forge/Aetheris.Forge.csproj" />
+ <Project Path="Aetheris.Forge.Sdk/Aetheris.Forge.Sdk.csproj" />
+ <Project Path="Aetheris.Forge.SampleExtension/Aetheris.Forge.SampleExtension.csproj" />
+ <Project Path="Aetheris.Forge.SampleExtension.Bindings/Aetheris.Forge.SampleExtension.Bindings.csproj" />
+ <Project Path="Aetheris.Forge.Testing/Aetheris.Forge.Testing.csproj" />
+ <Project Path="Aetheris.Forge.Sdk.Tests/Aetheris.Forge.Sdk.Tests.csproj" />
<Project Path="Aetheris.Kernel.StandardLibrary/Aetheris.Kernel.StandardLibrary.csproj" />
<Project Path="Aetheris.Kernel.Firmament/Aetheris.Kernel.Firmament.csproj" />
<Project Path="Aetheris.Kernel.Firmament.Tests/Aetheris.Kernel.Firmament.Tests.csproj" />
diff --git a/docs/forge/architecture.md b/docs/forge/architecture.md
new file mode 100644
index 00000000..ff1dd4f4
--- /dev/null
+++ b/docs/forge/architecture.md
@@ -0,0 +1,95 @@
+# Forge architecture
+
+Forge is Aetheris's sanctioned host-language embedding and compiler-extension boundary.
+
+The architectural contract is:
+
+- **Kernel** is the small, proven, broadly reusable geometry/compiler substrate.
+- **Firmament** is the typed compiler metaprogramming DSL for engineering intent, Concepts, Records/Tables, Templates, and deterministic source-controlled model or analysis generation.
+- **Forge** is the C# embedding API and explicit extension SDK. It invokes Firmament Templates and lets trusted packages contribute typed compiler capabilities without modifying `Aetheris.Kernel.Core`.
+
+Firmament is not a general-purpose runtime language and is not “C++ for CAD.” Host programming stays in C#. Firmament has no inline C#, inline Python, arbitrary scripting block, reflection escape hatch, or generic method invocation.
+
+## Responsibility
+
+Forge owns host compiler embedding, module and Template resolution, typed parameter binding, compilation requests, artifact access, extension registration and discovery, capability metadata, validation/provenance contracts, imported-resource handles, and the generated-host-binding seam.
+
+Forge does not own mutable raw BRep editing, a duplicate C# CAD API, geometry algorithms that belong in the shared Kernel, Firmament language semantics, solvers, marketplace policy, process sandboxing, or arbitrary host-language execution.
+
+## Project and dependency structure
+
+The dependency direction intentionally separates contracts from compiler hosting:
+
+```text
+Aetheris.Kernel.Core
+ ^
+ |
+Aetheris.Forge extension contracts and standard ConstructionIR executor
+ ^
+ |
+Aetheris.Kernel.Firmament typed Template binder and compiler
+ ^
+ |
+Aetheris.Forge.Sdk C# host embedding, capability dispatch, artifact/provenance access
+ ^
+ +-- Aetheris.Forge.Testing
+ +-- generated binding packages / host applications
+
+Aetheris.Forge.SampleExtension --> Aetheris.Forge only
+```
+
+The existing `Aetheris.Forge` assembly remains below Firmament because Firmament already consumes its concept contracts. Putting `ForgeHost` into that assembly would create a dependency cycle. `Aetheris.Forge.Sdk` is the sanctioned compiler-facing package while `Aetheris.Forge` remains the low-level extension-contract package.
+
+The sample extension depends only on `Aetheris.Forge` and public Kernel contracts reached through it. It receives no `InternalsVisibleTo` access and contains no capability-specific Kernel code.
+
+## Compilation model
+
+A host loads a real `.firmament` module, inspects Template metadata, resolves a Template, binds typed values, and invokes it. Host calls enter `FirmamentV2TemplateExpansion` as binder IR. They do not synthesize a Firmament application declaration. Host Record values become immutable compiler-owned static-record bindings and Templates still erase before feature AIR.
+
+A Template may contain the bounded domain declaration:
+
+```firmament
+Construct MyCompany.SecretGeometry.SecretCoupon SecretBody {
+ Width: Spec.Width
+ Depth: Spec.Depth
+ Height: Spec.Height
+}
+```
+
+`Construct` names a registered semantic capability ID. It is not C# syntax and cannot identify an assembly, type, or method. Forge resolves the ID against the compilation's explicit registry and manifest.
+
+The preferred extension route is:
+
+```text
+private semantic intent
+ -> admitted standard ContinuumConstructionDescriptor
+ -> Forge standard prismatic materializer
+ -> ordinary BRep validation
+ -> ordinary AP242 export and reimport
+```
+
+The lower-level `ExactBrep` output tier exists for truly unsupported exact constructions. It still runs `BrepBindingValidator`, STEP preflight/export, and STEP reimport. A mesh-derived capability cannot claim `ExactBrep`.
+
+Optional CIR output uses the same construction lineage. M1 admits the sample's exact axis-aligned prismatic CIR and runs `BrepCirConsistencyChecker` through an explicit `CirBrepAssociation`.
+
+## Determinism, provenance, and trust
+
+Registration is explicit; no arbitrary assembly scanning occurs. Capability enumeration and resolution use ordinal sorted IDs. Duplicate extension IDs, extension version conflicts, capability ID collisions, and capability version conflicts fail registration—there is no last-loaded-wins behavior.
+
+M1 rejects non-deterministic capabilities. Deterministic compilation assumes identical typed inputs, compiler version, extension IDs/versions, and resource hashes. Artifact hashes include STEP text, Template specialization identity, capability/version evidence, and provenance.
+
+Every extension artifact records host/module identity, Template specialization, capability ID/version, extension ID/version, construction identity, and final artifact validation. Raw plugin exceptions are wrapped in typed Forge diagnostics with capability and source context.
+
+Forge extensions are trusted compiler plugins in M1. They are not sandboxed, process-isolated, or suitable for untrusted code. Capabilities should be stateless; descriptors are immutable and invocation state arrives through an explicit context.
+
+## Package and future seams
+
+A normal .NET package may contain extension registration, Firmament modules, generated bindings, and tests. The package is activated explicitly by a host and declared in `ForgeExtensionManifest`. No marketplace or semantic-version negotiation is part of M1.
+
+The invocation model uses canonical values, dictionaries, resource hashes, module/template names, and extension identities rather than C# object identity. This is the future seam for Python, TypeScript, Go, RPC, and CLI descriptors; C# is the canonical implementation today.
+
+Future Firmament analysis Templates such as `ProofLoadAnalysis` can use the same host invocation and capability registry. New analysis output classifications and lowering targets can be added without making Firmament a runtime language or implementing FEA inside Forge M1.
+
+## Kernel policy
+
+“Aetheris does not support my construction” is not automatically a Kernel feature request. First use existing Firmament and Kernel capabilities. If they are insufficient, implement and register a Forge capability, keep it private if appropriate, and upstream it only after it proves broadly useful, exact, deterministic, generic, well tested, and maintainable.
diff --git a/docs/forge/artifacts/m1/README.md b/docs/forge/artifacts/m1/README.md
new file mode 100644
index 00000000..4e2ea760
--- /dev/null
+++ b/docs/forge/artifacts/m1/README.md
@@ -0,0 +1,24 @@
+# FORGE-SDK-M1 evidence
+
+Evidence is regenerated by:
+
+```powershell
+dotnet run --project tools/Aetheris.Forge.M1Evidence/Aetheris.Forge.M1Evidence.csproj -f net10.0
+```
+
+Files:
+
+- `current-forge-audit.md`: pre-change responsibility and coupling audit.
+- `api-surface-summary.md`: public M1 surface.
+- `capabilities.json`: inspectable registered capability metadata.
+- `template-metadata.json`: typed Template signature and generated name.
+- `invocation.json`: generated-binding/host invocation evidence.
+- `provenance.json`: host-to-artifact provenance trace.
+- `brep-validation.json`: topology counts and BRep/STEP validation.
+- `cli-analysis.json`: independent `Aetheris.CLI analyze --json` ground-truth inspection.
+- `cir-association.json`: ordinary CIR/BRep association result.
+- `determinism.json`: repeated artifact and STEP hashes.
+- `performance.json`: registration, resolution, Template, extension, and compiler-stage wall times.
+- `sample-secret-coupon.step`: validated external-capability AP242 artifact.
+
+The sample capability implementation is confined to `Aetheris.Forge.SampleExtension`; no capability-specific source exists in `Aetheris.Kernel.Core`.
diff --git a/docs/forge/artifacts/m1/api-surface-summary.md b/docs/forge/artifacts/m1/api-surface-summary.md
new file mode 100644
index 00000000..ff8c188e
--- /dev/null
+++ b/docs/forge/artifacts/m1/api-surface-summary.md
@@ -0,0 +1,31 @@
+# M1 API surface summary
+
+## Host embedding
+
+- `ForgeHost`: explicit extension environment, module loading, capability inspection.
+- `ForgeModule`: source/module identity and Template catalog.
+- `ForgeTemplate`: metadata plus invocation factory.
+- `ForgeInvocation`: typed bindings, resources, requested targets, compilation.
+- `ForgeCompilationResult` / `ForgeCompilationArtifact`: diagnostics, timings, AP242, deterministic hash, BRep/CIR evidence, capabilities, provenance.
+- `ForgeValue`: Length, Angle, Integer, Real, Boolean, String, Type, and structural Record values.
+- `ImportedStepResource`: canonical AP242 hash plus ordinary importer result.
+
+## Compiler seam
+
+- `FirmamentTemplateHostBridge.Inspect`: stable Template signature metadata.
+- `FirmamentTemplateHostBridge.Expand`: direct binder-IR invocation and specialization evidence.
+- `FirmamentBuildAndExport.CompileSource`: in-memory entry into the same materialization/validation path as file builds.
+
+## Extension SDK
+
+- `IForgeExtension`, `IForgeCapability`, `ForgeExtensionRegistry`.
+- `ForgeCapabilityDescriptorV1`, typed parameters, output classifications, lowering targets, determinism, admission/exactness/provenance contracts.
+- `ForgeExtensionManifest`, exact extension requirements.
+- `ForgeCapabilityExecutor`: typed admission, output-contract validation, ConstructionIR materialization, exact BRep validation, exception wrapping.
+- `Aetheris.Forge.Testing.ForgeExtensionAssertions`: focused author test kit.
+
+## Proof packages
+
+- `Aetheris.Forge.SampleExtension`: external/private capability and Firmament module.
+- `Aetheris.Forge.SampleExtension.Bindings`: deterministic generated binding proof using the same host path.
+- `Aetheris.Forge.Sdk.Tests`: native Template invocation, full extension stack, deterministic output, collision/version/missing diagnostics, resources, CIR association.
diff --git a/docs/forge/artifacts/m1/brep-validation.json b/docs/forge/artifacts/m1/brep-validation.json
new file mode 100644
index 00000000..b12acb2c
--- /dev/null
+++ b/docs/forge/artifacts/m1/brep-validation.json
@@ -0,0 +1,9 @@
+{
+ "bindingValidation": "passed",
+ "stepExport": "passed",
+ "stepReimport": "passed",
+ "vertices": 8,
+ "edges": 12,
+ "faces": 6,
+ "shells": 1
+}
diff --git a/docs/forge/artifacts/m1/capabilities.json b/docs/forge/artifacts/m1/capabilities.json
new file mode 100644
index 00000000..2f9e15f3
--- /dev/null
+++ b/docs/forge/artifacts/m1/capabilities.json
@@ -0,0 +1,44 @@
+[
+ {
+ "Id": {
+ "Value": "MyCompany.SecretGeometry.SecretCoupon"
+ },
+ "Version": "1.0.0",
+ "ExtensionId": "MyCompany.SecretGeometry",
+ "ExtensionVersion": "1.0.0",
+ "Description": "Private coupon sizing policy lowered to Aetheris standard prismatic ConstructionIR.",
+ "Inputs": [
+ {
+ "Name": "Width",
+ "Type": "Length",
+ "Required": true,
+ "DefaultValue": null,
+ "Description": "Finished coupon width."
+ },
+ {
+ "Name": "Depth",
+ "Type": "Length",
+ "Required": true,
+ "DefaultValue": null,
+ "Description": "Finished coupon depth."
+ },
+ {
+ "Name": "Height",
+ "Type": "Length",
+ "Required": true,
+ "DefaultValue": null,
+ "Description": "Finished coupon height."
+ }
+ ],
+ "OutputClassification": "ConstructionIr",
+ "SupportedTargets": [
+ "ConstructionIr",
+ "Brep",
+ "Cir"
+ ],
+ "Determinism": "Deterministic",
+ "ExactnessContract": "Exact planar, linear, closed manifold prism; no mesh-derived geometry.",
+ "AdmissionContract": "Width, Depth, and Height must be finite positive millimetre values.",
+ "ProvenanceIdentity": "MyCompany.SecretGeometry/SecretCoupon/v1"
+ }
+]
diff --git a/docs/forge/artifacts/m1/cir-association.json b/docs/forge/artifacts/m1/cir-association.json
new file mode 100644
index 00000000..98bd4fcc
--- /dev/null
+++ b/docs/forge/artifacts/m1/cir-association.json
@@ -0,0 +1,392 @@
+{
+ "Association": {
+ "ContinuumRegionId": {
+ "Value": "SecretBody:cir"
+ },
+ "BrepBodyId": "SecretBody",
+ "OuterShellId": "1",
+ "SemanticModelId": "SecretBody",
+ "ConstructionSourceIdentity": "[email protected]:24x16x6"
+ },
+ "Consistency": {
+ "Passed": true,
+ "Probes": [
+ {
+ "Kind": "face",
+ "EntityId": "1",
+ "Point": {
+ "X": -12,
+ "Y": -8,
+ "Z": -3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "face",
+ "EntityId": "2",
+ "Point": {
+ "X": -12,
+ "Y": 8,
+ "Z": 3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "face",
+ "EntityId": "3",
+ "Point": {
+ "X": -12,
+ "Y": -8,
+ "Z": -3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "face",
+ "EntityId": "4",
+ "Point": {
+ "X": 12,
+ "Y": -8,
+ "Z": -3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "face",
+ "EntityId": "5",
+ "Point": {
+ "X": 12,
+ "Y": 8,
+ "Z": -3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "face",
+ "EntityId": "6",
+ "Point": {
+ "X": -12,
+ "Y": 8,
+ "Z": -3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "edge",
+ "EntityId": "1",
+ "Point": {
+ "X": 0,
+ "Y": -8,
+ "Z": -3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "edge",
+ "EntityId": "2",
+ "Point": {
+ "X": 0,
+ "Y": -8,
+ "Z": 3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "edge",
+ "EntityId": "3",
+ "Point": {
+ "X": -12,
+ "Y": -8,
+ "Z": 0
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "edge",
+ "EntityId": "4",
+ "Point": {
+ "X": 12,
+ "Y": 0,
+ "Z": -3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "edge",
+ "EntityId": "5",
+ "Point": {
+ "X": 12,
+ "Y": 0,
+ "Z": 3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "edge",
+ "EntityId": "6",
+ "Point": {
+ "X": 12,
+ "Y": -8,
+ "Z": 0
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "edge",
+ "EntityId": "7",
+ "Point": {
+ "X": 0,
+ "Y": 8,
+ "Z": -3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "edge",
+ "EntityId": "8",
+ "Point": {
+ "X": 0,
+ "Y": 8,
+ "Z": 3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "edge",
+ "EntityId": "9",
+ "Point": {
+ "X": 12,
+ "Y": 8,
+ "Z": 0
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "edge",
+ "EntityId": "10",
+ "Point": {
+ "X": -12,
+ "Y": 0,
+ "Z": -3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "edge",
+ "EntityId": "11",
+ "Point": {
+ "X": -12,
+ "Y": 0,
+ "Z": 3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "edge",
+ "EntityId": "12",
+ "Point": {
+ "X": -12,
+ "Y": 8,
+ "Z": 0
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "vertex",
+ "EntityId": "1",
+ "Point": {
+ "X": -12,
+ "Y": -8,
+ "Z": -3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "vertex",
+ "EntityId": "2",
+ "Point": {
+ "X": 12,
+ "Y": -8,
+ "Z": -3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "vertex",
+ "EntityId": "3",
+ "Point": {
+ "X": 12,
+ "Y": 8,
+ "Z": -3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "vertex",
+ "EntityId": "4",
+ "Point": {
+ "X": -12,
+ "Y": 8,
+ "Z": -3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "vertex",
+ "EntityId": "5",
+ "Point": {
+ "X": -12,
+ "Y": -8,
+ "Z": 3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "vertex",
+ "EntityId": "6",
+ "Point": {
+ "X": 12,
+ "Y": -8,
+ "Z": 3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "vertex",
+ "EntityId": "7",
+ "Point": {
+ "X": 12,
+ "Y": 8,
+ "Z": 3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "vertex",
+ "EntityId": "8",
+ "Point": {
+ "X": -12,
+ "Y": 8,
+ "Z": 3
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "known-interior",
+ "EntityId": "region-center",
+ "Point": {
+ "X": 0,
+ "Y": 0,
+ "Z": 0
+ },
+ "Classification": "Inside",
+ "Passed": true
+ },
+ {
+ "Kind": "known-exterior",
+ "EntityId": "expanded-max",
+ "Point": {
+ "X": 36,
+ "Y": 24,
+ "Z": 9
+ },
+ "Classification": "Outside",
+ "Passed": true
+ },
+ {
+ "Kind": "extent-conservative-containment",
+ "EntityId": "min-x",
+ "Point": {
+ "X": -12,
+ "Y": -12,
+ "Z": 0
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "extent-conservative-containment",
+ "EntityId": "min-y",
+ "Point": {
+ "X": -8,
+ "Y": -8,
+ "Z": 0
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "extent-conservative-containment",
+ "EntityId": "min-z",
+ "Point": {
+ "X": -3,
+ "Y": -3,
+ "Z": 0
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "extent-conservative-containment",
+ "EntityId": "max-x",
+ "Point": {
+ "X": 12,
+ "Y": 12,
+ "Z": 0
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "extent-conservative-containment",
+ "EntityId": "max-y",
+ "Point": {
+ "X": 8,
+ "Y": 8,
+ "Z": 0
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ },
+ {
+ "Kind": "extent-conservative-containment",
+ "EntityId": "max-z",
+ "Point": {
+ "X": 3,
+ "Y": 3,
+ "Z": 0
+ },
+ "Classification": "Boundary",
+ "Passed": true
+ }
+ ],
+ "Summary": "BRep/CIR agreement passed for 34 deterministic probes; conservative extent residual=0.",
+ "MaximumExtentResidual": 0
+ }
+}
diff --git a/docs/forge/artifacts/m1/cli-analysis.json b/docs/forge/artifacts/m1/cli-analysis.json
new file mode 100644
index 00000000..0d57f3bd
--- /dev/null
+++ b/docs/forge/artifacts/m1/cli-analysis.json
@@ -0,0 +1,29 @@
+{
+ "command": "dotnet run --project Aetheris.CLI -- analyze docs/forge/artifacts/m1/sample-secret-coupon.step --json",
+ "bodyCount": 1,
+ "shellCount": 1,
+ "faceCount": 6,
+ "edgeCount": 12,
+ "vertexCount": 8,
+ "boundingBox": {
+ "min": [-12, -8, -3],
+ "max": [12, 8, 3]
+ },
+ "structuralAssessment": "enclosed-manifold",
+ "surfaceFamilies": {
+ "plane": 6,
+ "cylinder": 0,
+ "cone": 0,
+ "sphere": 0,
+ "torus": 0,
+ "bspline": 0
+ },
+ "curveFamilies": {
+ "line": 12,
+ "circle": 0,
+ "hyperbola": 0,
+ "ellipse": 0,
+ "bspline": 0
+ },
+ "idsContiguous": true
+}
diff --git a/docs/forge/artifacts/m1/current-forge-audit.md b/docs/forge/artifacts/m1/current-forge-audit.md
new file mode 100644
index 00000000..92e72ace
--- /dev/null
+++ b/docs/forge/artifacts/m1/current-forge-audit.md
@@ -0,0 +1,25 @@
+# FORGE-SDK-M1 baseline audit
+
+Before M1, `Aetheris.Forge` targeted `net10.0`, referenced only `Aetheris.Kernel.Core`, and contained three responsibility groups:
+
+1. Descriptor/inspection scaffolding in `Aetheris.Forge.Abstractions`, including package, Concept, Template, capability, fixture, diagnostic, and LLM-guidance descriptors.
+2. Firmament Concept interop in `Aetheris.Forge.Abstractions.FirmamentInterop`, including typed scalar views, Concept schemas and validators, a deterministic Concept registry, explicit trusted assembly loading, and built-in standard Concept packs.
+3. Legacy/experimental geometry helpers (`ForgeAtomics`, `ForgeRoundedRectangleProfile`) directly used by Standard Library code and tests.
+
+Firmament already depended on Forge for runtime Concept validation. The CLI could accept trusted external Concept-pack assemblies, but activation used reflection over `IForgeConceptPack` implementations and was limited to Concept validation/PMI obligations. There was no host Template invocation API, direct typed host binder, compilation result model, generated binding seam, construction capability registry, exactness classification, extension manifest, capability provenance, or CIR/BRep extension proof.
+
+Compiler invocation lived in `Aetheris.Kernel.Firmament` through file/source parsers and `FirmamentBuildAndExport`. Modern Template declarations were parsed into an internal immutable binder IR, specialized, and erased before AIR, but applications had to appear in Firmament source. InlineStep consumed canonical STEP through `Step242Importer` and preserved canonical hashes/topology maps.
+
+The accidental boundary pressure was that making the existing `Aetheris.Forge` assembly depend on the compiler would create a cycle (`Firmament -> Forge`). M1 therefore retained low-level contracts in `Aetheris.Forge`, exposed a narrow public Template-host bridge from Firmament, and added `Aetheris.Forge.Sdk` above the compiler. Existing Concept-pack behavior and legacy helpers remain compatible but are not the new construction-extension API.
+
+Baseline classification:
+
+| Area | Before M1 |
+|---|---|
+| Embedding | absent |
+| Invocation | source-authored Template applications only |
+| Compilation | Firmament file/source services, not Forge-owned |
+| Inspection | descriptor and Concept metadata scaffolds |
+| Artifact access | compiler/CLI-specific |
+| Extension | Concept validation packs only; no construction output |
+| Legacy/experimental | rounded-rectangle/extrusion helper API |
diff --git a/docs/forge/artifacts/m1/determinism.json b/docs/forge/artifacts/m1/determinism.json
new file mode 100644
index 00000000..a44ee4ff
--- /dev/null
+++ b/docs/forge/artifacts/m1/determinism.json
@@ -0,0 +1,18 @@
+{
+ "repeatedRuns": 2,
+ "sameArtifactHash": true,
+ "sameStepText": true,
+ "artifactHash": "7282965B703FEB85478AC8B651B6F6255D3BC922D3B2A7EBE73726C611CB4D36",
+ "capability": {
+ "CapabilityId": "MyCompany.SecretGeometry.SecretCoupon",
+ "CapabilityVersion": "1.0.0",
+ "ExtensionId": "MyCompany.SecretGeometry",
+ "ExtensionVersion": "1.0.0",
+ "OutputClassification": "ConstructionIr",
+ "LoweringTargets": [
+ "ConstructionIr",
+ "Brep",
+ "Cir"
+ ]
+ }
+}
diff --git a/docs/forge/artifacts/m1/invocation.json b/docs/forge/artifacts/m1/invocation.json
new file mode 100644
index 00000000..aef93695
--- /dev/null
+++ b/docs/forge/artifacts/m1/invocation.json
@@ -0,0 +1,20 @@
+{
+ "module": "SecretGeometry",
+ "template": "SecretCoupon",
+ "instance": "PrivateCoupon",
+ "generatedBinding": "ForgeTemplates.SecretCoupon(module, new SecretCouponSpec(24, 16, 6))",
+ "parameters": {
+ "Spec": {
+ "type": "SecretCouponSpec",
+ "Width": "24mm",
+ "Depth": "16mm",
+ "Height": "6mm"
+ }
+ },
+ "targets": [
+ "Brep",
+ "Cir"
+ ],
+ "success": true,
+ "diagnostics": []
+}
diff --git a/docs/forge/artifacts/m1/performance.json b/docs/forge/artifacts/m1/performance.json
new file mode 100644
index 00000000..6cd3b291
--- /dev/null
+++ b/docs/forge/artifacts/m1/performance.json
@@ -0,0 +1,18 @@
+{
+ "units": "milliseconds",
+ "first": {
+ "registration": 4.5488,
+ "capabilityResolution": 0.0795,
+ "templateInvocation": 37.5553,
+ "extensionLowering": 6.6124,
+ "compilerAndValidation": 201.7962
+ },
+ "warm": {
+ "registration": 4.5488,
+ "capabilityResolution": 0.0017,
+ "templateInvocation": 0.4954,
+ "extensionLowering": 0.0333,
+ "compilerAndValidation": 1.2135
+ },
+ "note": "Developer-machine wall-clock evidence; not a benchmark or release gate."
+}
diff --git a/docs/forge/artifacts/m1/provenance.json b/docs/forge/artifacts/m1/provenance.json
new file mode 100644
index 00000000..70578791
--- /dev/null
+++ b/docs/forge/artifacts/m1/provenance.json
@@ -0,0 +1,27 @@
+[
+ {
+ "Stage": "host",
+ "Identity": "C:\\Users\\yuech\\source\\repos\\Aetheris\\Aetheris.Forge.SampleExtension\\Templates\\SecretGeometry.firmament",
+ "Evidence": "PrivateCoupon"
+ },
+ {
+ "Stage": "template",
+ "Identity": "SecretCoupon",
+ "Evidence": "template:b95fb6d42442bd41;record-arguments=Spec"
+ },
+ {
+ "Stage": "capability",
+ "Identity": "MyCompany.SecretGeometry.SecretCoupon",
+ "Evidence": "[email protected];MyCompany.SecretGeometry/SecretCoupon/v1"
+ },
+ {
+ "Stage": "construction",
+ "Identity": "[email protected]:24x16x6",
+ "Evidence": "SecretBody"
+ },
+ {
+ "Stage": "artifact",
+ "Identity": "SecretBody",
+ "Evidence": "STEP AP242 export and reimport validated"
+ }
+]
diff --git a/docs/forge/artifacts/m1/sample-secret-coupon.step b/docs/forge/artifacts/m1/sample-secret-coupon.step
new file mode 100644
index 00000000..022c173a
--- /dev/null
+++ b/docs/forge/artifacts/m1/sample-secret-coupon.step
@@ -0,0 +1,172 @@
+ISO-10303-21;
+HEADER;
+FILE_DESCRIPTION(('Aetheris AP242 subset export'),'2;1');
+FILE_NAME('aetheris_export.step','1970-01-01T00:00:00',('Aetheris'),('Aetheris'),'Aetheris.Kernel','Aetheris.Kernel','');
+FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF'));
+ENDSEC;
+DATA;
+#1=CARTESIAN_POINT($,(0,0,-3));
+#2=DIRECTION($,(-0,-0,-1));
+#3=DIRECTION($,(1,0,0));
+#4=AXIS2_PLACEMENT_3D($,#1,#2,#3);
+#5=PLANE($,#4);
+#6=CARTESIAN_POINT($,(-12,-8,-3));
+#7=VERTEX_POINT($,#6);
+#8=CARTESIAN_POINT($,(12,-8,-3));
+#9=VERTEX_POINT($,#8);
+#10=CARTESIAN_POINT($,(-12,-8,-3));
+#11=DIRECTION($,(1,0,0));
+#12=VECTOR($,#11,1);
+#13=LINE($,#10,#12);
+#14=EDGE_CURVE($,#7,#9,#13,.T.);
+#15=ORIENTED_EDGE($,$,$,#14,.T.);
+#16=CARTESIAN_POINT($,(12,8,-3));
+#17=VERTEX_POINT($,#16);
+#18=CARTESIAN_POINT($,(12,-8,-3));
+#19=DIRECTION($,(0,1,0));
+#20=VECTOR($,#19,1);
+#21=LINE($,#18,#20);
+#22=EDGE_CURVE($,#9,#17,#21,.T.);
+#23=ORIENTED_EDGE($,$,$,#22,.T.);
+#24=CARTESIAN_POINT($,(-12,8,-3));
+#25=VERTEX_POINT($,#24);
+#26=CARTESIAN_POINT($,(12,8,-3));
+#27=DIRECTION($,(-1,0,0));
+#28=VECTOR($,#27,1);
+#29=LINE($,#26,#28);
+#30=EDGE_CURVE($,#17,#25,#29,.T.);
+#31=ORIENTED_EDGE($,$,$,#30,.T.);
+#32=CARTESIAN_POINT($,(-12,8,-3));
+#33=DIRECTION($,(0,-1,0));
+#34=VECTOR($,#33,1);
+#35=LINE($,#32,#34);
+#36=EDGE_CURVE($,#25,#7,#35,.T.);
+#37=ORIENTED_EDGE($,$,$,#36,.T.);
+#38=EDGE_LOOP($,(#15,#23,#31,#37));
+#39=FACE_OUTER_BOUND('',#38,.T.);
+#40=ADVANCED_FACE('',(#39),#5,.T.);
+#41=CARTESIAN_POINT($,(0,0,3));
+#42=DIRECTION($,(0,0,1));
+#43=DIRECTION($,(1,0,0));
+#44=AXIS2_PLACEMENT_3D($,#41,#42,#43);
+#45=PLANE($,#44);
+#46=CARTESIAN_POINT($,(-12,8,3));
+#47=VERTEX_POINT($,#46);
+#48=CARTESIAN_POINT($,(-12,-8,3));
+#49=VERTEX_POINT($,#48);
+#50=CARTESIAN_POINT($,(-12,8,3));
+#51=DIRECTION($,(0,-1,0));
+#52=VECTOR($,#51,1);
+#53=LINE($,#50,#52);
+#54=EDGE_CURVE($,#47,#49,#53,.T.);
+#55=ORIENTED_EDGE($,$,$,#54,.F.);
+#56=CARTESIAN_POINT($,(12,8,3));
+#57=VERTEX_POINT($,#56);
+#58=CARTESIAN_POINT($,(12,8,3));
+#59=DIRECTION($,(-1,0,0));
+#60=VECTOR($,#59,1);
+#61=LINE($,#58,#60);
+#62=EDGE_CURVE($,#57,#47,#61,.T.);
+#63=ORIENTED_EDGE($,$,$,#62,.F.);
+#64=CARTESIAN_POINT($,(12,-8,3));
+#65=VERTEX_POINT($,#64);
+#66=CARTESIAN_POINT($,(12,-8,3));
+#67=DIRECTION($,(0,1,0));
+#68=VECTOR($,#67,1);
+#69=LINE($,#66,#68);
+#70=EDGE_CURVE($,#65,#57,#69,.T.);
+#71=ORIENTED_EDGE($,$,$,#70,.F.);
+#72=CARTESIAN_POINT($,(-12,-8,3));
+#73=DIRECTION($,(1,0,0));
+#74=VECTOR($,#73,1);
+#75=LINE($,#72,#74);
+#76=EDGE_CURVE($,#49,#65,#75,.T.);
+#77=ORIENTED_EDGE($,$,$,#76,.F.);
+#78=EDGE_LOOP($,(#55,#63,#71,#77));
+#79=FACE_OUTER_BOUND('',#78,.T.);
+#80=ADVANCED_FACE('',(#79),#45,.T.);
+#81=CARTESIAN_POINT($,(-12,-8,-3));
+#82=DIRECTION($,(0,-1,0));
+#83=DIRECTION($,(0,0,1));
+#84=AXIS2_PLACEMENT_3D($,#81,#82,#83);
+#85=PLANE($,#84);
+#86=ORIENTED_EDGE($,$,$,#14,.T.);
+#87=CARTESIAN_POINT($,(12,-8,-3));
+#88=DIRECTION($,(0,0,1));
+#89=VECTOR($,#88,1);
+#90=LINE($,#87,#89);
+#91=EDGE_CURVE($,#9,#65,#90,.T.);
+#92=ORIENTED_EDGE($,$,$,#91,.T.);
+#93=ORIENTED_EDGE($,$,$,#76,.F.);
+#94=CARTESIAN_POINT($,(-12,-8,-3));
+#95=DIRECTION($,(0,0,1));
+#96=VECTOR($,#95,1);
+#97=LINE($,#94,#96);
+#98=EDGE_CURVE($,#7,#49,#97,.T.);
+#99=ORIENTED_EDGE($,$,$,#98,.F.);
+#100=EDGE_LOOP($,(#86,#92,#93,#99));
+#101=FACE_OUTER_BOUND('',#100,.T.);
+#102=ADVANCED_FACE('',(#101),#85,.T.);
+#103=CARTESIAN_POINT($,(12,-8,-3));
+#104=DIRECTION($,(1,0,0));
+#105=DIRECTION($,(0,0,1));
+#106=AXIS2_PLACEMENT_3D($,#103,#104,#105);
+#107=PLANE($,#106);
+#108=ORIENTED_EDGE($,$,$,#22,.T.);
+#109=CARTESIAN_POINT($,(12,8,-3));
+#110=DIRECTION($,(0,0,1));
+#111=VECTOR($,#110,1);
+#112=LINE($,#109,#111);
+#113=EDGE_CURVE($,#17,#57,#112,.T.);
+#114=ORIENTED_EDGE($,$,$,#113,.T.);
+#115=ORIENTED_EDGE($,$,$,#70,.F.);
+#116=ORIENTED_EDGE($,$,$,#91,.F.);
+#117=EDGE_LOOP($,(#108,#114,#115,#116));
+#118=FACE_OUTER_BOUND('',#117,.T.);
+#119=ADVANCED_FACE('',(#118),#107,.T.);
+#120=CARTESIAN_POINT($,(12,8,-3));
+#121=DIRECTION($,(0,1,-0));
+#122=DIRECTION($,(0,0,1));
+#123=AXIS2_PLACEMENT_3D($,#120,#121,#122);
+#124=PLANE($,#123);
+#125=ORIENTED_EDGE($,$,$,#30,.T.);
+#126=CARTESIAN_POINT($,(-12,8,-3));
+#127=DIRECTION($,(0,0,1));
+#128=VECTOR($,#127,1);
+#129=LINE($,#126,#128);
+#130=EDGE_CURVE($,#25,#47,#129,.T.);
+#131=ORIENTED_EDGE($,$,$,#130,.T.);
+#132=ORIENTED_EDGE($,$,$,#62,.F.);
+#133=ORIENTED_EDGE($,$,$,#113,.F.);
+#134=EDGE_LOOP($,(#125,#131,#132,#133));
+#135=FACE_OUTER_BOUND('',#134,.T.);
+#136=ADVANCED_FACE('',(#135),#124,.T.);
+#137=CARTESIAN_POINT($,(-12,8,-3));
+#138=DIRECTION($,(-1,0,0));
+#139=DIRECTION($,(0,0,1));
+#140=AXIS2_PLACEMENT_3D($,#137,#138,#139);
+#141=PLANE($,#140);
+#142=ORIENTED_EDGE($,$,$,#36,.T.);
+#143=ORIENTED_EDGE($,$,$,#98,.T.);
+#144=ORIENTED_EDGE($,$,$,#54,.F.);
+#145=ORIENTED_EDGE($,$,$,#130,.F.);
+#146=EDGE_LOOP($,(#142,#143,#144,#145));
+#147=FACE_OUTER_BOUND('',#146,.T.);
+#148=ADVANCED_FACE('',(#147),#141,.T.);
+#149=CLOSED_SHELL($,(#40,#80,#102,#119,#136,#148));
+#150=MANIFOLD_SOLID_BREP('SecretBody',#149);
+#151=APPLICATION_CONTEXT('mechanical design');
+#152=PRODUCT_CONTEXT('',#151,'mechanical');
+#153=PRODUCT('AETHERIS','SecretBody','',(#152));
+#154=PRODUCT_DEFINITION_FORMATION('','',#153);
+#155=PRODUCT_DEFINITION_CONTEXT('design',#151,'design');
+#156=PRODUCT_DEFINITION('','',#154,#155);
+#157=PRODUCT_DEFINITION_SHAPE('','',#156);
+#158=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));
+#159=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.));
+#160=(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT());
+#161=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNIT_ASSIGNED_CONTEXT((#158,#159,#160))REPRESENTATION_CONTEXT('3','3D'));
+#162=SHAPE_REPRESENTATION('SecretBody',(#150),#161);
+#163=SHAPE_DEFINITION_REPRESENTATION(#157,#162);
+ENDSEC;
+END-ISO-10303-21;
diff --git a/docs/forge/artifacts/m1/template-metadata.json b/docs/forge/artifacts/m1/template-metadata.json
new file mode 100644
index 00000000..bbbf87b9
--- /dev/null
+++ b/docs/forge/artifacts/m1/template-metadata.json
@@ -0,0 +1,17 @@
+[
+ {
+ "ModuleName": "SecretGeometry",
+ "Name": "SecretCoupon",
+ "TargetKind": "Struct",
+ "Parameters": [
+ {
+ "Name": "Spec",
+ "TypeName": "SecretCouponSpec",
+ "IsTypeParameter": false,
+ "DefaultValue": null,
+ "ConstraintConcept": null
+ }
+ ],
+ "GeneratedBindingName": "SecretCoupon"
+ }
+]
diff --git a/docs/forge/capability-graduation.md b/docs/forge/capability-graduation.md
new file mode 100644
index 00000000..b49d52cb
--- /dev/null
+++ b/docs/forge/capability-graduation.md
@@ -0,0 +1,27 @@
+# Forge capability graduation
+
+The expected lifecycle is:
+
+```text
+private bounded C# helper
+ -> explicit Forge extension
+ -> reusable internal or public package
+ -> optional shared-Kernel candidate
+```
+
+Working code is not automatically a Kernel feature. A capability should remain private or packaged through Forge when its semantics are customer-specific, proprietary, fast-moving, narrowly useful, or expensive for the shared project to maintain.
+
+A candidate may graduate upstream only when evidence shows:
+
+- broad usefulness across multiple independent consumers;
+- generic semantics rather than customer policy;
+- an honest exactness contract and admitted support geometry;
+- deterministic behavior and stable identity;
+- strong construction, BRep, export, provenance, and where relevant CIR tests;
+- successful use across more than one extension or product scenario;
+- a manageable long-term maintenance burden;
+- a clear improvement to the small shared substrate rather than API duplication.
+
+Graduation should preserve the existing Forge capability or provide a deterministic migration path. It must not force private callers to rewrite their Firmament Templates merely because an implementation becomes shared.
+
+For the common report “the Kernel does not support my geometry,” first inspect existing Firmament Templates and Kernel primitives. If the missing operation is not demonstrably general, author and register a Forge capability. Upstream it only after the evidence above exists.
diff --git a/docs/forge/extension-sdk.md b/docs/forge/extension-sdk.md
new file mode 100644
index 00000000..ae4762eb
--- /dev/null
+++ b/docs/forge/extension-sdk.md
@@ -0,0 +1,70 @@
+# Forge extension SDK
+
+Extension packages implement `IForgeExtension` and register immutable `IForgeCapability` instances explicitly with `ForgeExtensionRegistry`.
+
+```csharp
+public sealed class SecretGeometryExtension : IForgeExtension
+{
+ public string Id => "MyCompany.SecretGeometry";
+ public Version Version => new(1, 0, 0);
+
+ public void Register(ForgeExtensionRegistry registry) =>
+ registry.RegisterCapability(new SecretCouponCapability());
+}
+```
+
+There is no default assembly scan, reflection dispatch, global mutable registry, or `InvokeMethod("Assembly.Type.Method")` API.
+
+## Capability descriptor
+
+`ForgeCapabilityDescriptorV1` publishes:
+
+- stable capability ID and version;
+- extension/package ID and version;
+- typed input schema and descriptions;
+- output classification and supported lowering targets;
+- deterministic/experimental classification;
+- exactness, admission, and provenance contracts.
+
+`ForgeHost.Capabilities` and `ForgeExtensionRegistry.InspectCapabilities()` return descriptors in ordinal ID order. Tooling and LLMs can discover what exists, understand parameters and output guarantees, and interpret typed admission failures without reading implementation source.
+
+## Output tiers
+
+M1 adopts capability levels through output classification and lowering targets rather than separate registration systems:
+
+- `SemanticOnly`: compiler semantics with no geometry claim.
+- `ConstructionIr`: preferred custom intent lowered to `ContinuumConstructionDescriptor` and a standard Forge materializer.
+- `ExactBrep`: bounded low-level escape hatch using public Kernel BRep types and mandatory validation.
+- `ContinuumRegion`: optional CIR construction lineage.
+- `SurfaceMeshDerived`: explicitly non-exact and forbidden from masquerading as ExactBRep.
+- `Analysis`: reserved seam for future analysis compilers.
+
+The sample uses `ConstructionIr` and supports `ConstructionIr`, `Brep`, and `Cir` targets. It emits no topology lists and calls no Kernel internals.
+
+## Validation
+
+`ForgeCapabilityExecutor` validates parameter schema, requested targets, declared output classification, ConstructionIR invariants, exact BRep bindings, provenance completeness, and exception boundaries. `ForgeHost` then materializes via the standard executor, validates the BRep again at the acceptance boundary, exports AP242, and reimports the result. Requested CIR output receives an explicit association and consistency check.
+
+An extension cannot state “trust me, this BRep is valid.” A SurfaceMesh-derived result cannot claim exactness. Unexpected exceptions become `forge-capability-exception` with capability and source identity.
+
+## Manifest and resolution
+
+```csharp
+var manifest = new ForgeExtensionManifest([
+ new ForgeExtensionRequirement("MyCompany.SecretGeometry", new Version(1, 0, 0)),
+]);
+
+var host = new ForgeHost([new SecretGeometryExtension()], manifest);
+```
+
+The manifest is the reproducible extension environment for compilation. M1 requires exact extension versions and diagnoses missing or conflicting registrations; it does not negotiate version ranges. Capability references in Firmament use stable IDs in `Construct` declarations. Ambient DLL load order never changes semantics.
+
+## Packaging and lifetime
+
+The normal distribution unit is a .NET package/assembly containing registration code and capabilities, with optional Firmament modules, generated bindings, and tests. Capabilities should be stateless. Per-invocation information arrives through `ForgeCapabilityInvocationContext`; output and provenance are immutable values. Extensions are trusted local compiler code and are not sandboxed in M1.
+
+`Aetheris.Forge.Testing` provides focused helpers for successful fixture compilation, BRep validation, AP242 round trips, deterministic hash comparison, provenance completeness, and CIR association. It intentionally does not expose or duplicate internal test infrastructure.
+
+## Sample extension
+
+`Aetheris.Forge.SampleExtension` represents private `MyCompany.SecretGeometry`. `SecretCouponCapability` applies private sizing semantics and emits a generic exact prismatic construction descriptor. The Firmament Template remains domain code, the generated C# binding uses Forge, and the resulting body is an ordinary validated Aetheris artifact. The extension implementation contains zero capability-specific code in `Aetheris.Kernel.Core`.
diff --git a/docs/forge/invocation-sdk.md b/docs/forge/invocation-sdk.md
new file mode 100644
index 00000000..e3f64f28
--- /dev/null
+++ b/docs/forge/invocation-sdk.md
@@ -0,0 +1,80 @@
+# Forge invocation SDK
+
+`Aetheris.Forge.Sdk` exposes the host workflow `ForgeHost -> ForgeModule -> ForgeTemplate -> ForgeInvocation -> ForgeCompilationResult`.
+
+## Typed Template invocation
+
+```csharp
+var host = new ForgeHost();
+var module = host.LoadModule("parts.firmament");
+var template = module.ResolveTemplate("HostBox");
+
+ForgeCompilationResult result = template.Invoke("FixtureBox")
+ .Bind("Width", new ForgeLength(20))
+ .Bind("Depth", new ForgeLength(12))
+ .Bind("Height", new ForgeLength(5))
+ .Compile();
+```
+
+The module source is parsed because it is a real source file. The host does not concatenate an application source string: `FirmamentTemplateHostBridge` creates the application and host Record bindings directly in the existing Template binder IR. Parameter names, kinds, types, defaults, Record types, and type-parameter constraints are available through `ForgeTemplateMetadata` before invocation. Missing, unknown, and mismatched bindings stop before compiler or extension lowering.
+
+`ForgeCompilationResult` exposes typed diagnostics, stage timings, AP242 artifact text, deterministic artifact hash, capability evidence, provenance, optional BRep, and optional CIR association evidence.
+
+## Generated binding proof
+
+`Aetheris.Forge.SampleExtension.Bindings/ForgeTemplates.g.cs` demonstrates deterministic generated names and strongly typed C# records:
+
+```csharp
+var invocation = ForgeTemplates.SecretCoupon(
+ module,
+ new SecretCouponSpec(24, 16, 6),
+ instanceName: "PrivateCoupon");
+
+var result = invocation
+ .WithTargets(ForgeLoweringTarget.Brep, ForgeLoweringTarget.Cir)
+ .Compile();
+```
+
+The generated method only creates `ForgeValue` bindings and calls the same `ForgeInvocation` path. It contains no compiler or materialization logic. `ForgeGeneratedNames.TemplateMethod` defines the M1 deterministic identifier normalization seam; a production source generator remains future work.
+
+## Record values
+
+Records are supplied structurally:
+
+```csharp
+new ForgeRecord("SecretCouponSpec", new Dictionary<string, ForgeValue>
+{
+ ["Width"] = new ForgeLength(24),
+ ["Depth"] = new ForgeLength(16),
+ ["Height"] = new ForgeLength(6),
+});
+```
+
+The binder checks the declared Record type and validates members through the normal Firmament Template binder before feature lowering.
+
+## Imported STEP resources
+
+```csharp
+var resource = ImportedStepResource.Load("VendorPart", canonicalStepPath);
+invocation.AddResource(resource);
+```
+
+`ImportedStepResource.Load` requires Aetheris-canonical AP242, computes SHA-256, and imports through the ordinary `Step242Importer`; it does not establish a second STEP pipeline. A capability parameter declared as `ImportedStepResource` can bind it with `$VendorPart` in a bounded `Construct` input. Native InlineStep Template parameter binding is not generalized in M1.
+
+## Diagnostics
+
+Expected failures are returned as `ForgeDiagnostic`; normal compiler UX never receives a raw extension exception. Important M1 codes include:
+
+- `forge-template-parameter-missing`, `forge-template-parameter-unknown`, `forge-template-parameter-mismatch`
+- `forge-extension-missing`, `forge-extension-version-conflict`
+- `forge-capability-missing`, `forge-capability-id-collision`, `forge-capability-version-conflict`
+- `forge-capability-parameter-missing`, `forge-capability-parameter-unknown`, `forge-capability-parameter-mismatch`
+- `forge-capability-admission-rejected`, `forge-capability-output-contract-violation`
+- `forge-capability-construction-invalid`, `forge-capability-brep-invalid`
+- `forge-capability-lowering-target-unsupported`, `forge-capability-nondeterministic`
+- `forge-capability-provenance-missing`, `forge-capability-exception`
+- `forge-capability-cir-output-missing`, `forge-capability-cir-brep-inconsistent`
+
+## M1 limitations
+
+M1 materializes one `Construct` result per host invocation. Standard ConstructionIR materialization admits two ordered, corresponding, identical polygonal sections (an exact prism). CIR association is implemented for the sample's axis-aligned box region. Rich assembly composition, generalized loft materialization, nested host Record construction, native InlineStep Template parameters, and production C# source generation are deliberate next steps rather than hidden fallbacks.
diff --git a/tools/Aetheris.Forge.M1Evidence/Aetheris.Forge.M1Evidence.csproj b/tools/Aetheris.Forge.M1Evidence/Aetheris.Forge.M1Evidence.csproj
new file mode 100644
index 00000000..b6b9658a
--- /dev/null
+++ b/tools/Aetheris.Forge.M1Evidence/Aetheris.Forge.M1Evidence.csproj
@@ -0,0 +1,14 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <OutputType>Exe</OutputType>
+ <TargetFramework>net10.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ </PropertyGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\..\Aetheris.Forge.Sdk\Aetheris.Forge.Sdk.csproj" />
+ <ProjectReference Include="..\..\Aetheris.Forge.SampleExtension\Aetheris.Forge.SampleExtension.csproj" />
+ <ProjectReference Include="..\..\Aetheris.Forge.SampleExtension.Bindings\Aetheris.Forge.SampleExtension.Bindings.csproj" />
+ <ProjectReference Include="..\..\Aetheris.Forge.Testing\Aetheris.Forge.Testing.csproj" />
+ </ItemGroup>
+</Project>
diff --git a/tools/Aetheris.Forge.M1Evidence/Program.cs b/tools/Aetheris.Forge.M1Evidence/Program.cs
new file mode 100644
index 00000000..25a16b95
--- /dev/null
+++ b/tools/Aetheris.Forge.M1Evidence/Program.cs
@@ -0,0 +1,92 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Aetheris.Forge.Extensions;
+using Aetheris.Forge.Sdk;
+using Aetheris.Forge.Testing;
+using MyCompany.SecretGeometry;
+using MyCompany.SecretGeometry.Generated;
+
+var root = FindRepositoryRoot();
+var output = Path.Combine(root, "docs", "forge", "artifacts", "m1");
+Directory.CreateDirectory(output);
+var modulePath = Path.Combine(root, "Aetheris.Forge.SampleExtension", "Templates", "SecretGeometry.firmament");
+var manifest = new ForgeExtensionManifest([new(SecretGeometryExtension.ExtensionId, SecretGeometryExtension.ExtensionVersion)]);
+var host = new ForgeHost([new SecretGeometryExtension()], manifest);
+var module = host.LoadModule(modulePath);
+var first = ForgeTemplates.SecretCoupon(module, new SecretCouponSpec(24d, 16d, 6d), "PrivateCoupon")
+ .WithTargets(ForgeLoweringTarget.Brep, ForgeLoweringTarget.Cir)
+ .Compile();
+var second = ForgeTemplates.SecretCoupon(module, new SecretCouponSpec(24d, 16d, 6d), "PrivateCoupon")
+ .WithTargets(ForgeLoweringTarget.Brep, ForgeLoweringTarget.Cir)
+ .Compile();
+ForgeExtensionAssertions.RequireDeterministic(first, second);
+ForgeExtensionAssertions.RequireCompleteProvenance(first.Artifact!);
+ForgeExtensionAssertions.RequireValidBrep(first.Artifact!.Body!);
+ForgeExtensionAssertions.RequireCirAssociation(first.Artifact);
+ForgeExtensionAssertions.RequireStepRoundTrip(first.Artifact.StepText);
+
+var json = new JsonSerializerOptions
+{
+ WriteIndented = true,
+ Converters = { new JsonStringEnumConverter() },
+};
+Write("capabilities.json", host.Capabilities);
+Write("template-metadata.json", module.Templates);
+Write("invocation.json", new
+{
+ module = module.Name,
+ template = "SecretCoupon",
+ instance = "PrivateCoupon",
+ generatedBinding = "ForgeTemplates.SecretCoupon(module, new SecretCouponSpec(24, 16, 6))",
+ parameters = new { Spec = new { type = "SecretCouponSpec", Width = "24mm", Depth = "16mm", Height = "6mm" } },
+ targets = new[] { "Brep", "Cir" },
+ success = first.IsSuccess,
+ diagnostics = first.Diagnostics,
+});
+Write("provenance.json", first.Artifact.Provenance);
+Write("brep-validation.json", new
+{
+ bindingValidation = "passed",
+ stepExport = "passed",
+ stepReimport = "passed",
+ vertices = first.Artifact.Body!.Topology.Vertices.Count(),
+ edges = first.Artifact.Body.Topology.Edges.Count(),
+ faces = first.Artifact.Body.Topology.Faces.Count(),
+ shells = first.Artifact.Body.Topology.Shells.Count(),
+});
+Write("cir-association.json", first.Artifact.Cir!);
+Write("determinism.json", new
+{
+ repeatedRuns = 2,
+ sameArtifactHash = first.Artifact.ArtifactHash == second.Artifact!.ArtifactHash,
+ sameStepText = first.Artifact.StepText == second.Artifact.StepText,
+ artifactHash = first.Artifact.ArtifactHash,
+ capability = first.Artifact.Capabilities.Single(),
+});
+Write("performance.json", new
+{
+ units = "milliseconds",
+ first = Timing(first),
+ warm = Timing(second),
+ note = "Developer-machine wall-clock evidence; not a benchmark or release gate.",
+});
+File.WriteAllText(Path.Combine(output, "sample-secret-coupon.step"), first.Artifact.StepText, new System.Text.UTF8Encoding(false));
+Console.WriteLine(JsonSerializer.Serialize(new { output, first.Artifact.ArtifactHash, first.IsSuccess }, json));
+
+object Timing(ForgeCompilationResult result) => new
+{
+ registration = result.RegistrationTime.TotalMilliseconds,
+ capabilityResolution = result.ResolutionTime.TotalMilliseconds,
+ templateInvocation = result.TemplateInvocationTime.TotalMilliseconds,
+ extensionLowering = result.ExtensionLoweringTime.TotalMilliseconds,
+ compilerAndValidation = result.CompilerLoweringTime.TotalMilliseconds,
+};
+
+void Write(string name, object value) => File.WriteAllText(Path.Combine(output, name), JsonSerializer.Serialize(value, json) + Environment.NewLine, new System.Text.UTF8Encoding(false));
+
+static string FindRepositoryRoot()
+{
+ var directory = new DirectoryInfo(AppContext.BaseDirectory);
+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;
+ return directory?.FullName ?? throw new DirectoryNotFoundException("Aetheris repository root not found.");
+}