Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Expose authoritative Forge template schemas
Yuechen Lif80eb713f78e
diff --git a/Aetheris.Forge.Host.Tests/ForgeProtocolV1Tests.cs b/Aetheris.Forge.Host.Tests/ForgeProtocolV1Tests.csnew file mode 100644index 00000000..470d4445--- /dev/null+++ b/Aetheris.Forge.Host.Tests/ForgeProtocolV1Tests.cs@@ -0,0 +1,142 @@+using System.Security.Cryptography;+using System.Text.Json;+using Aetheris.Forge.Host;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Forge.Host.Tests;++public sealed class ForgeProtocolV1Tests+{+ private const string Enclosure = "Standard.SheetMetal.ElectronicsEnclosure";++ [Fact]+ public void InfoListAndDescriptionAreStableAndDerivedFromFirmamentSchema()+ {+ var host = new ForgeProtocolHost();+ var info = host.GetHostInfo();+ Assert.Equal(1, info.ProtocolVersion);+ Assert.Equal(["ListTemplates", "DescribeTemplate", "InvokeTemplate"], info.Capabilities);++ var list = host.ListTemplates();+ Assert.Equal(list.Templates.OrderBy(item => item.Id, StringComparer.Ordinal), list.Templates);+ Assert.Contains(list.Templates, item => item.Id == Enclosure);+ Assert.DoesNotContain(list.Templates, item => item.Id.Contains("Aetheris.", StringComparison.Ordinal));++ var description = host.DescribeTemplate(Enclosure)!;+ var spec = Assert.Single(description.Parameters);+ Assert.Equal("record", spec.Type);+ Assert.Equal("mm", spec.Fields!.Single(item => item.Name == "Width").Unit);+ Assert.Equal(["Auto", "Rectangular", "Round"], spec.Fields!.Single(item => item.Name == "ReliefPolicy").AllowedValues);+ Assert.Equal([ForgeArtifactKind.StepAp242, ForgeArtifactKind.FlatStep, ForgeArtifactKind.Svg], description.Artifacts);+ }++ [Fact]+ public void RealEnclosureInvocationProducesDeterministicStepFlatStepAndSvg()+ {+ using var first = TempDirectory.Create();+ using var second = TempDirectory.Create();+ var host = new ForgeProtocolHost();+ var request = Request(ValidArguments(), ForgeArtifactKind.StepAp242, ForgeArtifactKind.FlatStep, ForgeArtifactKind.Svg);++ var a = host.InvokeTemplate(Enclosure, request, first.Path);+ var b = host.InvokeTemplate(Enclosure, request, second.Path);++ Assert.True(a.Success, string.Join(Environment.NewLine, a.Diagnostics.Select(item => item.Code + ": " + item.Message)));+ Assert.True(b.Success, string.Join(Environment.NewLine, b.Diagnostics.Select(item => item.Code + ": " + item.Message)));+ Assert.Equal(a.Identity.Specialization, b.Identity.Specialization);+ Assert.Equal(a.Artifacts.Select(item => (item.Kind, item.Sha256)), b.Artifacts.Select(item => (item.Kind, item.Sha256)));+ Assert.All(a.Artifacts, artifact =>+ {+ var bytes = File.ReadAllBytes(System.IO.Path.Combine(first.Path, artifact.Path));+ Assert.Equal(artifact.Size, bytes.LongLength);+ Assert.Equal(Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(), artifact.Sha256);+ Assert.False(System.IO.Path.IsPathRooted(artifact.Path));+ });+ Assert.True(Step242Importer.ImportBody(File.ReadAllText(System.IO.Path.Combine(first.Path, "part.step"))).IsSuccess);+ Assert.True(Step242Importer.ImportBody(File.ReadAllText(System.IO.Path.Combine(first.Path, "part.flat.step"))).IsSuccess);+ }++ [Theory]+ [MemberData(nameof(InvalidRequests))]+ public void InvalidInvocationsReturnCanonicalStructuredDiagnostics(+ string template, IReadOnlyDictionary<string, object?> arguments, string expectedCode)+ {+ using var output = TempDirectory.Create();+ var result = new ForgeProtocolHost().InvokeTemplate(template, Request(arguments, ForgeArtifactKind.StepAp242), output.Path);+ Assert.False(result.Success);+ Assert.Contains(result.Diagnostics, item => item.Code == expectedCode);+ Assert.Empty(result.Artifacts);+ }++ public static TheoryData<string, IReadOnlyDictionary<string, object?>, string> InvalidRequests() => new()+ {+ { "Standard.SheetMetal.DoesNotExist", ValidArguments(), "forge-host-template-not-found" },+ { Enclosure, Without("width"), "firmament-template-record-missing-field" },+ { Enclosure, With("mystery", "1 mm"), "firmament-template-record-extra-field" },+ { Enclosure, With("width", true), "forge-host-argument-transport-type" },+ { Enclosure, With("width", "12 kg"), "firmament-template-record-field-type-mismatch" },+ { Enclosure, With("lidLipHeight", "1 mm"), "firmament-template-require-failed" },+ };++ [Fact]+ public void ProtocolVersionAndUnsupportedArtifactAreRejectedBeforeExecution()+ {+ using var output = TempDirectory.Create();+ var host = new ForgeProtocolHost();+ var version = host.InvokeTemplate(Enclosure, new(99, Elements(ValidArguments()), null), output.Path);+ Assert.Contains(version.Diagnostics, item => item.Code == "forge-host-protocol-version-unsupported");++ var artifact = host.InvokeTemplate(Enclosure, new(1, Elements(ValidArguments()), [(ForgeArtifactKind)999]), output.Path);+ Assert.Contains(artifact.Diagnostics, item => item.Code == "forge-host-artifact-unsupported");+ }++ [Fact]+ public void ProcessCommandReadsStructuredStdinAndWritesOnlyStructuredStdout()+ {+ using var outputDirectory = TempDirectory.Create();+ var request = JsonSerializer.Serialize(Request(ValidArguments(), ForgeArtifactKind.StepAp242),+ ForgeProtocolJsonContext.Default.ForgeTemplateInvocationRequest);+ var stdout = new StringWriter();+ var exitCode = Program.Run(["invoke", Enclosure, "--request", "-", "--out", outputDirectory.Path],+ new StringReader(request), stdout);+ var response = JsonSerializer.Deserialize(stdout.ToString(), ForgeProtocolJsonContext.Default.ForgeTemplateInvocationResult);+ Assert.Equal(0, exitCode);+ Assert.True(response!.Success);+ Assert.True(File.Exists(System.IO.Path.Combine(outputDirectory.Path, "part.step")));+ }++ private static ForgeTemplateInvocationRequest Request(IReadOnlyDictionary<string, object?> values, params ForgeArtifactKind[] artifacts) =>+ new(1, Elements(values), artifacts);++ private static IReadOnlyDictionary<string, JsonElement> Elements(IReadOnlyDictionary<string, object?> values) =>+ values.ToDictionary(pair => pair.Key, pair => JsonSerializer.SerializeToElement(pair.Value), StringComparer.Ordinal);++ private static Dictionary<string, object?> ValidArguments() => new(StringComparer.Ordinal)+ {+ ["width"] = "120 mm", ["height"] = "40 mm", ["depth"] = "80 mm", ["thickness"] = "1.5 mm",+ ["lidLipHeight"] = "8 mm", ["insideRadius"] = "2 mm", ["kFactor"] = 0.42, ["reliefPolicy"] = "Rectangular",+ };++ private static Dictionary<string, object?> Without(string name)+ {+ var values = ValidArguments(); values.Remove(name); return values;+ }++ private static Dictionary<string, object?> With(string name, object? value)+ {+ var values = ValidArguments(); values[name] = value; return values;+ }++ private sealed class TempDirectory : IDisposable+ {+ private TempDirectory(string path) => Path = path;+ public string Path { get; }+ public static TempDirectory Create()+ {+ var path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "aetheris-forge-x1-" + Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(path);+ return new(path);+ }+ public void Dispose() { if (Directory.Exists(Path)) Directory.Delete(Path, true); }+ }+}diff --git a/Aetheris.Forge.Host/Aetheris.Forge.Host.csproj b/Aetheris.Forge.Host/Aetheris.Forge.Host.csprojindex 0a1c31d8..32b80681 100644--- a/Aetheris.Forge.Host/Aetheris.Forge.Host.csproj+++ b/Aetheris.Forge.Host/Aetheris.Forge.Host.csproj@@ -1,5 +1,6 @@<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup>+ <OutputType>Exe</OutputType><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable>@@ -11,5 +12,9 @@<ProjectReference Include="..\Aetheris.Continuum\Aetheris.Continuum.csproj" /><ProjectReference Include="..\Aetheris.FEA\Aetheris.FEA.csproj" /><ProjectReference Include="..\Aetheris.Modules.BuiltIn\Aetheris.Modules.BuiltIn.csproj" />+ <ProjectReference Include="..\Aetheris.SheetMetal\Aetheris.SheetMetal.csproj" />+ </ItemGroup>+ <ItemGroup>+ <InternalsVisibleTo Include="Aetheris.Forge.Host.Tests" /></ItemGroup></Project>diff --git a/Aetheris.Forge.Host/ForgeProtocolContracts.cs b/Aetheris.Forge.Host/ForgeProtocolContracts.csnew file mode 100644index 00000000..fb987db2--- /dev/null+++ b/Aetheris.Forge.Host/ForgeProtocolContracts.cs@@ -0,0 +1,98 @@+using System.Text.Json;+using System.Text.Json.Serialization;++namespace Aetheris.Forge.Host;++public static class ForgeHostProtocol+{+ public const int Version = 1;+ public const string Name = "Forge Host Protocol";+}++public enum ForgeProtocolDiagnosticSeverity { Info, Warning, Error }+public enum ForgeArtifactKind { StepAp242, FlatStep, Svg }++public sealed record ForgeHostInfo(+ int ProtocolVersion,+ string ProtocolName,+ string AetherisVersion,+ IReadOnlyList<string> Capabilities,+ string Concurrency);++public sealed record ForgeTemplateSummary(+ string Id,+ string DisplayName,+ string Version);++public sealed record ForgeTemplateListResponse(+ int ProtocolVersion,+ IReadOnlyList<ForgeTemplateSummary> Templates);++public sealed record ForgeTemplateParameterDescription(+ string Name,+ string Type,+ bool Required,+ string? Default,+ string? Dimension,+ string? Unit,+ IReadOnlyList<string>? AllowedValues,+ IReadOnlyList<ForgeTemplateParameterDescription>? Fields);++public sealed record ForgeTemplateDescription(+ int ProtocolVersion,+ string Id,+ string DisplayName,+ string Version,+ string Documentation,+ IReadOnlyList<ForgeTemplateParameterDescription> Parameters,+ IReadOnlyList<ForgeArtifactKind> Artifacts);++public sealed record ForgeTemplateInvocationRequest(+ int ProtocolVersion,+ IReadOnlyDictionary<string, JsonElement>? Arguments,+ IReadOnlyList<ForgeArtifactKind>? Artifacts);++public sealed record ForgeProtocolDiagnostic(+ string Code,+ ForgeProtocolDiagnosticSeverity Severity,+ string Message,+ string? Target = null,+ string? Source = null);++public sealed record ForgeArtifact(+ ForgeArtifactKind Kind,+ string Name,+ string ContentType,+ long Size,+ string Sha256,+ string Path);++public sealed record ForgeInvocationIdentity(+ int ProtocolVersion,+ string Template,+ string TemplateVersion,+ string AetherisVersion,+ string? Specialization);++public sealed record ForgeTemplateInvocationResult(+ bool Success,+ ForgeInvocationIdentity Identity,+ IReadOnlyList<ForgeProtocolDiagnostic> Diagnostics,+ IReadOnlyList<ForgeArtifact> Artifacts,+ double ExecutionMilliseconds);++public sealed record ForgeProtocolErrorResponse(+ int ProtocolVersion,+ IReadOnlyList<ForgeProtocolDiagnostic> Diagnostics);++[JsonSourceGenerationOptions(+ PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,+ WriteIndented = true,+ UseStringEnumConverter = true)]+[JsonSerializable(typeof(ForgeHostInfo))]+[JsonSerializable(typeof(ForgeTemplateListResponse))]+[JsonSerializable(typeof(ForgeTemplateDescription))]+[JsonSerializable(typeof(ForgeTemplateInvocationRequest))]+[JsonSerializable(typeof(ForgeTemplateInvocationResult))]+[JsonSerializable(typeof(ForgeProtocolErrorResponse))]+internal partial class ForgeProtocolJsonContext : JsonSerializerContext;diff --git a/Aetheris.Forge.Host/ForgeProtocolHost.cs b/Aetheris.Forge.Host/ForgeProtocolHost.csnew file mode 100644index 00000000..4cc3264e--- /dev/null+++ b/Aetheris.Forge.Host/ForgeProtocolHost.cs@@ -0,0 +1,363 @@+using System.Diagnostics;+using System.Globalization;+using System.Reflection;+using System.Security.Cryptography;+using System.Text;+using System.Text.Json;+using System.Text.RegularExpressions;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.SheetMetal;++namespace Aetheris.Forge.Host;++/// <summary>+/// Language-neutral, serialized invocation boundary over registered public Firmament Templates.+/// It intentionally exposes DTOs and artifacts, never compiler or geometry object graphs.+/// </summary>+public sealed class ForgeProtocolHost+{+ private static readonly UTF8Encoding Utf8 = new(false);+ private readonly object invocationGate = new();+ private readonly IReadOnlyDictionary<string, RegisteredTemplate> templates;++ public ForgeProtocolHost() : this(CreateStandardTemplates()) { }++ private ForgeProtocolHost(IEnumerable<RegisteredTemplate> templates)+ {+ this.templates = templates.OrderBy(item => item.Id, StringComparer.Ordinal)+ .ToDictionary(item => item.Id, StringComparer.Ordinal);+ }++ public ForgeHostInfo GetHostInfo() => new(+ ForgeHostProtocol.Version,+ ForgeHostProtocol.Name,+ AetherisVersion,+ ["ListTemplates", "DescribeTemplate", "InvokeTemplate"],+ "serialized-per-host-instance");++ public ForgeTemplateListResponse ListTemplates() => new(+ ForgeHostProtocol.Version,+ templates.Values.Select(item => new ForgeTemplateSummary(item.Id, item.DisplayName, item.Version)).ToArray());++ public ForgeTemplateDescription? DescribeTemplate(string templateId)+ {+ ArgumentException.ThrowIfNullOrWhiteSpace(templateId);+ if (!templates.TryGetValue(templateId, out var template)) return null;+ return new(+ ForgeHostProtocol.Version,+ template.Id,+ template.DisplayName,+ template.Version,+ template.Documentation,+ template.Metadata.Parameters.Select(parameter => DescribeParameter(template, parameter)).ToArray(),+ template.Artifacts);+ }++ public ForgeTemplateInvocationResult InvokeTemplate(+ string templateId,+ ForgeTemplateInvocationRequest request,+ string outputDirectory)+ {+ ArgumentException.ThrowIfNullOrWhiteSpace(templateId);+ ArgumentNullException.ThrowIfNull(request);+ ArgumentException.ThrowIfNullOrWhiteSpace(outputDirectory);+ var started = Stopwatch.GetTimestamp();+ var version = templates.TryGetValue(templateId, out var known) ? known.Version : string.Empty;+ ForgeTemplateInvocationResult Failure(params ForgeProtocolDiagnostic[] diagnostics) => new(+ false, Identity(templateId, version, null), diagnostics, [], Stopwatch.GetElapsedTime(started).TotalMilliseconds);++ if (request.ProtocolVersion != ForgeHostProtocol.Version)+ return Failure(Error("forge-host-protocol-version-unsupported",+ $"Protocol version {request.ProtocolVersion} is unsupported; this host accepts version {ForgeHostProtocol.Version}."));+ if (known is null)+ return Failure(Error("forge-host-template-not-found", $"Public template '{templateId}' was not found.", templateId));++ lock (invocationGate)+ {+ var requestedArtifacts = (request.Artifacts is null || request.Artifacts.Count == 0+ ? new[] { ForgeArtifactKind.StepAp242 }+ : request.Artifacts.Distinct().ToArray())+ .OrderBy(item => item).ToArray();+ var unsupported = requestedArtifacts.Except(known.Artifacts).ToArray();+ if (unsupported.Length > 0)+ return Failure(unsupported.Select(item => Error("forge-host-artifact-unsupported",+ $"Template '{templateId}' does not declare artifact '{item}'.", item.ToString())).ToArray());++ var diagnostics = new List<ForgeProtocolDiagnostic>();+ var hostArguments = BindArguments(known, request.Arguments ?? new Dictionary<string, JsonElement>(), diagnostics);+ if (diagnostics.Any(item => item.Severity == ForgeProtocolDiagnosticSeverity.Error))+ return Failure(diagnostics.ToArray());++ var expansion = FirmamentTemplateHostBridge.Expand(+ known.Source, known.Metadata.Name, "InteropPart", hostArguments, out var bindingDiagnostics);+ diagnostics.AddRange(bindingDiagnostics.Select(FromFirmamentDiagnostic));+ if (expansion is null || diagnostics.Any(item => item.Severity == ForgeProtocolDiagnosticSeverity.Error))+ return Failure(diagnostics.ToArray());++ var compilation = SheetMetalFirmament.Compile(expansion.ExpandedSource, $"forge-host:{known.Id}");+ diagnostics.AddRange(compilation.Diagnostics.Select(FromSheetMetalDiagnostic));+ if (!compilation.IsSuccess || compilation.Part?.FormedBody is null || compilation.FlatPattern is null)+ return Failure(diagnostics.ToArray());++ var dfm = SheetMetalDfm.Evaluate(compilation.Part, compilation.FlatPattern);+ diagnostics.AddRange(dfm.Findings.Where(item => item.Status is SheetMetalDfmStatus.Warning or SheetMetalDfmStatus.Fail)+ .Select(item => new ForgeProtocolDiagnostic(item.RuleId,+ item.Status == SheetMetalDfmStatus.Fail ? ForgeProtocolDiagnosticSeverity.Error : ForgeProtocolDiagnosticSeverity.Warning,+ item.Message, item.SubjectId, "SheetMetalDfm")));+ if (diagnostics.Any(item => item.Severity == ForgeProtocolDiagnosticSeverity.Error))+ return Failure(diagnostics.ToArray());++ try+ {+ var root = Path.GetFullPath(outputDirectory);+ Directory.CreateDirectory(root);+ var artifacts = new List<ForgeArtifact>();+ foreach (var kind in requestedArtifacts)+ {+ var (name, contentType, content) = GenerateArtifact(kind, compilation);+ var path = Path.Combine(root, name);+ var resolved = Path.GetFullPath(path);+ if (!string.Equals(Path.GetDirectoryName(resolved), root, StringComparison.OrdinalIgnoreCase))+ throw new InvalidOperationException("Generated artifact path escaped the requested output directory.");+ var bytes = Utf8.GetBytes(content);+ File.WriteAllBytes(resolved, bytes);+ artifacts.Add(new(kind, name, contentType, bytes.LongLength,+ Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(), name));+ }+ return new(true, Identity(templateId, known.Version, expansion.SpecializationIdentity),+ diagnostics, artifacts, Stopwatch.GetElapsedTime(started).TotalMilliseconds);+ }+ catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)+ {+ diagnostics.Add(Error("forge-host-artifact-write-failed", exception.Message, outputDirectory));+ return Failure(diagnostics.ToArray());+ }+ catch (InvalidOperationException exception)+ {+ diagnostics.Add(Error("forge-host-artifact-generation-failed", exception.Message, templateId, "AetherisLowering"));+ return Failure(diagnostics.ToArray());+ }+ }+ }++ private static IReadOnlyList<RegisteredTemplate> CreateStandardTemplates()+ {+ var source = SheetMetalTemplateLibrary.Source;+ var module = FirmamentTemplateHostBridge.InspectModule(source, out var diagnostics);+ if (diagnostics.Count > 0)+ throw new InvalidOperationException("Standard Firmament template catalog is invalid: " + string.Join("; ", diagnostics));+ var version = "1+" + Convert.ToHexString(SHA256.HashData(Utf8.GetBytes(source)))[..12].ToLowerInvariant();+ return module.Templates.Where(item => string.Equals(item.TargetKind, "SheetMetal", StringComparison.Ordinal))+ .Select(item => new RegisteredTemplate(+ "Standard.SheetMetal." + item.Name,+ Humanize(item.Name),+ version,+ $"Standard production Firmament Sheet Metal template '{item.Name}'. Its schema is derived from the embedded authoritative module.",+ source,+ item,+ module.Records.ToDictionary(record => record.Name, StringComparer.Ordinal),+ module.Enums.ToDictionary(value => value.Name, StringComparer.Ordinal),+ [ForgeArtifactKind.StepAp242, ForgeArtifactKind.FlatStep, ForgeArtifactKind.Svg]))+ .ToArray();+ }++ private static ForgeTemplateParameterDescription DescribeParameter(RegisteredTemplate template, FirmamentTemplateParameterMetadata parameter)+ {+ var fields = template.Records.TryGetValue(parameter.TypeName, out var record)+ ? record.Fields.Select(field => DescribeValue(template, field.Name, field.TypeName, true, null)).ToArray()+ : null;+ return DescribeValue(template, parameter.Name, parameter.TypeName, parameter.DefaultExpression is null,+ parameter.DefaultExpression, fields);+ }++ private static ForgeTemplateParameterDescription DescribeValue(RegisteredTemplate template, string name, string type,+ bool required, string? defaultValue, IReadOnlyList<ForgeTemplateParameterDescription>? fields = null)+ {+ var dimension = type switch { "Length" => "length", "Angle" => "angle", _ => null };+ var unit = type switch { "Length" => "mm", "Angle" => "deg", _ => null };+ var allowed = template.Enums.TryGetValue(type, out var enumeration) ? enumeration.Cases : null;+ return new(name, PublicType(type, fields is not null), required, defaultValue, dimension, unit, allowed, fields);+ }++ private static IReadOnlyDictionary<string, FirmamentHostArgument> BindArguments(+ RegisteredTemplate template,+ IReadOnlyDictionary<string, JsonElement> supplied,+ ICollection<ForgeProtocolDiagnostic> diagnostics)+ {+ var result = new Dictionary<string, FirmamentHostArgument>(StringComparer.Ordinal);+ var parameters = template.Metadata.Parameters;+ FirmamentTemplateRecordMetadata? onlyRecord = null;+ var projectedRecord = parameters.Count == 1 && template.Records.TryGetValue(parameters[0].TypeName, out onlyRecord);+ if (projectedRecord && !TryGet(supplied, parameters[0].Name, out _))+ {+ BindRecordFields(parameters[0].Name, parameters[0].TypeName, onlyRecord!, supplied, result, template, diagnostics);+ return result;+ }++ foreach (var pair in supplied)+ {+ var parameter = parameters.FirstOrDefault(item => string.Equals(item.Name, pair.Key, StringComparison.OrdinalIgnoreCase));+ if (parameter is null)+ {+ result[pair.Key] = new(pair.Value.GetRawText());+ continue;+ }+ if (template.Records.TryGetValue(parameter.TypeName, out var record))+ BindRecord(parameter.Name, parameter.TypeName, record, pair.Value, result, template, diagnostics);+ else if (TryLiteral(parameter.TypeName, pair.Value, template, out var literal, out var message))+ result[parameter.Name] = new(literal);+ else diagnostics.Add(Error("forge-host-argument-transport-type", message, parameter.Name));+ }+ return result;+ }++ private static void BindRecord(string parameterName, string recordType, FirmamentTemplateRecordMetadata record,+ JsonElement value, IDictionary<string, FirmamentHostArgument> result, RegisteredTemplate template,+ ICollection<ForgeProtocolDiagnostic> diagnostics)+ {+ if (value.ValueKind != JsonValueKind.Object)+ {+ diagnostics.Add(Error("forge-host-argument-transport-type",+ $"Parameter '{parameterName}' expects a JSON object for Firmament Record '{recordType}'.", parameterName));+ return;+ }+ var fields = new Dictionary<string, string>(StringComparer.Ordinal);+ BindRecordFields(parameterName, recordType, record,+ value.EnumerateObject().ToDictionary(property => property.Name, property => property.Value, StringComparer.Ordinal),+ result, template, diagnostics);+ }++ private static void BindRecordFields(string parameterName, string recordType, FirmamentTemplateRecordMetadata record,+ IEnumerable<KeyValuePair<string, JsonElement>> values, IDictionary<string, FirmamentHostArgument> result,+ RegisteredTemplate template, ICollection<ForgeProtocolDiagnostic> diagnostics)+ {+ var fields = new Dictionary<string, string>(StringComparer.Ordinal);+ foreach (var property in values)+ {+ var field = record.Fields.FirstOrDefault(item => string.Equals(item.Name, property.Key, StringComparison.OrdinalIgnoreCase));+ if (field is null)+ {+ fields[property.Key] = property.Value.GetRawText();+ continue;+ }+ if (TryLiteral(field.TypeName, property.Value, template, out var literal, out var message)) fields[field.Name] = literal;+ else diagnostics.Add(Error("forge-host-argument-transport-type", message, parameterName + "." + field.Name));+ }+ result[parameterName] = new(string.Empty, recordType, fields);+ }++ private static bool TryLiteral(string type, JsonElement value, RegisteredTemplate template, out string literal, out string message)+ {+ literal = string.Empty;+ message = string.Empty;+ switch (type)+ {+ case "Length": case "Angle":+ if (value.ValueKind == JsonValueKind.String)+ {+ literal = Regex.Replace(value.GetString()!.Trim(), @"(?<=\d)\s+(?=[A-Za-z])", string.Empty,+ RegexOptions.CultureInvariant);+ return true;+ }+ break;+ case "int":+ if (value.ValueKind == JsonValueKind.Number && value.TryGetInt64(out _)) { literal = value.GetRawText(); return true; }+ break;+ case "float":+ if (value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var number) && double.IsFinite(number))+ { literal = number.ToString("R", CultureInfo.InvariantCulture); return true; }+ break;+ case "bool":+ if (value.ValueKind is JsonValueKind.True or JsonValueKind.False) { literal = value.GetBoolean() ? "true" : "false"; return true; }+ break;+ case "String":+ if (value.ValueKind == JsonValueKind.String) { literal = value.GetRawText(); return true; }+ break;+ default:+ if (template.Enums.ContainsKey(type) && value.ValueKind == JsonValueKind.String)+ { literal = value.GetString()!; return true; }+ if (value.ValueKind == JsonValueKind.String) { literal = value.GetString()!; return true; }+ break;+ }+ message = $"Firmament value of type '{type}' has incompatible JSON kind '{value.ValueKind}'.";+ return false;+ }++ private static (string Name, string ContentType, string Content) GenerateArtifact(ForgeArtifactKind kind, SheetMetalAuthoringResult result)+ {+ if (kind == ForgeArtifactKind.StepAp242)+ {+ var exported = Step242Exporter.ExportBody(result.Part!.FormedBody!, new Step242ExportOptions { ProductName = "InteropPart" });+ if (!exported.IsSuccess) throw new InvalidOperationException("STEP AP242 export failed: " + string.Join("; ", exported.Diagnostics.Select(item => item.Message)));+ return ("part.step", "model/step", exported.Value);+ }+ if (kind == ForgeArtifactKind.FlatStep)+ {+ var flat = SheetMetalManufacturingArtifacts.BuildFlatBody(result.Part!, result.FlatPattern!);+ if (!flat.IsSuccess || flat.Body is null) throw new InvalidOperationException("Flat STEP lowering failed: " + string.Join("; ", flat.Diagnostics.Select(item => item.Message)));+ var exported = Step242Exporter.ExportBody(flat.Body, new Step242ExportOptions { ProductName = "InteropPart flat pattern" });+ if (!exported.IsSuccess) throw new InvalidOperationException("Flat STEP export failed: " + string.Join("; ", exported.Diagnostics.Select(item => item.Message)));+ return ("part.flat.step", "model/step", exported.Value);+ }+ if (kind == ForgeArtifactKind.Svg)+ return ("part.flat.svg", "image/svg+xml", SheetMetalSvgRenderer.Render(result.FlatPattern!));+ throw new InvalidOperationException($"Artifact kind '{kind}' has no generator.");+ }++ private static ForgeProtocolDiagnostic FromFirmamentDiagnostic(string value)+ {+ var parts = value.Split(':', 3);+ return Error(parts[0], value, parts.Length > 1 ? parts[1] : null, "FirmamentBinder");+ }++ private static ForgeProtocolDiagnostic FromSheetMetalDiagnostic(SheetMetalDiagnostic value) => new(+ value.Code,+ value.Severity switch+ {+ SheetMetalDiagnosticSeverity.Information => ForgeProtocolDiagnosticSeverity.Info,+ SheetMetalDiagnosticSeverity.Warning => ForgeProtocolDiagnosticSeverity.Warning,+ _ => ForgeProtocolDiagnosticSeverity.Error,+ },+ value.Message,+ value.SourceFaceIds is null ? null : string.Join(",", value.SourceFaceIds),+ "SheetMetalLowering");++ private static ForgeProtocolDiagnostic Error(string code, string message, string? target = null, string? source = null) =>+ new(code, ForgeProtocolDiagnosticSeverity.Error, message, target, source);++ private static ForgeInvocationIdentity Identity(string template, string version, string? specialization) =>+ new(ForgeHostProtocol.Version, template, version, AetherisVersion, specialization);++ private static bool TryGet(IReadOnlyDictionary<string, JsonElement> values, string name, out JsonElement value)+ {+ foreach (var pair in values)+ if (string.Equals(pair.Key, name, StringComparison.OrdinalIgnoreCase)) { value = pair.Value; return true; }+ value = default;+ return false;+ }++ private static string PublicType(string type, bool record) => type switch+ {+ "int" => "integer", "float" => "number", "bool" => "boolean", "String" => "string",+ _ when record => "record", _ => type,+ };++ private static string Humanize(string value) => Regex.Replace(value, "(?<=[a-z0-9])(?=[A-Z])", " ", RegexOptions.CultureInvariant);++ private static string AetherisVersion =>+ typeof(ForgeProtocolHost).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion+ ?? typeof(ForgeProtocolHost).Assembly.GetName().Version?.ToString()+ ?? "unknown";++ private sealed record RegisteredTemplate(+ string Id,+ string DisplayName,+ string Version,+ string Documentation,+ string Source,+ FirmamentTemplateMetadata Metadata,+ IReadOnlyDictionary<string, FirmamentTemplateRecordMetadata> Records,+ IReadOnlyDictionary<string, FirmamentTemplateEnumMetadata> Enums,+ IReadOnlyList<ForgeArtifactKind> Artifacts);+}diff --git a/Aetheris.Forge.Host/Program.cs b/Aetheris.Forge.Host/Program.csnew file mode 100644index 00000000..80c084e0--- /dev/null+++ b/Aetheris.Forge.Host/Program.cs@@ -0,0 +1,72 @@+using System.Text.Json;+using System.Text.Json.Serialization.Metadata;++namespace Aetheris.Forge.Host;++public static class Program+{+ public static int Main(string[] args) => Run(args, Console.In, Console.Out);++ internal static int Run(string[] args, TextReader input, TextWriter output)+ {+ var host = new ForgeProtocolHost();+ try+ {+ if (args.Length == 1 && args[0] == "info")+ return Write(output, host.GetHostInfo(), ForgeProtocolJsonContext.Default.ForgeHostInfo);+ if (args.Length == 1 && args[0] == "list")+ return Write(output, host.ListTemplates(), ForgeProtocolJsonContext.Default.ForgeTemplateListResponse);+ if (args.Length == 2 && args[0] == "describe")+ {+ var description = host.DescribeTemplate(args[1]);+ if (description is not null)+ return Write(output, description, ForgeProtocolJsonContext.Default.ForgeTemplateDescription);+ return WriteError(output, "forge-host-template-not-found", $"Public template '{args[1]}' was not found.", 3);+ }+ if (args.Length >= 2 && args[0] == "invoke")+ {+ var requestPath = Option(args, "--request");+ var outputDirectory = Option(args, "--out");+ if (outputDirectory is null)+ return WriteError(output, "forge-host-output-directory-required", "Invoke requires --out <directory>.", 2);+ var json = requestPath is null || requestPath == "-" ? input.ReadToEnd() : File.ReadAllText(requestPath);+ var request = JsonSerializer.Deserialize(json, ForgeProtocolJsonContext.Default.ForgeTemplateInvocationRequest);+ if (request is null)+ return WriteError(output, "forge-host-request-invalid", "Invocation request was empty.", 2);+ var result = host.InvokeTemplate(args[1], request, outputDirectory);+ Write(output, result, ForgeProtocolJsonContext.Default.ForgeTemplateInvocationResult);+ return result.Success ? 0 : 4;+ }+ return WriteError(output, "forge-host-command-invalid",+ "Usage: forge-host info | list | describe <template-id> | invoke <template-id> [--request <json|->] --out <directory>", 2);+ }+ catch (JsonException exception)+ {+ return WriteError(output, "forge-host-request-json-invalid", exception.Message, 2);+ }+ catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException)+ {+ return WriteError(output, "forge-host-request-read-failed", exception.Message, 2);+ }+ }++ private static string? Option(string[] args, string name)+ {+ var index = Array.IndexOf(args, name);+ return index >= 0 && index + 1 < args.Length ? args[index + 1] : null;+ }++ private static int Write<T>(TextWriter output, T value, JsonTypeInfo<T> typeInfo)+ {+ output.WriteLine(JsonSerializer.Serialize(value, typeInfo));+ return 0;+ }++ private static int WriteError(TextWriter output, string code, string message, int exitCode)+ {+ var response = new ForgeProtocolErrorResponse(ForgeHostProtocol.Version,+ [new(code, ForgeProtocolDiagnosticSeverity.Error, message)]);+ Write(output, response, ForgeProtocolJsonContext.Default.ForgeProtocolErrorResponse);+ return exitCode;+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.csindex 7c66e69f..5d94b230 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentTemplateHostBridge.cs@@ -13,6 +13,24 @@ public sealed record FirmamentTemplateParameterMetadata(string? DefaultExpression,string? ConstraintConcept);+public sealed record FirmamentTemplateRecordFieldMetadata(+ string Name,+ string TypeName);++public sealed record FirmamentTemplateRecordMetadata(+ string Name,+ IReadOnlyList<FirmamentTemplateRecordFieldMetadata> Fields);++public sealed record FirmamentTemplateEnumMetadata(+ string Name,+ IReadOnlyList<string> Cases);++/// <summary>Authoritative public Template schema extracted from Firmament binder IR.</summary>+public sealed record FirmamentTemplateModuleMetadata(+ IReadOnlyList<FirmamentTemplateMetadata> Templates,+ IReadOnlyList<FirmamentTemplateRecordMetadata> Records,+ IReadOnlyList<FirmamentTemplateEnumMetadata> Enums);+public enum FirmamentTemplateParameterKind{Value = 1,@@ -67,6 +85,15 @@ public static class FirmamentTemplateHostBridgepublic static IReadOnlyList<FirmamentTemplateMetadata> Inspect(string moduleSource,out IReadOnlyList<string> diagnostics)+ => InspectModule(moduleSource, out diagnostics).Templates;++ /// <summary>+ /// Inspects templates and their referenced Record/Enum definitions through the same parser+ /// used by host binding. Interop callers therefore never need to parse Firmament source.+ /// </summary>+ public static FirmamentTemplateModuleMetadata InspectModule(+ string moduleSource,+ out IReadOnlyList<string> diagnostics){ArgumentNullException.ThrowIfNull(moduleSource);var collected = new List<string>();@@ -81,8 +108,15 @@ public static class FirmamentTemplateHostBridgeparameter.DefaultExpression,parameter.ConstraintConcept)).ToArray())).ToArray();+ var records = FirmamentV2TemplateExpansion.InspectRecords(moduleSource, collected)+ .Select(record => new FirmamentTemplateRecordMetadata(record.Name,+ record.Fields.Select(field => new FirmamentTemplateRecordFieldMetadata(field.Key, field.Value)).ToArray()))+ .ToArray();+ var enums = FirmamentV2TemplateExpansion.InspectEnums(moduleSource)+ .Select(item => new FirmamentTemplateEnumMetadata(item.Key, item.Value.ToArray()))+ .ToArray();diagnostics = collected.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray();- return templates;+ return new(templates, records, enums);}public static FirmamentHostTemplateExpansion? Expand(diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.csindex 315d5549..2ea0ed18 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs@@ -45,6 +45,9 @@ internal static class FirmamentV2TemplateExpansioninternal const string WrongRecordType = Prefix + "record-argument-type-mismatch";internal const string RecordCollectionMismatch = Prefix + "record-collection-scalar-mismatch";internal const string UnknownRecordMember = Prefix + "unknown-record-member";+ internal const string RecordMissingField = Prefix + "record-missing-field";+ internal const string RecordExtraField = Prefix + "record-extra-field";+ internal const string RecordFieldTypeMismatch = Prefix + "record-field-type-mismatch";internal const string MaterializedRecordArgument = Prefix + "materialized-value-not-compile-time-record";internal const string UnsupportedRecordValue = Prefix + "unsupported-record-value-form";internal const string WithBaseNotRecord = Prefix + "with-base-not-record";@@ -82,6 +85,8 @@ internal static class FirmamentV2TemplateExpansionstring TargetKind,IReadOnlyList<HostParameter> Parameters);+ internal sealed record HostRecord(string Name, IReadOnlyDictionary<string, string> Fields);+internal static IReadOnlyList<HostTemplate> Inspect(string source, List<string> diagnostics) =>ParseDeclarations(source, diagnostics).Select(template => new HostTemplate(@@ -96,6 +101,20 @@ internal static class FirmamentV2TemplateExpansion.OrderBy(template => template.Name, StringComparer.Ordinal).ToArray();+ internal static IReadOnlyList<HostRecord> InspectRecords(string source, List<string> diagnostics) =>+ ParseRecordTypes(source, diagnostics).Values+ .OrderBy(record => record.Name, StringComparer.Ordinal)+ .Select(record => new HostRecord(record.Name,+ record.Fields.OrderBy(field => field.Key, StringComparer.Ordinal)+ .ToDictionary(field => field.Key, field => field.Value, StringComparer.Ordinal)))+ .ToArray();++ internal static IReadOnlyDictionary<string, IReadOnlyList<string>> InspectEnums(string source) =>+ ParseEnums(source).OrderBy(item => item.Key, StringComparer.Ordinal)+ .ToDictionary(item => item.Key,+ item => (IReadOnlyList<string>)item.Value.OrderBy(value => value, StringComparer.Ordinal).ToArray(),+ StringComparer.Ordinal);+/// <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@@ -139,6 +158,12 @@ internal static class FirmamentV2TemplateExpansion{var recordName = $"__forge_{instanceName}_{pair.Key}";var recordType = pair.Value.RecordType ?? string.Empty;+ if (!recordTypes.TryGetValue(recordType, out var recordDefinition))+ {+ diagnostics.Add(UnknownRecordType + $":{pair.Key}:{recordType}");+ continue;+ }+ ValidateSyntheticRecord(recordName, recordDefinition, pair.Value.RecordFields, string.Empty);staticRecords[recordName] = new TemplateStaticRecordIr(recordName,recordType,@@ -149,6 +174,7 @@ internal static class FirmamentV2TemplateExpansion}arguments.Add(new TemplateArgumentIr(pair.Key, expression, new FirmamentV2SourceSpan(source.Length, 0)));}+ if (HasErrors(diagnostics)) return null;var application = new TemplateApplicationIr(template.TargetKind,@@ -206,6 +232,33 @@ internal static class FirmamentV2TemplateExpansionforeach (var change in changes)source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);return HasErrors(diagnostics) ? null : new Result(source, [instantiation]);++ void ValidateSyntheticRecord(string recordName, TemplateRecordTypeIr definition,+ IReadOnlyDictionary<string, string> fields, string prefix)+ {+ foreach (var expected in definition.Fields)+ {+ var path = prefix + expected.Key;+ if (!fields.TryGetValue(path, out var value))+ {+ diagnostics.Add(RecordMissingField + ":" + recordName + ":" + path);+ continue;+ }+ if (recordTypes.TryGetValue(expected.Value, out var nested))+ {+ if (!string.Equals(value, expected.Value, StringComparison.Ordinal))+ diagnostics.Add(RecordFieldTypeMismatch + $":{recordName}.{path}:expected-{expected.Value}:actual-{value}");+ else ValidateSyntheticRecord(recordName, nested, fields, path + ".");+ }+ else if (!TypeMatches(value, expected.Value, enums, recordTypes, staticRecords))+ diagnostics.Add(RecordFieldTypeMismatch + $":{recordName}.{path}:expected-{expected.Value}:actual-{value}");+ }+ var admitted = definition.Fields.Keys.Select(field => prefix + field).ToArray();+ foreach (var extra in fields.Keys.Where(field => field.StartsWith(prefix, StringComparison.Ordinal)+ && !admitted.Contains(field, StringComparer.Ordinal)+ && !admitted.Any(candidate => field.StartsWith(candidate + ".", StringComparison.Ordinal))))+ diagnostics.Add(RecordExtraField + ":" + recordName + ":" + extra);+ }}public static Result? Expand(string source, List<string> diagnostics)@@ -471,10 +524,10 @@ internal static class FirmamentV2TemplateExpansionif (close < 0 || !recordTypes.TryGetValue(typeName, out var recordType)) continue;if (!string.Equals(typeName, literalType, StringComparison.Ordinal)) { diagnostics.Add(WrongRecordType + $":{name}:expected-{typeName}:actual-{literalType}"); continue; }var fields = ParseRecordFields(source[(open + 1)..close]);- foreach (var missing in recordType.Fields.Keys.Where(field => !fields.ContainsKey(field))) diagnostics.Add(Prefix + "record-missing-field:" + name + ":" + missing);- foreach (var extra in fields.Keys.Where(field => !recordType.Fields.ContainsKey(field))) diagnostics.Add(Prefix + "record-extra-field:" + name + ":" + extra);+ foreach (var missing in recordType.Fields.Keys.Where(field => !fields.ContainsKey(field))) diagnostics.Add(RecordMissingField + ":" + name + ":" + missing);+ foreach (var extra in fields.Keys.Where(field => !recordType.Fields.ContainsKey(field))) diagnostics.Add(RecordExtraField + ":" + name + ":" + extra);foreach (var field in fields.Where(field => recordType.Fields.TryGetValue(field.Key, out var expected) && !recordTypes.ContainsKey(expected) && !TypeMatches(field.Value, expected, enums, recordTypes, result)))- diagnostics.Add(Prefix + "record-field-type-mismatch:" + name + "." + field.Key + ":expected-" + recordType.Fields[field.Key] + ":actual-" + field.Value);+ diagnostics.Add(RecordFieldTypeMismatch + ":" + name + "." + field.Key + ":expected-" + recordType.Fields[field.Key] + ":actual-" + field.Value);result[name] = new(name, typeName, fields.ToImmutableDictionary(StringComparer.Ordinal), new(header.Index, close - header.Index + 1));}foreach (Match declaration in Regex.Matches(source, @"\bStatic\s+(?<name>[A-Za-z_]\w*)\s*(?::\s*(?<type>[A-Za-z_]\w*))?\s*=\s*(?<table>[A-Za-z_]\w*)\s*\[\s*(?<lookup>[^\]]+)\s*\]", RegexOptions.CultureInvariant))diff --git a/docs/forge/forge-interop-x1.md b/docs/forge/forge-interop-x1.mdnew file mode 100644index 00000000..f3b2d1da--- /dev/null+++ b/docs/forge/forge-interop-x1.md@@ -0,0 +1,60 @@+# FORGE-INTEROP-X1 report++FORGE-INTEROP-X1 establishes the process-oriented Forge Host Protocol v1 as Aetheris' first stable language-neutral template boundary. Aetheris remains entirely .NET; the four dogfood clients contain process and JSON plumbing only.++```text+foreign caller+ -> explicit protocol v1 DTO+ -> ForgeProtocolHost public catalog+ -> authoritative Firmament module metadata and Template resolver+ -> real Firmament typed Record/value binder and Require evaluation+ -> real SheetMetal Firmament compiler and Aetheris lowering+ -> formed STEP AP242 / flat STEP / SVG+ -> relative artifact manifest, SHA-256 hashes, structured diagnostics+```++`Aetheris.Forge.Host` remains the single host project. It is now both the same referenceable `Aetheris.Forge.Host` C# assembly and an executable process entry point. Its assembly identity and existing native `ForgeHost -> ForgeModule -> ForgeTemplate -> ForgeInvocation` API are unchanged, and its existing tests still execute directly. The interop host adds explicit wire DTOs rather than serializing `ForgeCompilationResult`, BRep bodies, or other managed domain objects.++## Production witness++The witness is the embedded production Firmament template `Standard.SheetMetal.ElectronicsEnclosure`, not a synthetic box. The request is [`samples/forge-interop-x1/request.json`](../../samples/forge-interop-x1/request.json): 120 × 80 × 40 mm, 1.5 mm sheet, 2 mm inside radius, 8 mm lip, K-factor 0.42, and rectangular relief.++The real specialization identity was `template:94546352d5d67afa`. It produced no diagnostics and these canonical artifacts in the validation run:++| Artifact | Bytes | SHA-256 |+|---|---:|---|+| formed STEP AP242 | 52,386 | `114cd7c0c6a8a364b2943cc955a12d8a96b576a187dfc1957ea9f769296872be` |+| flat STEP | 59,019 | `88c437373fe4fdf91e8f0a5b5e0e5c135b290f0dfe18449ec3ee7c0970c1d075` |+| flat SVG | 4,630 | `1657e3bbc3ef418617b45c5d9ab76a96d70b0ba6356c0e88a7ba07edc18b6519` |++Execution was approximately 335 ms in the first Debug smoke run; timing is observational and is intentionally excluded from artifact identity. The formed and flat STEP artifacts reimport through the Aetheris AP242 importer and pass `Aetheris.CLI inspect`.++Python 3.10, Go, Rust 1.95, and Node 26 executing the TypeScript client each invoked the same host and produced byte-identical hashes for all three artifacts. Run the complete witness with:++```powershell+./scripts/test-forge-interop-x1.ps1+```++The clients live under [`samples/forge-interop-x1`](../../samples/forge-interop-x1). Each reads the same request, starts the Forge Host executable, parses success and artifact paths, and checks that files exist. None parses units, applies defaults, knows sheet-metal geometry, or duplicates Firmament logic.++## Protocol and NativeAOT decision++The complete contract is [Forge Host Protocol v1](protocol-v1.md). A process protocol was selected because it is immediately usable from shell, CI, Python, Go, Rust, C++, TypeScript/Node, and Java with no ABI-specific ownership model. JSON uses explicit DTOs and a source-generated `JsonSerializerContext`; no CLR polymorphic type metadata is enabled.++A Windows x64 NativeAOT publish completes and the native executable handles `info` and a production invocation. The publish reports pre-existing trim/AOT warnings in transitive subsystems that are outside this narrow execution path; the protocol's own serializer path uses source-generated metadata. A C ABI was deliberately deferred: it would add opaque-handle, buffer-allocation, lifetime, and export-versioning commitments without improving the X1 interoperability proof. The process boundary is the v1 product.++## Validation coverage++`ForgeProtocolV1Tests` covers host info, deterministic template ordering, authoritative introspection, valid production invocation, missing field, unknown field, wrong JSON type, wrong unit, unknown template, semantic `Require` failure, unsupported artifact, protocol-version rejection, deterministic rerun, artifact byte/hash agreement, STEP reimport, and structured-stdin/stdout command execution.++The X1 work also closed a binder inconsistency: synthetic host Record values now receive the same missing/extra/type field validation as source-authored Static Records before `Require` evaluation. This is why an interop wrong-unit error now belongs to the canonical Firmament Record diagnostic family instead of degrading into a later expression error.++## Limitations++- The v1 public catalog currently exposes the five embedded standard Sheet Metal product-family templates. Package/plugin template federation and arbitrary module discovery are not protocol capabilities.+- Public execution currently supports the parameter categories exercised by those templates: Length, Angle, integer, number, boolean, string, enum, and nested Record values. Material references, imported STEP resources, type parameters, collections, dates, versions, and profile paths are not yet exposed through this protocol even where native Firmament has related concepts.+- Declared artifact kinds are formed STEP AP242, flat STEP, and SVG. A template returns only requested kinds it declares; DXF and reports are not v1 artifact promises.+- Invocation is serialized per host instance. Thread-safe parallel in-process invocation is not claimed.+- NativeAOT process publishing is validated on `win-x64`; broader RID publication is not claimed by this milestone. There is no C ABI.+- Artifact filenames are host-selected and the manifest paths are relative to the caller-selected output directory. Inline base64 artifact transport and network transport are not supported.+- Protocol v1 stabilizes the boundary shape and semantics, not the membership of the public template catalog. New public templates and artifact kinds may be added compatibly.diff --git a/docs/forge/invocation-sdk.md b/docs/forge/invocation-sdk.mdindex be36d79b..8d932c9d 100644--- a/docs/forge/invocation-sdk.md+++ b/docs/forge/invocation-sdk.md@@ -1,5 +1,7 @@# Forge Host invocation API+Native C# remains the direct, first-class invocation path described here. Foreign-language callers use the deliberately smaller [Forge Host Protocol v1](protocol-v1.md), which resolves the same authoritative Firmament Template definitions without exposing managed object graphs or requiring C# callers to round-trip through JSON.+`Aetheris.Forge.Host` exposes the host workflow `ForgeHost -> ForgeModule -> ForgeTemplate -> ForgeInvocation -> ForgeCompilationResult`.## Typed Template invocationdiff --git a/docs/forge/protocol-v1.md b/docs/forge/protocol-v1.mdnew file mode 100644index 00000000..a241b022--- /dev/null+++ b/docs/forge/protocol-v1.md@@ -0,0 +1,94 @@+# Forge Host Protocol v1++Forge Host Protocol v1 is the stable language-neutral process boundary for public Firmament Templates. It has four discovery/invocation commands and deliberately exposes no AIR, CIR, BRep, parser, solver, EF Core, CLR type, or extension-loading surface.++```text+Aetheris.Forge.Host info+Aetheris.Forge.Host list+Aetheris.Forge.Host describe <template-id>+Aetheris.Forge.Host invoke <template-id> [--request <file|->] --out <directory>+```++Standard output is exactly one JSON document. `invoke` reads UTF-8 JSON from the named file or standard input when `--request` is absent or `-`. Human-readable progress is not written to standard output. Successful commands return exit code `0`; command/request errors return `2`, missing templates return `3`, and invocation failures return `4`.++## Identity and discovery++`info` returns the independent protocol version, Aetheris implementation version, capabilities, and concurrency policy. Protocol v1 is not coupled to an AIR, CIR, BRep, parser, or CLR schema version.++`list` returns public templates in ordinal template-ID order. The built-in IDs use semantic names such as `Standard.SheetMetal.ElectronicsEnclosure`; CLR type names are not identities. Template versions contain a protocol-facing major followed by a digest of the authoritative embedded Firmament module.++`describe` returns the template's parameters, nested Record fields, Firmament types, dimensions, preferred transport units, enum cases, defaults, and declared artifact kinds. This metadata comes from `FirmamentTemplateHostBridge.InspectModule`, which uses the same immutable parser/binder IR as invocation. The host does not maintain a second JSON schema.++## Invocation request++```json+{+ "protocolVersion": 1,+ "arguments": {+ "width": "120 mm",+ "height": "40 mm",+ "depth": "80 mm",+ "thickness": "1.5 mm",+ "lidLipHeight": "8 mm",+ "insideRadius": "2 mm",+ "kFactor": 0.42,+ "reliefPolicy": "Rectangular"+ },+ "artifacts": ["StepAp242", "FlatStep", "Svg"]+}+```++The authoritative enclosure parameter is the `EnclosureSpec` Record shown by `describe`. Callers may send it as `{ "Spec": { ... } }`. When a template has exactly one Record parameter, v1 also accepts its fields at the top level, as above. Names are matched case-insensitively and rebound to authoritative Firmament spelling; unknown names remain errors.++Transport values retain engineering meaning:++- `Length` and `Angle` are strings with units; optional whitespace before the unit is normalized before the Firmament binder validates dimension and unit.+- `integer`, `number`, and `boolean` use the matching JSON primitives.+- `string` uses a JSON string.+- Firmament enums use their declared case as a JSON string.+- Record parameters use JSON objects and are validated recursively by the Firmament binder.++No unit or constraint semantics live in clients. For example, `"12 kg"` transported for a `Length` reaches the normal binder and returns `firmament-template-record-field-type-mismatch`.++## Invocation response++```json+{+ "success": true,+ "identity": {+ "protocolVersion": 1,+ "template": "Standard.SheetMetal.ElectronicsEnclosure",+ "templateVersion": "1+b1ab02987f0a",+ "aetherisVersion": "2.0.0-preview.2+...",+ "specialization": "template:94546352d5d67afa"+ },+ "diagnostics": [],+ "artifacts": [+ {+ "kind": "StepAp242",+ "name": "part.step",+ "contentType": "model/step",+ "size": 52386,+ "sha256": "114cd7c0c6a8a364b2943cc955a12d8a96b576a187dfc1957ea9f769296872be",+ "path": "part.step"+ }+ ],+ "executionMilliseconds": 335.0+}+```++Artifact paths are UTF-8 file names relative to the requested output directory, never developer-machine absolute paths. The host chooses bounded file names and verifies that resolved paths remain directly inside that directory. STEP and SVG are written as UTF-8 without a byte-order mark. `sha256` is the lowercase SHA-256 of the exact artifact bytes and excludes response timing or timestamps.++Diagnostics contain `code`, `severity`, `message`, and optional `target` and `source`. Binder, semantic/DFM, lowering, export, request, and path failures retain distinct codes. Managed exception objects and stack traces are not protocol values.++## Lifecycle, concurrency, and security++Each CLI execution accepts one bounded request, writes its result, and exits. `ForgeProtocolHost` also serializes invocation per host instance; protocol v1 does not claim parallel invocation safety. Independent processes may run concurrently subject to normal output-directory isolation.++Only templates in the explicit public catalog are invocable. The process protocol cannot load assemblies, select CLR types, submit Firmament source, execute C#, invoke arbitrary methods, or control host configuration. The request controls values, declared artifact kinds, and one explicit output directory only.++## Compatibility++Additive optional response properties and new templates/artifact kinds may appear within v1. Existing property meaning, diagnostic code meaning, semantic template IDs, and engineering-value transport rules will not be silently changed. A request with an unsupported protocol version fails before binding or lowering.++C# callers continue to use `ForgeHost`, generated Forge bindings, or `SheetMetalProductFamilies` directly. They do not need to serialize JSON or launch a subprocess.diff --git a/samples/forge-interop-x1/README.md b/samples/forge-interop-x1/README.mdnew file mode 100644index 00000000..6d0b2756--- /dev/null+++ b/samples/forge-interop-x1/README.md@@ -0,0 +1,13 @@+# Forge interop X1 dogfood++These are intentionally tiny process clients for Forge Host Protocol v1. Build `Aetheris.Forge.Host` in Release, then pass the resulting host executable, the shared request, and a distinct output directory to a client:++```powershell+python python/client.py <host-executable> request.json out/python+go run go/main.go <host-executable> request.json out/go+rustc rust/client.rs -o out/rust-client.exe+out/rust-client.exe <host-executable> request.json out/rust+node typescript/client.ts <host-executable> request.json out/typescript+```++[`scripts/test-forge-interop-x1.ps1`](../../scripts/test-forge-interop-x1.ps1) builds the host, runs all four, validates every STEP with Aetheris.CLI, and rejects any cross-language artifact hash difference.diff --git a/samples/forge-interop-x1/go/main.go b/samples/forge-interop-x1/go/main.gonew file mode 100644index 00000000..c88db635--- /dev/null+++ b/samples/forge-interop-x1/go/main.go@@ -0,0 +1,35 @@+package main++import (+ "bytes"+ "encoding/json"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+)++type artifact struct { Path string `json:"path"` }+type response struct {+ Success bool `json:"success"`+ Artifacts []artifact `json:"artifacts"`+}++func main() {+ host, requestPath, outputDir := os.Args[1], os.Args[2], os.Args[3]+ request, err := os.ReadFile(requestPath)+ if err != nil { panic(err) }+ command := exec.Command(host, "invoke", "Standard.SheetMetal.ElectronicsEnclosure", "--request", "-", "--out", outputDir)+ command.Stdin = bytes.NewReader(request)+ var stdout bytes.Buffer+ command.Stdout = &stdout+ command.Stderr = os.Stderr+ if err = command.Run(); err != nil { panic(err) }+ var result response+ if err = json.Unmarshal(stdout.Bytes(), &result); err != nil { panic(err) }+ if !result.Success { panic("Forge Host invocation failed") }+ for _, item := range result.Artifacts {+ if _, err = os.Stat(filepath.Join(outputDir, item.Path)); err != nil { panic(err) }+ }+ fmt.Print(stdout.String())+}diff --git a/samples/forge-interop-x1/python/client.py b/samples/forge-interop-x1/python/client.pynew file mode 100644index 00000000..c2d0c23c--- /dev/null+++ b/samples/forge-interop-x1/python/client.py@@ -0,0 +1,20 @@+import json+import pathlib+import subprocess+import sys++host, request_path, output_dir = sys.argv[1:4]+request = pathlib.Path(request_path).read_text(encoding="utf-8")+process = subprocess.run(+ [host, "invoke", "Standard.SheetMetal.ElectronicsEnclosure", "--request", "-", "--out", output_dir],+ input=request,+ text=True,+ capture_output=True,+ check=False,+)+result = json.loads(process.stdout)+if process.returncode != 0 or not result.get("success"):+ raise SystemExit(process.stdout or process.stderr)+for artifact in result["artifacts"]:+ assert (pathlib.Path(output_dir) / artifact["path"]).is_file()+print(json.dumps(result))diff --git a/samples/forge-interop-x1/request.json b/samples/forge-interop-x1/request.jsonnew file mode 100644index 00000000..0d7356cd--- /dev/null+++ b/samples/forge-interop-x1/request.json@@ -0,0 +1,14 @@+{+ "protocolVersion": 1,+ "arguments": {+ "width": "120 mm",+ "height": "40 mm",+ "depth": "80 mm",+ "thickness": "1.5 mm",+ "lidLipHeight": "8 mm",+ "insideRadius": "2 mm",+ "kFactor": 0.42,+ "reliefPolicy": "Rectangular"+ },+ "artifacts": ["StepAp242", "FlatStep", "Svg"]+}diff --git a/samples/forge-interop-x1/rust/client.rs b/samples/forge-interop-x1/rust/client.rsnew file mode 100644index 00000000..1d86c4dc--- /dev/null+++ b/samples/forge-interop-x1/rust/client.rs@@ -0,0 +1,17 @@+use std::{env, fs, io::Write, path::Path, process::{Command, Stdio}};++fn main() {+ let args: Vec<String> = env::args().collect();+ let request = fs::read(&args[2]).expect("read request");+ let mut child = Command::new(&args[1])+ .args(["invoke", "Standard.SheetMetal.ElectronicsEnclosure", "--request", "-", "--out", &args[3]])+ .stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().expect("start Forge Host");+ child.stdin.as_mut().unwrap().write_all(&request).expect("write request");+ let output = child.wait_with_output().expect("wait for Forge Host");+ let response = String::from_utf8(output.stdout).expect("UTF-8 response");+ assert!(output.status.success() && response.contains("\"success\": true"), "{}", response);+ for name in ["part.step", "part.flat.step", "part.flat.svg"] {+ assert!(Path::new(&args[3]).join(name).is_file(), "missing artifact {}", name);+ }+ print!("{response}");+}diff --git a/samples/forge-interop-x1/typescript/client.ts b/samples/forge-interop-x1/typescript/client.tsnew file mode 100644index 00000000..17cfd1fd--- /dev/null+++ b/samples/forge-interop-x1/typescript/client.ts@@ -0,0 +1,14 @@+import { readFileSync, existsSync } from "node:fs";+import { join } from "node:path";+import { spawnSync } from "node:child_process";++const [host, requestPath, outputDirectory] = process.argv.slice(2);+const execution = spawnSync(host, [+ "invoke", "Standard.SheetMetal.ElectronicsEnclosure", "--request", "-", "--out", outputDirectory,+], { input: readFileSync(requestPath), encoding: "utf8" });+const result = JSON.parse(execution.stdout);+if (execution.status !== 0 || !result.success) throw new Error(execution.stdout || execution.stderr);+for (const artifact of result.artifacts) {+ if (!existsSync(join(outputDirectory, artifact.path))) throw new Error(`Missing ${artifact.path}`);+}+process.stdout.write(JSON.stringify(result));diff --git a/scripts/test-forge-interop-x1.ps1 b/scripts/test-forge-interop-x1.ps1new file mode 100644index 00000000..bcbbf14b--- /dev/null+++ b/scripts/test-forge-interop-x1.ps1@@ -0,0 +1,39 @@+[CmdletBinding()]+param()++$ErrorActionPreference = "Stop"+$repo = Split-Path -Parent $PSScriptRoot+$hostPath = Join-Path $repo "Aetheris.Forge.Host/bin/Release/net10.0/Aetheris.Forge.Host.exe"+$request = Join-Path $repo "samples/forge-interop-x1/request.json"+$root = Join-Path $repo ".tmp/forge-interop-x1"++dotnet build (Join-Path $repo "Aetheris.Forge.Host/Aetheris.Forge.Host.csproj") -c Release --nologo | Out-Host+New-Item -ItemType Directory -Force -Path $root | Out-Null++$pythonOut = Join-Path $root "python"+$goOut = Join-Path $root "go"+$rustOut = Join-Path $root "rust"+$typescriptOut = Join-Path $root "typescript"++$python = python (Join-Path $repo "samples/forge-interop-x1/python/client.py") $hostPath $request $pythonOut | ConvertFrom-Json+$go = go run (Join-Path $repo "samples/forge-interop-x1/go/main.go") $hostPath $request $goOut | ConvertFrom-Json+$rustBinary = Join-Path $root "rust-client.exe"+rustc (Join-Path $repo "samples/forge-interop-x1/rust/client.rs") -o $rustBinary+$rust = & $rustBinary $hostPath $request $rustOut | ConvertFrom-Json+$typescript = node (Join-Path $repo "samples/forge-interop-x1/typescript/client.ts") $hostPath $request $typescriptOut | ConvertFrom-Json++$results = [ordered]@{ python = $python; go = $go; rust = $rust; typescript = $typescript }+$baseline = ($python.artifacts | Sort-Object kind | ForEach-Object { "$($_.kind):$($_.sha256)" }) -join ";"+foreach ($entry in $results.GetEnumerator()) {+ $hashes = ($entry.Value.artifacts | Sort-Object kind | ForEach-Object { "$($_.kind):$($_.sha256)" }) -join ";"+ if ($hashes -ne $baseline) { throw "$($entry.Key) artifact hashes differ from Python." }+ $step = Join-Path (Join-Path $root $entry.Key) "part.step"+ dotnet run --project (Join-Path $repo "Aetheris.CLI") -- inspect $step --json | Out-Null+}++[pscustomobject]@{+ template = "Standard.SheetMetal.ElectronicsEnclosure"+ languages = @($results.Keys)+ artifactHashes = $python.artifacts | Select-Object kind, sha256, size+ equivalent = $true+} | ConvertTo-Json -Depth 5