Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add external forge pack validation support

Yuechen Li6aac093b0c40
diff --git a/Aetheris.CLI.Tests/Aetheris.CLI.Tests.csproj b/Aetheris.CLI.Tests/Aetheris.CLI.Tests.csproj
index 4f3273aa..2fd99be1 100644
--- a/Aetheris.CLI.Tests/Aetheris.CLI.Tests.csproj
+++ b/Aetheris.CLI.Tests/Aetheris.CLI.Tests.csproj
@@ -19,5 +19,7 @@
<ItemGroup>
<ProjectReference Include="..\Aetheris.CLI\Aetheris.CLI.csproj" />
+ <ProjectReference Include="..\tests\Aetheris.TestForgePack\Aetheris.TestForgePack.csproj" />
+ <ProjectReference Include="..\tests\Aetheris.TestForgePack.Duplicate\Aetheris.TestForgePack.Duplicate.csproj" />
</ItemGroup>
</Project>
diff --git a/Aetheris.CLI.Tests/FirmamentV2RuntimeConceptValidationCliTests.cs b/Aetheris.CLI.Tests/FirmamentV2RuntimeConceptValidationCliTests.cs
index e53ff32c..09564bb5 100644
--- a/Aetheris.CLI.Tests/FirmamentV2RuntimeConceptValidationCliTests.cs
+++ b/Aetheris.CLI.Tests/FirmamentV2RuntimeConceptValidationCliTests.cs
@@ -1,5 +1,4 @@
using System.Text.Json;
-
namespace Aetheris.CLI.Tests;
public sealed class FirmamentV2RuntimeConceptValidationCliTests
@@ -47,7 +46,7 @@ public sealed class FirmamentV2RuntimeConceptValidationCliTests
}
[Fact]
- public void ValidateHelp_DoesNotAdvertiseExternalForgePackLoading()
+ public void ValidateHelp_AdvertisesTrustedExternalForgePackLoading()
{
var stdout = new StringWriter();
var stderr = new StringWriter();
@@ -56,7 +55,8 @@ public sealed class FirmamentV2RuntimeConceptValidationCliTests
Assert.Equal(0, exitCode);
Assert.Equal(string.Empty, stderr.ToString());
- Assert.DoesNotContain("--forge-pack", stdout.ToString(), StringComparison.Ordinal);
+ Assert.Contains("--forge-pack <path>", stdout.ToString(), StringComparison.Ordinal);
+ Assert.Contains("does not sandbox external packs", stdout.ToString(), StringComparison.Ordinal);
}
[Fact]
@@ -86,6 +86,95 @@ public sealed class FirmamentV2RuntimeConceptValidationCliTests
&& diagnostic.GetProperty("severity").GetString() == "warning");
}
+ [Fact]
+ public void ValidateJson_MissingForgePackPath_FailsClearly()
+ {
+ var fixturePath = FixturePath("Language/valid/concept-applications-forge.valid.firmfixture");
+ var stdout = new StringWriter();
+ var stderr = new StringWriter();
+
+ var exitCode = CliRunner.Run(["validate", fixturePath, "--forge-pack", "does-not-exist.dll", "--json"], stdout, stderr);
+
+ Assert.Equal(1, exitCode);
+ Assert.Equal(string.Empty, stdout.ToString());
+ Assert.Contains("Forge concept pack assembly was not found", stderr.ToString(), StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void ValidateJson_AssemblyWithoutPacks_FailsClearly()
+ {
+ var fixturePath = FixturePath("Language/valid/concept-applications-forge.valid.firmfixture");
+ var stdout = new StringWriter();
+ var stderr = new StringWriter();
+
+ var exitCode = CliRunner.Run(["validate", fixturePath, "--forge-pack", typeof(CliRunner).Assembly.Location, "--json"], stdout, stderr);
+
+ Assert.Equal(1, exitCode);
+ Assert.Equal(string.Empty, stdout.ToString());
+ Assert.Contains("contains no public IForgeConceptPack implementations", stderr.ToString(), StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void ValidateJson_ExternalPack_ValidatesExternalConceptAndReportsProvenance()
+ {
+ var fixturePath = FixturePath("Language/invalid/concept-external-boss-hole.invalid.firmfixture");
+ var stdout = new StringWriter();
+ var stderr = new StringWriter();
+
+ var exitCode = CliRunner.Run(["validate", fixturePath, "--forge-pack", typeof(Aetheris.TestForgePack.TestForgePack).Assembly.Location, "--json"], stdout, stderr);
+
+ Assert.Equal(0, exitCode);
+ Assert.Equal(string.Empty, stderr.ToString());
+
+ using var document = JsonDocument.Parse(stdout.ToString());
+ var validation = document.RootElement.GetProperty("firmamentV2Validation");
+ Assert.Equal("valid", validation.GetProperty("status").GetString());
+ Assert.Contains(
+ validation.GetProperty("diagnostics").EnumerateArray(),
+ diagnostic => diagnostic.GetProperty("code").GetString() == "testforge.boss-hole.seen"
+ && diagnostic.GetProperty("severity").GetString() == "warning");
+ var concept = Assert.Single(validation.GetProperty("concepts").EnumerateArray());
+ Assert.Equal("Aetheris.TestForgePack", concept.GetProperty("runtimeValidation").GetProperty("provider").GetString());
+ var forgeRuntime = validation.GetProperty("forgeRuntime");
+ Assert.Equal("Aetheris.Standard", forgeRuntime.GetProperty("builtInPack").GetString());
+ var externalPack = Assert.Single(forgeRuntime.GetProperty("externalPacks").EnumerateArray());
+ Assert.Equal("Aetheris.TestForgePack", externalPack.GetProperty("id").GetString());
+ Assert.Equal("Aetheris.TestForgePack.dll", externalPack.GetProperty("assembly").GetString());
+ }
+
+ [Fact]
+ public void ValidateJson_DuplicateConceptPack_FailsClearly()
+ {
+ var fixturePath = FixturePath("Language/valid/concept-applications-forge.valid.firmfixture");
+ var stdout = new StringWriter();
+ var stderr = new StringWriter();
+ var duplicatePackPath = Path.Combine(AppContext.BaseDirectory, "Aetheris.TestForgePack.Duplicate.dll");
+
+ var exitCode = CliRunner.Run(["validate", fixturePath, "--forge-pack", duplicatePackPath, "--json"], stdout, stderr);
+
+ Assert.Equal(1, exitCode);
+ Assert.Equal(string.Empty, stdout.ToString());
+ Assert.Contains("duplicate concept 'hole<Countersink>'", stderr.ToString(), StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void ValidateJson_DefaultRuntime_RemainsBuiltInOnly()
+ {
+ var fixturePath = FixturePath("Language/valid/concept-applications-forge.valid.firmfixture");
+ var stdout = new StringWriter();
+ var stderr = new StringWriter();
+
+ var exitCode = CliRunner.Run(["validate", fixturePath, "--json"], stdout, stderr);
+
+ Assert.Equal(0, exitCode);
+ Assert.Equal(string.Empty, stderr.ToString());
+
+ using var document = JsonDocument.Parse(stdout.ToString());
+ var forgeRuntime = document.RootElement.GetProperty("firmamentV2Validation").GetProperty("forgeRuntime");
+ Assert.Equal("Aetheris.Standard", forgeRuntime.GetProperty("builtInPack").GetString());
+ Assert.Empty(forgeRuntime.GetProperty("externalPacks").EnumerateArray());
+ }
+
private static string FixturePath(string relative) => Path.Combine(FindRepoRoot(), "fixtures", "FirmamentV2", relative);
private static string FindRepoRoot()
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index b798ef1f..b635c3ea 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -1,5 +1,6 @@
using System.Text.Json;
using System.Text.Json.Serialization;
+using Aetheris.Forge.Abstractions.FirmamentInterop;
using Aetheris.Kernel.Firmament;
using Aetheris.Kernel.Firmament.Assembly;
using Aetheris.Kernel.Firmament.FirmamentV2;
@@ -109,7 +110,7 @@ public static class CliRunner
int? RigidRootCount = null);
private const string TopLevelUsage = "Usage: aetheris <build|validate|analyze|trace|canon|asm|experimental> <path> [options]";
private const string BuildUsage = "Usage: aetheris build <file.firmament> [--out <path>] [--json]";
- private const string ValidateUsage = "Usage: aetheris validate <file.firmament|file.firmfixture> [--json]";
+ private const string ValidateUsage = "Usage: aetheris validate <file.firmament|file.firmfixture> [--forge-pack <path>] [--json]";
private const string AnalyzeUsage = "Usage: aetheris analyze <file.step> [--face <id>] [--edge <id>] [--vertex <id>] [--json]";
private const string AnalyzeMapUsage = "Usage: aetheris analyze map <file.step> (--plane <xy|xz|yz> --direction <+x|-x|+y|-y|+z|-z> | --views six --llm) --resolution <NxM> [--point <u,v>] [--rank-probes|--evidence-bundle] --json";
private const string AnalyzeSectionUsage = "Usage: aetheris analyze section <file.step> (--xy|--xz|--yz) --offset <value> --json";
@@ -288,23 +289,30 @@ public static class CliRunner
if (IsHelpFlag(args[0]))
{
- stdout.WriteLine(ValidateUsage);
- stdout.WriteLine(" --json Emit Firmament V2 validation report JSON.");
+ WriteValidateHelp(stdout);
return 0;
}
var sourcePath = args[0];
var json = false;
+ var forgePackPaths = new List<string>();
for (var i = 1; i < args.Length; i++)
{
switch (args[i])
{
+ case "--forge-pack" when i + 1 < args.Length:
+ forgePackPaths.Add(args[++i]);
+ break;
+ case "--forge-pack":
+ stderr.WriteLine("Validate option --forge-pack requires a local assembly path.");
+ stderr.WriteLine(ValidateUsage);
+ return 1;
case "--json":
json = true;
break;
case "-h":
case "--help":
- stdout.WriteLine(ValidateUsage);
+ WriteValidateHelp(stdout);
return 0;
default:
stderr.WriteLine($"Unknown validate option '{args[i]}'.");
@@ -319,13 +327,38 @@ public static class CliRunner
return 1;
}
- var parse = FirmamentV2Parser.Parse(File.ReadAllText(sourcePath), Path.GetDirectoryName(Path.GetFullPath(sourcePath)));
- var report = FirmamentV2ValidationReportBuilder.Build(parse, sourcePath);
+ var runtimeConfiguration = CreateValidateForgeRuntimeConfiguration(forgePackPaths);
+ var parse = FirmamentV2Parser.Parse(
+ File.ReadAllText(sourcePath),
+ Path.GetDirectoryName(Path.GetFullPath(sourcePath)),
+ runtimeConfiguration.Catalog);
+ var runtimeValidation = FirmamentV2RuntimeConceptValidation.Validate(parse.Document, runtimeConfiguration);
+ var report = FirmamentV2ValidationReportBuilder.Build(parse, sourcePath, runtimeValidation, runtimeConfiguration.Catalog);
if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = report }, JsonOptions));
else stdout.WriteLine($"Firmament V2 validation: {report.Status} ({report.Summary.FatalDiagnosticCount} fatal, {report.Summary.WarningDiagnosticCount} warning)");
return report.Status == "invalid" ? 1 : 0;
}
+ private static FirmamentV2ForgeRuntimeConfiguration CreateValidateForgeRuntimeConfiguration(IReadOnlyList<string> forgePackPaths)
+ {
+ if (forgePackPaths.Count == 0)
+ {
+ return FirmamentV2ForgeRuntimeConfiguration.CreateDefault();
+ }
+
+ var loader = new ForgeConceptPackAssemblyLoader();
+ var packs = new List<(IForgeConceptPack Pack, string AssemblyPath)>();
+ foreach (var forgePackPath in forgePackPaths)
+ {
+ foreach (var pack in loader.LoadFromAssemblyPath(forgePackPath))
+ {
+ packs.Add((pack, Path.GetFullPath(forgePackPath)));
+ }
+ }
+
+ return FirmamentV2ForgeRuntimeConfiguration.Create(packs);
+ }
+
private static int RunTrace(string[] args, TextWriter stdout, TextWriter stderr)
{
if (args.Length > 0 && IsHelpFlag(args[0]))
@@ -2292,6 +2325,13 @@ public static class CliRunner
stdout.WriteLine(" aetheris build part.firmament --out part.step --json");
}
+ private static void WriteValidateHelp(TextWriter stdout)
+ {
+ stdout.WriteLine(ValidateUsage);
+ stdout.WriteLine(" --json Emit Firmament V2 validation report JSON.");
+ stdout.WriteLine(" --forge-pack <path> Load a trusted local .NET assembly containing IForgeConceptPack implementations. This executes local code; Aetheris does not sandbox external packs. Do not load untrusted packs.");
+ }
+
private static void WriteTraceHelp(TextWriter stdout)
{
stdout.WriteLine("Trace a built-in Aetheris lowering case through AIR, route selection, BRepPlan, emitted BRep/STEP smoke, and CIR mirror admission. Use `analyze` for existing STEP/BRep geometry.");
diff --git a/Aetheris.Forge/Abstractions/FirmamentInterop/ForgeConceptPackAssemblyLoader.cs b/Aetheris.Forge/Abstractions/FirmamentInterop/ForgeConceptPackAssemblyLoader.cs
new file mode 100644
index 00000000..dbd17544
--- /dev/null
+++ b/Aetheris.Forge/Abstractions/FirmamentInterop/ForgeConceptPackAssemblyLoader.cs
@@ -0,0 +1,92 @@
+using System.Reflection;
+using System.Runtime.Loader;
+
+namespace Aetheris.Forge.Abstractions.FirmamentInterop;
+
+public sealed class ForgeConceptPackAssemblyLoader
+{
+ public IReadOnlyList<IForgeConceptPack> LoadFromAssemblyPath(string path)
+ {
+ ArgumentException.ThrowIfNullOrWhiteSpace(path);
+
+ if (path.StartsWith("file:", StringComparison.OrdinalIgnoreCase))
+ {
+ throw new InvalidOperationException(
+ $"Forge concept pack path '{path}' must be a local file path, not a URI. Forge concept packs are trusted local code execution. Aetheris does not sandbox external packs. Do not load packs you do not trust.");
+ }
+
+ if (Uri.TryCreate(path, UriKind.Absolute, out var uri) && !uri.IsFile)
+ {
+ throw new InvalidOperationException(
+ $"Forge concept pack path '{path}' must be a local file path, not a URI. Forge concept packs are trusted local code execution. Aetheris does not sandbox external packs. Do not load packs you do not trust.");
+ }
+
+ var fullPath = Path.GetFullPath(path);
+ if (Directory.Exists(fullPath))
+ {
+ throw new InvalidOperationException(
+ $"Forge concept pack path '{path}' resolves to a directory. Forge concept packs are trusted local code execution. Aetheris does not sandbox external packs. Do not load packs you do not trust.");
+ }
+
+ if (!File.Exists(fullPath))
+ {
+ throw new InvalidOperationException(
+ $"Forge concept pack assembly was not found: {path}. Forge concept packs are trusted local code execution. Aetheris does not sandbox external packs. Do not load packs you do not trust.");
+ }
+
+ if (!string.Equals(Path.GetExtension(fullPath), ".dll", StringComparison.OrdinalIgnoreCase))
+ {
+ throw new InvalidOperationException(
+ $"Forge concept pack path '{path}' must point to a local .dll assembly. Forge concept packs are trusted local code execution. Aetheris does not sandbox external packs. Do not load packs you do not trust.");
+ }
+
+ Assembly assembly;
+ try
+ {
+ assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath);
+ }
+ catch (BadImageFormatException ex)
+ {
+ throw new InvalidOperationException($"Forge concept pack assembly '{path}' is not a valid .NET assembly.", ex);
+ }
+ catch (FileLoadException ex)
+ {
+ throw new InvalidOperationException($"Forge concept pack assembly '{path}' could not be loaded.", ex);
+ }
+
+ var packTypes = assembly
+ .GetExportedTypes()
+ .Where(type => type.IsClass && !type.IsAbstract && typeof(IForgeConceptPack).IsAssignableFrom(type))
+ .OrderBy(type => type.FullName, StringComparer.Ordinal)
+ .ToArray();
+
+ if (packTypes.Length == 0)
+ {
+ throw new InvalidOperationException($"Forge concept pack assembly '{path}' contains no public IForgeConceptPack implementations.");
+ }
+
+ var packs = new List<IForgeConceptPack>(packTypes.Length);
+ foreach (var packType in packTypes)
+ {
+ var constructor = packType.GetConstructor(Type.EmptyTypes);
+ if (constructor is null || !constructor.IsPublic)
+ {
+ throw new InvalidOperationException(
+ $"Forge concept pack type '{packType.FullName}' in '{path}' must have a public parameterless constructor.");
+ }
+
+ try
+ {
+ packs.Add((IForgeConceptPack)constructor.Invoke(null));
+ }
+ catch (TargetInvocationException ex)
+ {
+ throw new InvalidOperationException(
+ $"Forge concept pack type '{packType.FullName}' in '{path}' threw during activation: {ex.InnerException?.Message ?? ex.Message}",
+ ex.InnerException ?? ex);
+ }
+ }
+
+ return packs;
+ }
+}
diff --git a/Aetheris.Forge/Abstractions/FirmamentInterop/ForgeConceptRegistry.cs b/Aetheris.Forge/Abstractions/FirmamentInterop/ForgeConceptRegistry.cs
index 69990a2e..efcea5f4 100644
--- a/Aetheris.Forge/Abstractions/FirmamentInterop/ForgeConceptRegistry.cs
+++ b/Aetheris.Forge/Abstractions/FirmamentInterop/ForgeConceptRegistry.cs
@@ -41,6 +41,12 @@ public sealed class ForgeConceptRegistry : IForgeRegistry
}
public bool TryResolve(ConceptId id, out IForgeConcept concept) => concepts.TryGetValue(id, out concept!);
+
+ public IReadOnlyList<IForgeConcept> EnumerateConcepts() =>
+ concepts.Values
+ .OrderBy(concept => concept.Id.Family, StringComparer.Ordinal)
+ .ThenBy(concept => concept.Id.Concept, StringComparer.Ordinal)
+ .ToArray();
}
public sealed class ConceptSchemaBuilder
diff --git a/Aetheris.Kernel.Firmament.Tests/Aetheris.Kernel.Firmament.Tests.csproj b/Aetheris.Kernel.Firmament.Tests/Aetheris.Kernel.Firmament.Tests.csproj
index 04528d53..e6606506 100644
--- a/Aetheris.Kernel.Firmament.Tests/Aetheris.Kernel.Firmament.Tests.csproj
+++ b/Aetheris.Kernel.Firmament.Tests/Aetheris.Kernel.Firmament.Tests.csproj
@@ -46,5 +46,7 @@
<ProjectReference Include="..\Aetheris.Kernel.Firmament\Aetheris.Kernel.Firmament.csproj" />
<ProjectReference Include="..\Aetheris.Kernel.Core\Aetheris.Kernel.Core.csproj" />
<ProjectReference Include="..\Aetheris.Firmament.FrictionLab\Aetheris.Firmament.FrictionLab.csproj" />
+ <ProjectReference Include="..\tests\Aetheris.TestForgePack\Aetheris.TestForgePack.csproj" />
+ <ProjectReference Include="..\tests\Aetheris.TestForgePack.Duplicate\Aetheris.TestForgePack.Duplicate.csproj" />
</ItemGroup>
</Project>
diff --git a/Aetheris.Kernel.Firmament.Tests/ForgeCsA3RuntimeConceptValidationTests.cs b/Aetheris.Kernel.Firmament.Tests/ForgeCsA3RuntimeConceptValidationTests.cs
index cf1be44d..656f0025 100644
--- a/Aetheris.Kernel.Firmament.Tests/ForgeCsA3RuntimeConceptValidationTests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/ForgeCsA3RuntimeConceptValidationTests.cs
@@ -124,7 +124,8 @@ public sealed class ForgeCsA3RuntimeConceptValidationTests
{
var runtime = FirmamentV2RuntimeConceptValidation.Validate(ParseFixture("Language/valid/concept-applications-forge.valid.firmfixture").Document);
- Assert.Equal("Aetheris.Standard", runtime.Provider);
+ Assert.Equal("Aetheris.Standard", runtime.ForgeRuntime.BuiltInPack);
+ Assert.Empty(runtime.ForgeRuntime.ExternalPacks);
Assert.Equal(2, runtime.Concepts.Count);
Assert.All(runtime.Concepts, concept => Assert.Equal("Aetheris.Standard", concept.Provider));
}
diff --git a/Aetheris.Kernel.Firmament.Tests/ForgeCsA5ExternalConceptPackTests.cs b/Aetheris.Kernel.Firmament.Tests/ForgeCsA5ExternalConceptPackTests.cs
new file mode 100644
index 00000000..649b64aa
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/ForgeCsA5ExternalConceptPackTests.cs
@@ -0,0 +1,100 @@
+using Aetheris.Forge.Abstractions.FirmamentInterop;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class ForgeCsA5ExternalConceptPackTests
+{
+ [Fact]
+ public void ForgeCsA5_WithoutExternalPack_UnknownExternalConceptRemainsInvalid()
+ {
+ var parse = ParseFixture("Language/invalid/concept-external-boss-hole.invalid.firmfixture");
+
+ Assert.NotNull(parse.Document);
+ Assert.Contains(FirmamentV2Parser.ConceptUnknownConcept, parse.Diagnostics);
+ }
+
+ [Fact]
+ public void ForgeCsA5_WithExternalPack_ParserAndRuntimeAcceptExternalConcept()
+ {
+ var configuration = CreateExternalRuntimeConfiguration(typeof(Aetheris.TestForgePack.TestForgePack).Assembly.Location);
+ var path = FixturePath("Language/invalid/concept-external-boss-hole.invalid.firmfixture");
+ var parse = FirmamentV2Parser.Parse(File.ReadAllText(path), Path.GetDirectoryName(path), configuration.Catalog);
+
+ Assert.True(parse.IsSuccess);
+ Assert.DoesNotContain(FirmamentV2Parser.ConceptUnknownConcept, parse.Diagnostics);
+
+ var runtime = FirmamentV2RuntimeConceptValidation.Validate(parse.Document, configuration);
+ Assert.Equal("Aetheris.Standard", runtime.ForgeRuntime.BuiltInPack);
+ var externalPack = Assert.Single(runtime.ForgeRuntime.ExternalPacks);
+ Assert.Equal("Aetheris.TestForgePack", externalPack.Id);
+ Assert.Contains(runtime.Diagnostics, diagnostic => diagnostic.Code == "testforge.boss-hole.seen");
+
+ var report = FirmamentV2ValidationReportBuilder.Build(parse, path, runtime, configuration.Catalog);
+ Assert.Equal("valid", report.Status);
+ Assert.Equal("Aetheris.Standard", report.ForgeRuntime.BuiltInPack);
+ Assert.Single(report.ForgeRuntime.ExternalPacks, pack => pack.Id == "Aetheris.TestForgePack");
+ var concept = Assert.Single(report.Concepts);
+ Assert.Equal("Aetheris.TestForgePack", concept.RuntimeValidation!.Provider);
+ Assert.Contains(concept.RuntimeValidation.Diagnostics, diagnostic => diagnostic.Code == "testforge.boss-hole.seen");
+ }
+
+ [Fact]
+ public void ForgeCsA5_DuplicateConceptRegistration_IsDeterministic()
+ {
+ var loader = new ForgeConceptPackAssemblyLoader();
+ var duplicateAssembly = Path.Combine(AppContext.BaseDirectory, "Aetheris.TestForgePack.Duplicate.dll");
+ var packs = loader.LoadFromAssemblyPath(duplicateAssembly)
+ .Select(pack => (pack, AssemblyPath: duplicateAssembly))
+ .ToArray();
+
+ var exception = Assert.Throws<InvalidOperationException>(() => FirmamentV2ForgeRuntimeConfiguration.Create(packs));
+
+ Assert.Contains("duplicate concept 'hole<Countersink>'", exception.Message, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void ForgeCsA5_DefaultReport_RemainsBuiltInOnly()
+ {
+ var report = BuildFixture("Language/valid/concept-applications-forge.valid.firmfixture");
+
+ Assert.Equal("Aetheris.Standard", report.ForgeRuntime.BuiltInPack);
+ Assert.Empty(report.ForgeRuntime.ExternalPacks);
+ }
+
+ private static FirmamentV2ValidationReport BuildFixture(string relative)
+ {
+ var path = FixturePath(relative);
+ var parse = FirmamentV2Parser.Parse(File.ReadAllText(path), Path.GetDirectoryName(path));
+ Assert.NotNull(parse.Document);
+ return FirmamentV2ValidationReportBuilder.Build(parse, path);
+ }
+
+ private static FirmamentV2ParseResult ParseFixture(string relative)
+ {
+ var path = FixturePath(relative);
+ return FirmamentV2Parser.Parse(File.ReadAllText(path), Path.GetDirectoryName(path));
+ }
+
+ private static FirmamentV2ForgeRuntimeConfiguration CreateExternalRuntimeConfiguration(string assemblyPath)
+ {
+ var loader = new ForgeConceptPackAssemblyLoader();
+ var packs = loader.LoadFromAssemblyPath(assemblyPath)
+ .Select(pack => (pack, AssemblyPath: assemblyPath))
+ .ToArray();
+ return FirmamentV2ForgeRuntimeConfiguration.Create(packs);
+ }
+
+ private static string FixturePath(string relative) => Path.Combine(FindRepoRoot(), "fixtures", "FirmamentV2", relative);
+
+ private static string FindRepoRoot()
+ {
+ var dir = new DirectoryInfo(AppContext.BaseDirectory);
+ while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "Aetheris.slnx")))
+ {
+ dir = dir.Parent;
+ }
+
+ return dir?.FullName ?? throw new InvalidOperationException("Could not find repo root.");
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ForgeConceptRegistry.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ForgeConceptRegistry.cs
index f824bd5d..842218b6 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ForgeConceptRegistry.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ForgeConceptRegistry.cs
@@ -1,3 +1,6 @@
+using Aetheris.Forge.Abstractions.FirmamentInterop;
+using Aetheris.Forge.Standard;
+
namespace Aetheris.Kernel.Firmament.FirmamentV2;
public enum FirmamentV2ForgeFieldKind
@@ -5,7 +8,11 @@ public enum FirmamentV2ForgeFieldKind
Length,
Angle,
Target,
- Material
+ Material,
+ String,
+ Bool,
+ Float,
+ Int
}
public sealed record FirmamentV2ForgeFieldDescriptor(string Name, FirmamentV2ForgeFieldKind Kind, bool Required)
@@ -15,6 +22,10 @@ public sealed record FirmamentV2ForgeFieldDescriptor(string Name, FirmamentV2For
FirmamentV2ForgeFieldKind.Length => type == FirmamentV2PrimitiveType.Length,
FirmamentV2ForgeFieldKind.Angle => type == FirmamentV2PrimitiveType.Angle,
FirmamentV2ForgeFieldKind.Material => type == FirmamentV2PrimitiveType.String,
+ FirmamentV2ForgeFieldKind.String => type == FirmamentV2PrimitiveType.String,
+ FirmamentV2ForgeFieldKind.Bool => type == FirmamentV2PrimitiveType.Bool,
+ FirmamentV2ForgeFieldKind.Float => type == FirmamentV2PrimitiveType.Float,
+ FirmamentV2ForgeFieldKind.Int => type == FirmamentV2PrimitiveType.Int,
FirmamentV2ForgeFieldKind.Target => false,
_ => false
};
@@ -22,61 +33,109 @@ public sealed record FirmamentV2ForgeFieldDescriptor(string Name, FirmamentV2For
public sealed record FirmamentV2ForgeConceptDescriptor(string FamilyName, string ConceptName, IReadOnlyDictionary<string, FirmamentV2ForgeFieldDescriptor> Fields);
-public static class FirmamentV2ForgeConceptRegistry
+public sealed class FirmamentV2ForgeConceptCatalog
{
- private static readonly IReadOnlyDictionary<string, IReadOnlyDictionary<string, FirmamentV2ForgeConceptDescriptor>> Families = Build();
+ private readonly IReadOnlyDictionary<string, IReadOnlyDictionary<string, FirmamentV2ForgeConceptDescriptor>> families;
- public static bool HasFamily(string familyName) => Families.ContainsKey(familyName);
+ public FirmamentV2ForgeConceptCatalog(IReadOnlyDictionary<string, IReadOnlyDictionary<string, FirmamentV2ForgeConceptDescriptor>> families)
+ {
+ ArgumentNullException.ThrowIfNull(families);
+ this.families = families;
+ }
- public static bool TryGet(string familyName, string conceptName, out FirmamentV2ForgeConceptDescriptor descriptor)
+ public bool HasFamily(string familyName) => families.ContainsKey(familyName);
+
+ public bool TryGet(string familyName, string conceptName, out FirmamentV2ForgeConceptDescriptor descriptor)
{
descriptor = null!;
- if (!Families.TryGetValue(familyName, out var concepts)) return false;
+ if (!families.TryGetValue(familyName, out var concepts))
+ {
+ return false;
+ }
+
return concepts.TryGetValue(conceptName, out descriptor!);
}
- internal static IReadOnlyList<FirmamentV2ForgeConceptDescriptor> EnumerateDescriptors() =>
- Families.Values
+ public IReadOnlyList<FirmamentV2ForgeConceptDescriptor> EnumerateDescriptors() =>
+ families.Values
.SelectMany(concepts => concepts.Values)
.OrderBy(descriptor => descriptor.FamilyName, StringComparer.Ordinal)
.ThenBy(descriptor => descriptor.ConceptName, StringComparer.Ordinal)
.ToArray();
- private static IReadOnlyDictionary<string, IReadOnlyDictionary<string, FirmamentV2ForgeConceptDescriptor>> Build()
+ public static FirmamentV2ForgeConceptCatalog FromConcepts(IEnumerable<IForgeConcept> concepts)
{
- var process = new Dictionary<string, FirmamentV2ForgeConceptDescriptor>(StringComparer.Ordinal)
- {
- ["CNC"] = Descriptor("process", "CNC",
- Field("material", FirmamentV2ForgeFieldKind.Material),
- Field("minimumToolRadius", FirmamentV2ForgeFieldKind.Length))
- };
+ ArgumentNullException.ThrowIfNull(concepts);
- var hole = new Dictionary<string, FirmamentV2ForgeConceptDescriptor>(StringComparer.Ordinal)
- {
- ["Countersink"] = Descriptor("hole", "Countersink",
- Field("target", FirmamentV2ForgeFieldKind.Target),
- Field("diameter", FirmamentV2ForgeFieldKind.Length),
- Field("countersinkDiameter", FirmamentV2ForgeFieldKind.Length),
- Field("angle", FirmamentV2ForgeFieldKind.Angle)),
- ["Shaft"] = Descriptor("hole", "Shaft",
- Field("target", FirmamentV2ForgeFieldKind.Target),
- Field("diameter", FirmamentV2ForgeFieldKind.Length)),
- ["Counterbore"] = Descriptor("hole", "Counterbore",
- Field("target", FirmamentV2ForgeFieldKind.Target),
- Field("diameter", FirmamentV2ForgeFieldKind.Length),
- Field("counterboreDiameter", FirmamentV2ForgeFieldKind.Length),
- Field("counterboreDepth", FirmamentV2ForgeFieldKind.Length))
- };
-
- return new Dictionary<string, IReadOnlyDictionary<string, FirmamentV2ForgeConceptDescriptor>>(StringComparer.Ordinal)
+ var families = new Dictionary<string, Dictionary<string, FirmamentV2ForgeConceptDescriptor>>(StringComparer.Ordinal);
+ foreach (var concept in concepts)
{
- ["process"] = process,
- ["hole"] = hole
- };
+ var descriptor = ToDescriptor(concept);
+ if (!families.TryGetValue(descriptor.FamilyName, out var family))
+ {
+ family = new Dictionary<string, FirmamentV2ForgeConceptDescriptor>(StringComparer.Ordinal);
+ families.Add(descriptor.FamilyName, family);
+ }
+
+ family.Add(descriptor.ConceptName, descriptor);
+ }
+
+ return new FirmamentV2ForgeConceptCatalog(
+ families.ToDictionary(
+ pair => pair.Key,
+ pair => (IReadOnlyDictionary<string, FirmamentV2ForgeConceptDescriptor>)pair.Value,
+ StringComparer.Ordinal));
}
- private static FirmamentV2ForgeConceptDescriptor Descriptor(string family, string concept, params FirmamentV2ForgeFieldDescriptor[] fields) =>
- new(family, concept, fields.ToDictionary(f => f.Name, StringComparer.Ordinal));
+ public static FirmamentV2ForgeConceptCatalog CreateBuiltIn()
+ {
+ var registry = new ForgeConceptRegistry();
+ new StandardForgeRuntimeConceptPack().Register(registry);
+ return FromConcepts(registry.EnumerateConcepts());
+ }
+
+ private static FirmamentV2ForgeConceptDescriptor ToDescriptor(IForgeConcept concept)
+ {
+ ArgumentNullException.ThrowIfNull(concept);
- private static FirmamentV2ForgeFieldDescriptor Field(string name, FirmamentV2ForgeFieldKind kind) => new(name, kind, true);
+ var schema = new ConceptSchemaBuilder();
+ concept.Define(schema);
+ return new FirmamentV2ForgeConceptDescriptor(
+ concept.Id.Family,
+ concept.Id.Concept,
+ schema.Fields.ToDictionary(
+ field => field.Name,
+ field => new FirmamentV2ForgeFieldDescriptor(field.Name, MapFieldKind(field.Kind), field.Required),
+ StringComparer.Ordinal));
+ }
+
+ private static FirmamentV2ForgeFieldKind MapFieldKind(ConceptSchemaValueKind kind) => kind switch
+ {
+ ConceptSchemaValueKind.Length => FirmamentV2ForgeFieldKind.Length,
+ ConceptSchemaValueKind.Angle => FirmamentV2ForgeFieldKind.Angle,
+ ConceptSchemaValueKind.Target => FirmamentV2ForgeFieldKind.Target,
+ ConceptSchemaValueKind.Material => FirmamentV2ForgeFieldKind.Material,
+ ConceptSchemaValueKind.String => FirmamentV2ForgeFieldKind.String,
+ ConceptSchemaValueKind.Bool => FirmamentV2ForgeFieldKind.Bool,
+ ConceptSchemaValueKind.Float => FirmamentV2ForgeFieldKind.Float,
+ ConceptSchemaValueKind.Int => FirmamentV2ForgeFieldKind.Int,
+ _ => throw new InvalidOperationException($"Concept schema kind '{kind}' is not supported by Firmament V2 parser descriptors.")
+ };
+}
+
+public static class FirmamentV2ForgeConceptRegistry
+{
+ private static readonly FirmamentV2ForgeConceptCatalog DefaultCatalog = FirmamentV2ForgeConceptCatalog.CreateBuiltIn();
+
+ public static FirmamentV2ForgeConceptCatalog Catalog => DefaultCatalog;
+
+ public static bool HasFamily(string familyName) => DefaultCatalog.HasFamily(familyName);
+
+ public static bool TryGet(string familyName, string conceptName, out FirmamentV2ForgeConceptDescriptor descriptor)
+ {
+ return DefaultCatalog.TryGet(familyName, conceptName, out descriptor);
+ }
+
+ internal static IReadOnlyList<FirmamentV2ForgeConceptDescriptor> EnumerateDescriptors() =>
+ DefaultCatalog.EnumerateDescriptors();
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ForgeRuntime.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ForgeRuntime.cs
new file mode 100644
index 00000000..80ffd2b4
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ForgeRuntime.cs
@@ -0,0 +1,117 @@
+using Aetheris.Forge.Abstractions.FirmamentInterop;
+using Aetheris.Forge.Standard;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+public sealed record FirmamentV2ExternalForgePackReference(
+ string Id,
+ string Version,
+ string Assembly);
+
+public sealed record FirmamentV2ForgeRuntimeMetadata(
+ string BuiltInPack,
+ IReadOnlyList<FirmamentV2ExternalForgePackReference> ExternalPacks);
+
+public sealed class FirmamentV2ForgeRuntimeConfiguration
+{
+ private FirmamentV2ForgeRuntimeConfiguration(
+ FirmamentV2ForgeConceptCatalog catalog,
+ IForgeRegistry registry,
+ IReadOnlyDictionary<ConceptId, string> conceptProviders,
+ FirmamentV2ForgeRuntimeMetadata metadata)
+ {
+ Catalog = catalog;
+ Registry = registry;
+ ConceptProviders = conceptProviders;
+ Metadata = metadata;
+ }
+
+ public FirmamentV2ForgeConceptCatalog Catalog { get; }
+
+ public IForgeRegistry Registry { get; }
+
+ public IReadOnlyDictionary<ConceptId, string> ConceptProviders { get; }
+
+ public FirmamentV2ForgeRuntimeMetadata Metadata { get; }
+
+ public static FirmamentV2ForgeRuntimeConfiguration CreateDefault() => Create([]);
+
+ public static FirmamentV2ForgeRuntimeConfiguration Create(
+ IReadOnlyList<(IForgeConceptPack Pack, string AssemblyPath)> externalPacks)
+ {
+ ArgumentNullException.ThrowIfNull(externalPacks);
+
+ var trackingRegistry = new TrackingForgeRegistry();
+ var builtInPack = new StandardForgeRuntimeConceptPack();
+ trackingRegistry.RegisterPack(builtInPack, null);
+
+ var externalPackMetadata = new List<FirmamentV2ExternalForgePackReference>(externalPacks.Count);
+ foreach (var (pack, assemblyPath) in externalPacks)
+ {
+ trackingRegistry.RegisterPack(pack, assemblyPath);
+ externalPackMetadata.Add(new FirmamentV2ExternalForgePackReference(
+ pack.Id,
+ pack.Version.ToString(),
+ Path.GetFileName(assemblyPath)));
+ }
+
+ return new FirmamentV2ForgeRuntimeConfiguration(
+ FirmamentV2ForgeConceptCatalog.FromConcepts(trackingRegistry.EnumerateConcepts()),
+ trackingRegistry,
+ new Dictionary<ConceptId, string>(trackingRegistry.ConceptProviders),
+ new FirmamentV2ForgeRuntimeMetadata(builtInPack.Id, externalPackMetadata));
+ }
+
+ private sealed class TrackingForgeRegistry : IForgeRegistry
+ {
+ private readonly ForgeConceptRegistry inner = new();
+ private readonly Dictionary<ConceptId, string> conceptProviders = new();
+ private string? currentPackId;
+ private string? currentAssemblyPath;
+
+ public IReadOnlyDictionary<ConceptId, string> ConceptProviders => conceptProviders;
+
+ public void RegisterPack(IForgeConceptPack pack, string? assemblyPath)
+ {
+ ArgumentNullException.ThrowIfNull(pack);
+
+ currentPackId = pack.Id;
+ currentAssemblyPath = assemblyPath;
+ try
+ {
+ pack.Register(this);
+ }
+ catch (Exception ex) when (ex is not InvalidOperationException || assemblyPath is not null)
+ {
+ var prefix = assemblyPath is null
+ ? $"Built-in forge concept pack '{pack.Id}' failed to register."
+ : $"External forge concept pack '{pack.Id}' from '{assemblyPath}' failed to register.";
+ throw new InvalidOperationException($"{prefix} {ex.Message}", ex);
+ }
+ finally
+ {
+ currentPackId = null;
+ currentAssemblyPath = null;
+ }
+ }
+
+ public void Register(IForgeConcept concept)
+ {
+ ArgumentNullException.ThrowIfNull(concept);
+
+ if (conceptProviders.ContainsKey(concept.Id))
+ {
+ var packLabel = currentPackId ?? "<unknown-pack>";
+ var sourceLabel = currentAssemblyPath is null ? packLabel : $"{packLabel} ({currentAssemblyPath})";
+ throw new InvalidOperationException($"Forge concept pack '{sourceLabel}' attempted to register duplicate concept '{concept.Id}'.");
+ }
+
+ inner.Register(concept);
+ conceptProviders.Add(concept.Id, currentPackId ?? string.Empty);
+ }
+
+ public bool TryResolve(ConceptId id, out IForgeConcept concept) => inner.TryResolve(id, out concept!);
+
+ public IReadOnlyList<IForgeConcept> EnumerateConcepts() => inner.EnumerateConcepts();
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index dd25e31d..80b0e9a7 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -211,13 +211,19 @@ public static class FirmamentV2Parser
private static readonly Regex ConceptRegex = new(@"\bconcept\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s*:\s*(?<value>[-+0-9.eE]+)\s*(?<unit>[A-Za-z_][A-Za-z0-9_]*)?", RegexOptions.CultureInvariant);
private static readonly Regex PathRegex = new("\\bpath\\s*:\\s*\"(?<path>[^\"]+)\"", RegexOptions.CultureInvariant);
- public static FirmamentV2ParseResult Parse(string sourceText) => Parse(sourceText, null);
+ public static FirmamentV2ParseResult Parse(string sourceText) => Parse(sourceText, null, null);
- public static FirmamentV2ParseResult Parse(string sourceText, string? sourceDirectory)
+ public static FirmamentV2ParseResult Parse(string sourceText, string? sourceDirectory) => Parse(sourceText, sourceDirectory, null);
+
+ public static FirmamentV2ParseResult Parse(
+ string sourceText,
+ string? sourceDirectory,
+ FirmamentV2ForgeConceptCatalog? conceptCatalog)
{
ArgumentNullException.ThrowIfNull(sourceText);
var diagnostics = new List<string> { "firmament-v2-parser-invoked" };
var source = StripLineComments(sourceText);
+ conceptCatalog ??= FirmamentV2ForgeConceptRegistry.Catalog;
if (ContainsRawBackendId(source)) diagnostics.Add(RawBackendIdReferenceForbidden);
if (ContainsUnsupportedConstruct(source)) diagnostics.Add(UnsupportedConstruct);
@@ -266,7 +272,7 @@ public static class FirmamentV2Parser
var recognizedRegions = ParseRecognizedRegions(source, byName, diagnostics);
var replacements = ParseReplacements(source, byName, recognizedRegions, diagnostics);
var (pmi, pmiBlock, boundPmi) = ParsePmi(source, byName, modifyBlocks, recognizedRegions, boundLets, boundLetRecords, diagnostics);
- var (manufacturingConcepts, featureConcepts) = ParseConceptApplications(source, boundLets, boundLetRecords, diagnostics);
+ var (manufacturingConcepts, featureConcepts) = ParseConceptApplications(source, boundLets, boundLetRecords, conceptCatalog, diagnostics);
FirmamentV2Document? document = null;
if (modelMatch.Success && unitsMatch.Success && solids.Count > 0)
@@ -965,6 +971,7 @@ public static class FirmamentV2Parser
string source,
IReadOnlyList<FirmamentV2BoundLet> boundLets,
IReadOnlyList<FirmamentV2BoundLetRecord> boundLetRecords,
+ FirmamentV2ForgeConceptCatalog conceptCatalog,
List<string> diagnostics)
{
var manufacturing = new List<FirmamentV2ManufacturingConceptDeclaration>();
@@ -975,7 +982,7 @@ public static class FirmamentV2Parser
if (close < 0) { diagnostics.Add(UnsupportedConstruct); continue; }
var application = new FirmamentV2ConceptApplication(match.Groups["family"].Value, match.Groups["concept"].Value, new(match.Groups["family"].Index, match.Groups["concept"].Index + match.Groups["concept"].Length - match.Groups["family"].Index));
var fields = ParseConceptFields(source[(open + 1)..close], open + 1, diagnostics);
- var bound = ValidateConceptApplication(application, fields, boundLets, boundLetRecords, diagnostics);
+ var bound = ValidateConceptApplication(application, fields, boundLets, boundLetRecords, conceptCatalog, diagnostics);
manufacturing.Add(new(application, fields, new(match.Index, close - match.Index + 1), bound));
}
@@ -987,7 +994,7 @@ public static class FirmamentV2Parser
if (close < 0) { diagnostics.Add(UnsupportedConstruct); continue; }
var application = new FirmamentV2ConceptApplication(match.Groups["family"].Value, match.Groups["concept"].Value, new(match.Groups["family"].Index, match.Groups["concept"].Index + match.Groups["concept"].Length - match.Groups["family"].Index));
var fields = ParseConceptFields(source[(open + 1)..close], open + 1, diagnostics);
- var bound = ValidateConceptApplication(application, fields, boundLets, boundLetRecords, diagnostics);
+ var bound = ValidateConceptApplication(application, fields, boundLets, boundLetRecords, conceptCatalog, diagnostics);
features.Add(new(match.Groups["name"].Value, application, fields, new(match.Index, close - match.Index + 1), bound));
}
@@ -1041,11 +1048,12 @@ public static class FirmamentV2Parser
IReadOnlyList<FirmamentV2ConceptField> fields,
IReadOnlyList<FirmamentV2BoundLet> boundLets,
IReadOnlyList<FirmamentV2BoundLetRecord> boundLetRecords,
+ FirmamentV2ForgeConceptCatalog conceptCatalog,
List<string> diagnostics)
{
- if (!FirmamentV2ForgeConceptRegistry.TryGet(application.FamilyName, application.ConceptName, out var descriptor))
+ if (!conceptCatalog.TryGet(application.FamilyName, application.ConceptName, out var descriptor))
{
- diagnostics.Add(FirmamentV2ForgeConceptRegistry.HasFamily(application.FamilyName) ? ConceptUnknownConcept : ConceptUnknownFamily);
+ diagnostics.Add(conceptCatalog.HasFamily(application.FamilyName) ? ConceptUnknownConcept : ConceptUnknownFamily);
return [];
}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2RuntimeConceptValidation.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2RuntimeConceptValidation.cs
index f9fe13e7..a089fd98 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2RuntimeConceptValidation.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2RuntimeConceptValidation.cs
@@ -5,7 +5,7 @@ using Aetheris.Kernel.Firmament.FirmamentV2.FirmamentInterop;
namespace Aetheris.Kernel.Firmament.FirmamentV2;
public sealed record FirmamentV2RuntimeConceptValidationResult(
- string Provider,
+ FirmamentV2ForgeRuntimeMetadata ForgeRuntime,
IReadOnlyList<FirmamentV2RuntimeConceptValidationEntry> Concepts,
IReadOnlyList<PmiObligation> PmiObligations,
IReadOnlyList<FirmamentDiagnostic> Diagnostics);
@@ -26,16 +26,19 @@ public sealed record FirmamentV2RuntimeConceptValidationEntry(
public static class FirmamentV2RuntimeConceptValidation
{
public static FirmamentV2RuntimeConceptValidationResult Validate(FirmamentV2Document? document)
+ => Validate(document, FirmamentV2ForgeRuntimeConfiguration.CreateDefault());
+
+ public static FirmamentV2RuntimeConceptValidationResult Validate(
+ FirmamentV2Document? document,
+ FirmamentV2ForgeRuntimeConfiguration configuration)
{
+ ArgumentNullException.ThrowIfNull(configuration);
+
if (document is null)
{
- return new FirmamentV2RuntimeConceptValidationResult(string.Empty, [], [], []);
+ return new FirmamentV2RuntimeConceptValidationResult(configuration.Metadata, [], [], []);
}
- var registry = new ForgeConceptRegistry();
- var pack = new StandardForgeRuntimeConceptPack();
- pack.Register(registry);
-
var variables = new FirmamentV2VariablesAdapter(document);
var conceptResults = new List<FirmamentV2RuntimeConceptValidationEntry>();
var obligations = new List<PmiObligation>();
@@ -46,8 +49,7 @@ public static class FirmamentV2RuntimeConceptValidation
ValidateApplication(
FirmamentV2ConceptApplicationAdapter.Adapt(declaration),
variables,
- pack.Id,
- registry,
+ configuration,
conceptResults,
obligations,
diagnostics);
@@ -58,15 +60,14 @@ public static class FirmamentV2RuntimeConceptValidation
ValidateApplication(
FirmamentV2ConceptApplicationAdapter.Adapt(declaration),
variables,
- pack.Id,
- registry,
+ configuration,
conceptResults,
obligations,
diagnostics);
}
return new FirmamentV2RuntimeConceptValidationResult(
- pack.Id,
+ configuration.Metadata,
conceptResults,
obligations,
diagnostics);
@@ -75,17 +76,20 @@ public static class FirmamentV2RuntimeConceptValidation
private static void ValidateApplication(
FirmamentConceptApplicationView application,
IFirmamentVariables variables,
- string provider,
- IForgeRegistry registry,
+ FirmamentV2ForgeRuntimeConfiguration configuration,
ICollection<FirmamentV2RuntimeConceptValidationEntry> conceptResults,
ICollection<PmiObligation> obligations,
ICollection<FirmamentDiagnostic> diagnostics)
{
- if (!registry.TryResolve(application.ConceptId, out var concept))
+ if (!configuration.Registry.TryResolve(application.ConceptId, out var concept))
{
return;
}
+ var provider = configuration.ConceptProviders.TryGetValue(application.ConceptId, out var providerId)
+ ? providerId
+ : configuration.Metadata.BuiltInPack;
+
var context = new ConceptValidationContext(application, variables);
var conceptDiagnostics = concept.Validate(context)
.Distinct()
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
index ec4a16be..0a7ff2dc 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
@@ -6,6 +6,7 @@ namespace Aetheris.Kernel.Firmament.FirmamentV2;
public sealed record FirmamentV2ValidationReport(
string Source,
string Status,
+ FirmamentV2ForgeRuntimeMetadata ForgeRuntime,
IReadOnlyList<FirmamentV2ValidationLet> Lets,
IReadOnlyList<FirmamentV2ValidationConcept> Concepts,
IReadOnlyList<FirmamentV2ValidationPmiRecord> Pmi,
@@ -28,9 +29,14 @@ public sealed record FirmamentV2ValidationConceptPmiObligation(string Kind, stri
public static class FirmamentV2ValidationReportBuilder
{
- public static FirmamentV2ValidationReport Build(FirmamentV2ParseResult parse, string source = "inline")
+ public static FirmamentV2ValidationReport Build(
+ FirmamentV2ParseResult parse,
+ string source = "inline",
+ FirmamentV2RuntimeConceptValidationResult? runtimeValidation = null,
+ FirmamentV2ForgeConceptCatalog? conceptCatalog = null)
{
- var runtimeValidation = FirmamentV2RuntimeConceptValidation.Validate(parse.Document);
+ runtimeValidation ??= FirmamentV2RuntimeConceptValidation.Validate(parse.Document);
+ conceptCatalog ??= FirmamentV2ForgeConceptRegistry.Catalog;
var diagnostics = parse.Diagnostics
.Distinct(StringComparer.Ordinal)
.Select(ToParserDiagnostic)
@@ -42,7 +48,7 @@ public static class FirmamentV2ValidationReportBuilder
var warningCount = diagnostics.Length - fatalCount;
var document = parse.Document;
var lets = document is null ? [] : BuildLets(document);
- var concepts = document is null ? [] : BuildConcepts(document, runtimeValidation);
+ var concepts = document is null ? [] : BuildConcepts(document, runtimeValidation, conceptCatalog);
var pmi = document is null ? [] : BuildPmi(document, diagnostics);
var conceptPmiEvaluation = document is null
? new FirmamentV2ConceptPmiObligationEvaluation([], [])
@@ -73,6 +79,7 @@ public static class FirmamentV2ValidationReportBuilder
return new FirmamentV2ValidationReport(
source,
status,
+ runtimeValidation.ForgeRuntime,
lets,
concepts,
pmi,
@@ -109,7 +116,8 @@ public static class FirmamentV2ValidationReportBuilder
private static IReadOnlyList<FirmamentV2ValidationConcept> BuildConcepts(
FirmamentV2Document document,
- FirmamentV2RuntimeConceptValidationResult runtimeValidation)
+ FirmamentV2RuntimeConceptValidationResult runtimeValidation,
+ FirmamentV2ForgeConceptCatalog conceptCatalog)
{
var runtimeByKey = runtimeValidation.Concepts.ToDictionary(
result => ConceptKey(result.Kind, result.Name, result.Family, result.Concept),
@@ -118,12 +126,12 @@ public static class FirmamentV2ValidationReportBuilder
var rows = new List<FirmamentV2ValidationConcept>();
foreach (var declaration in document.ManufacturingConcepts ?? [])
{
- rows.Add(Concept("manufacturing", null, declaration.Application, declaration.BoundFields ?? [], runtimeByKey));
+ rows.Add(Concept("manufacturing", null, declaration.Application, declaration.BoundFields ?? [], runtimeByKey, conceptCatalog));
}
foreach (var declaration in document.FeatureConcepts ?? [])
{
- rows.Add(Concept("feature", declaration.Name, declaration.Application, declaration.BoundFields ?? [], runtimeByKey));
+ rows.Add(Concept("feature", declaration.Name, declaration.Application, declaration.BoundFields ?? [], runtimeByKey, conceptCatalog));
}
return rows;
@@ -134,7 +142,8 @@ public static class FirmamentV2ValidationReportBuilder
string? name,
FirmamentV2ConceptApplication application,
IReadOnlyList<FirmamentV2BoundConceptField> fields,
- IReadOnlyDictionary<string, FirmamentV2RuntimeConceptValidationEntry> runtimeByKey)
+ IReadOnlyDictionary<string, FirmamentV2RuntimeConceptValidationEntry> runtimeByKey,
+ FirmamentV2ForgeConceptCatalog conceptCatalog)
{
var reportFields = fields
.Select(field => new FirmamentV2ValidationConceptField(
@@ -144,7 +153,7 @@ public static class FirmamentV2ValidationReportBuilder
field.TargetSource ?? field.Field.Source))
.ToArray();
- var parserValid = FirmamentV2ForgeConceptRegistry.TryGet(application.FamilyName, application.ConceptName, out var descriptor)
+ var parserValid = conceptCatalog.TryGet(application.FamilyName, application.ConceptName, out var descriptor)
&& descriptor.Fields.Values.Where(field => field.Required).All(field => reportFields.Any(reportField => reportField.Name == field.Name))
&& reportFields.All(reportField => reportField.Type != "unknown");
diff --git a/Aetheris.slnx b/Aetheris.slnx
index 4b83eb0c..2f9c1456 100644
--- a/Aetheris.slnx
+++ b/Aetheris.slnx
@@ -15,6 +15,8 @@
<Project Path="Aetheris.CLI/Aetheris.CLI.csproj" />
<Project Path="Aetheris.CLI.Tests/Aetheris.CLI.Tests.csproj" />
<Project Path="Aetheris.Kernel.Core.Tests/Aetheris.Kernel.Core.Tests.csproj" />
+ <Project Path="tests/Aetheris.TestForgePack/Aetheris.TestForgePack.csproj" />
+ <Project Path="tests/Aetheris.TestForgePack.Duplicate/Aetheris.TestForgePack.Duplicate.csproj" />
<Project Path="demos/Aetheris.PmiInjectionDemo/Aetheris.PmiInjectionDemo.csproj">
<Build Solution="Debug|*" Project="false" />
</Project>
diff --git a/docs/implementation/forge-cs-a5-trusted-external-concept-packs.md b/docs/implementation/forge-cs-a5-trusted-external-concept-packs.md
new file mode 100644
index 00000000..5ca41fa8
--- /dev/null
+++ b/docs/implementation/forge-cs-a5-trusted-external-concept-packs.md
@@ -0,0 +1,202 @@
+# FORGE-CS-A5 trusted external concept packs
+
+Milestone: **FORGE-CS-A5**
+
+Phase 2 doctrine remains:
+
+```text
+Firmament remains data.
+C# owns logic.
+Forge is the interop boundary.
+```
+
+## Purpose
+
+FORGE-CS-A5 adds **optional trusted local assembly loading** for external C# Forge concept packs during:
+
+```bash
+dotnet run --project Aetheris.CLI -- validate <file.firmament|file.firmfixture> --forge-pack <path-to-pack.dll> --json
+```
+
+Default behavior remains unchanged. Without `--forge-pack`, validation uses only the built-in:
+
+```text
+Aetheris.Standard
+```
+
+## Trust and security contract
+
+Forge concept packs are trusted local code execution.
+Aetheris does not sandbox external packs.
+Do not load packs you do not trust.
+
+Implemented hard policy:
+
+- local file paths only
+- existing `.dll` assemblies only
+- no remote URLs
+- no `file://` URIs
+- no `.cs` source loading
+- no Roslyn compilation
+- no NuGet restore
+- no package-id loading
+- no implicit probing beyond explicit CLI paths
+- no auto-discovery directories
+- no Firmament syntax for importing or executing C#
+
+Firmament remains data. External packs are loaded only because the user explicitly passes `--forge-pack` on the CLI.
+
+## CLI shape
+
+`aetheris validate --help` now advertises:
+
+```text
+--forge-pack <path> Load a trusted local .NET assembly containing IForgeConceptPack implementations. This executes local code; Aetheris does not sandbox external packs. Do not load untrusted packs.
+```
+
+Multiple packs are supported by repeating the flag:
+
+```bash
+aetheris validate part.firmament --forge-pack ./PackA.dll --forge-pack ./PackB.dll --json
+```
+
+Scope remains validation-only. `build` and export paths were not widened.
+
+## Assembly loader
+
+Added loader:
+
+```csharp
+ForgeConceptPackAssemblyLoader
+```
+
+Behavior:
+
+- rejects missing files
+- rejects directory paths
+- rejects URI-style input
+- rejects non-`.dll` paths
+- loads via `AssemblyLoadContext.Default.LoadFromAssemblyPath(...)`
+- finds public non-abstract `IForgeConceptPack` types
+- requires public parameterless constructors
+- instantiates every discovered pack
+- fails clearly when no pack types exist in the assembly
+
+The loader does not claim isolation or unloading. Collectible contexts and plugin sandboxing remain out of scope.
+
+## Registry merge and duplicate policy
+
+Built-ins register first through `Aetheris.Standard`.
+
+External packs then register into the same runtime registry and parser descriptor catalog.
+
+Policy:
+
+- duplicate `ConceptId` is an error
+- built-ins cannot be silently replaced
+- duplicate external concepts are errors
+- error messages name the duplicate concept id and pack
+
+Example failure:
+
+```text
+Forge concept pack 'Aetheris.TestForgePack.Duplicate (...dll)' attempted to register duplicate concept 'hole<Countersink>'.
+```
+
+Override and replacement policy remains deferred.
+
+## Parser integration
+
+The key A5 design issue was real: pre-A5 parser/binder validation rejected unknown concept ids before runtime validation could see them.
+
+A5 implements parser integration by building a combined descriptor catalog from:
+
+- built-in runtime concepts
+- explicitly loaded external runtime concepts
+
+That combined catalog is passed into the existing parser/binder path before concept field validation runs.
+
+Result:
+
+- built-ins still parse exactly as before by default
+- external packs can add new concept ids such as `hole<BossTest>`
+- parser/binder required-field, unknown-field, duplicate-field, and type checks remain active
+- unknown concepts still fail deterministically when no matching trusted pack was loaded
+
+Firmament syntax did not change.
+
+## Report provenance
+
+`firmamentV2Validation` now includes:
+
+```json
+{
+ "forgeRuntime": {
+ "builtInPack": "Aetheris.Standard",
+ "externalPacks": [
+ {
+ "id": "Aetheris.TestForgePack",
+ "version": "1.0.0",
+ "assembly": "Aetheris.TestForgePack.dll"
+ }
+ ]
+ }
+}
+```
+
+Concept rows still expose `runtimeValidation.provider`, and external concepts report the external pack id there.
+
+## Test-only external pack assemblies
+
+Added test-only helper assemblies:
+
+```text
+tests/Aetheris.TestForgePack/
+tests/Aetheris.TestForgePack.Duplicate/
+```
+
+`Aetheris.TestForgePack` provides:
+
+- `TestForgePack`
+- `hole<BossTest>`
+- warning diagnostic `testforge.boss-hole.seen`
+
+`Aetheris.TestForgePack.Duplicate` intentionally collides with built-in `hole<Countersink>` to prove duplicate rejection.
+
+Fixture:
+
+```text
+fixtures/FirmamentV2/Language/invalid/concept-external-boss-hole.invalid.firmfixture
+```
+
+Without `--forge-pack`, it remains invalid with unknown-concept diagnostics.
+With the trusted test pack loaded, the same source becomes valid and reports external provenance.
+
+## Tests
+
+Focused coverage added for:
+
+- `aetheris validate --help` advertising trusted pack loading
+- missing pack path failure
+- assembly-without-pack failure
+- external pack validating external concept ids
+- duplicate built-in collision failure
+- default built-in-only runtime metadata
+- existing A4 PMI-obligation coverage remaining intact
+
+## Explicit non-scope
+
+FORGE-CS-A5 does not add:
+
+- untrusted plugin loading
+- sandboxing
+- Roslyn/source compilation
+- NuGet restore
+- package-manager loading
+- remote loading
+- auto-discovery
+- Firmament imports for C#
+- template behavior
+- document mutation
+- PMI auto-generation
+- AP242 export changes
diff --git a/docs/v2/aetheris-v2-phase2-csharp-interop-scope-contract.md b/docs/v2/aetheris-v2-phase2-csharp-interop-scope-contract.md
index 3a6a262c..62011f02 100644
--- a/docs/v2/aetheris-v2-phase2-csharp-interop-scope-contract.md
+++ b/docs/v2/aetheris-v2-phase2-csharp-interop-scope-contract.md
@@ -2,6 +2,8 @@
Milestone: **V2-PHASE2-L0**
+Status note, July 8 2026: **FORGE-CS-A5 has now implemented trusted local external Forge concept-pack loading for validation only.** The trust boundary in this contract still applies: no sandboxing, no untrusted loading, and no code import from Firmament source.
+
This document opens Aetheris V2.0 Phase 2 with a documentation-only scope contract for **C#-backed Firmament automation and concept authoring**. It is the architecture doctrine future Phase 2 milestones must obey. It does not add runtime behavior, parser behavior, Firmament syntax, C# plugin loading, Roslyn compilation, template generation, geometry generation, AP242 export behavior, or tests.
Phase 1 closed on this manufacturing-intent path:
diff --git a/fixtures/FirmamentV2/Language/invalid/concept-external-boss-hole.invalid.firmfixture b/fixtures/FirmamentV2/Language/invalid/concept-external-boss-hole.invalid.firmfixture
new file mode 100644
index 00000000..0cf41132
--- /dev/null
+++ b/fixtures/FirmamentV2/Language/invalid/concept-external-boss-hole.invalid.firmfixture
@@ -0,0 +1,24 @@
+// fixture-id: concept-external-boss-hole
+// case: forge-cs-a5-external-boss-hole
+// category: Language
+// syntax-version: FirmamentV2
+// validity: invalid
+// implementation: parser-backed
+// expected: invalid
+// expected-stage: validation-report
+// expected-diagnostic: firmament-v2-concept-unknown-concept
+// notes: Without --forge-pack this external concept remains unknown; trusted local pack loading can make the same source valid.
+model ExternalBossHole {
+ units mm
+
+ let BossHole {
+ diameter: length = 6.0mm tol 0.05mm
+ }
+
+ solid part: Box { size: [20, 20, 12] }
+
+ feature boss: hole<BossTest> {
+ target: part.region("bossHole")
+ diameter: BossHole.diameter
+ }
+}
diff --git a/tests/Aetheris.TestForgePack.Duplicate/Aetheris.TestForgePack.Duplicate.csproj b/tests/Aetheris.TestForgePack.Duplicate/Aetheris.TestForgePack.Duplicate.csproj
new file mode 100644
index 00000000..f043597b
--- /dev/null
+++ b/tests/Aetheris.TestForgePack.Duplicate/Aetheris.TestForgePack.Duplicate.csproj
@@ -0,0 +1,12 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>net10.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ <AssemblyName>Aetheris.TestForgePack.Duplicate</AssemblyName>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\..\Aetheris.Forge\Aetheris.Forge.csproj" />
+ </ItemGroup>
+</Project>
diff --git a/tests/Aetheris.TestForgePack.Duplicate/DuplicateCountersinkForgePack.cs b/tests/Aetheris.TestForgePack.Duplicate/DuplicateCountersinkForgePack.cs
new file mode 100644
index 00000000..cac73b49
--- /dev/null
+++ b/tests/Aetheris.TestForgePack.Duplicate/DuplicateCountersinkForgePack.cs
@@ -0,0 +1,36 @@
+using Aetheris.Forge.Abstractions.FirmamentInterop;
+
+namespace Aetheris.TestForgePack.Duplicate;
+
+public sealed class DuplicateCountersinkForgePack : IForgeConceptPack
+{
+ public string Id => "Aetheris.TestForgePack.Duplicate";
+
+ public Version Version => new(1, 0, 0);
+
+ public void Register(IForgeRegistry registry)
+ {
+ ArgumentNullException.ThrowIfNull(registry);
+ registry.Register(new DuplicateCountersinkConcept());
+ }
+}
+
+public sealed class DuplicateCountersinkConcept : IForgeConcept
+{
+ public ConceptId Id => new("hole", "Countersink");
+
+ public void Define(ConceptSchemaBuilder schema)
+ {
+ ArgumentNullException.ThrowIfNull(schema);
+ schema.RequiredTarget("target");
+ schema.RequiredLength("diameter");
+ schema.RequiredLength("countersinkDiameter");
+ schema.RequiredAngle("angle");
+ }
+
+ public IEnumerable<FirmamentDiagnostic> Validate(ConceptValidationContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ yield break;
+ }
+}
diff --git a/tests/Aetheris.TestForgePack/Aetheris.TestForgePack.csproj b/tests/Aetheris.TestForgePack/Aetheris.TestForgePack.csproj
new file mode 100644
index 00000000..50ca6207
--- /dev/null
+++ b/tests/Aetheris.TestForgePack/Aetheris.TestForgePack.csproj
@@ -0,0 +1,12 @@
+<Project Sdk="Microsoft.NET.Sdk">
+ <PropertyGroup>
+ <TargetFramework>net10.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ <AssemblyName>Aetheris.TestForgePack</AssemblyName>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\..\Aetheris.Forge\Aetheris.Forge.csproj" />
+ </ItemGroup>
+</Project>
diff --git a/tests/Aetheris.TestForgePack/TestForgePack.cs b/tests/Aetheris.TestForgePack/TestForgePack.cs
new file mode 100644
index 00000000..b0703c6d
--- /dev/null
+++ b/tests/Aetheris.TestForgePack/TestForgePack.cs
@@ -0,0 +1,37 @@
+using Aetheris.Forge.Abstractions.FirmamentInterop;
+
+namespace Aetheris.TestForgePack;
+
+public sealed class TestForgePack : IForgeConceptPack
+{
+ public string Id => "Aetheris.TestForgePack";
+
+ public Version Version => new(1, 0, 0);
+
+ public void Register(IForgeRegistry registry)
+ {
+ ArgumentNullException.ThrowIfNull(registry);
+ registry.Register(new TestBossHoleConcept());
+ }
+}
+
+public sealed class TestBossHoleConcept : IForgeConcept
+{
+ public ConceptId Id => new("hole", "BossTest");
+
+ public void Define(ConceptSchemaBuilder schema)
+ {
+ ArgumentNullException.ThrowIfNull(schema);
+ schema.RequiredTarget("target");
+ schema.RequiredLength("diameter");
+ }
+
+ public IEnumerable<FirmamentDiagnostic> Validate(ConceptValidationContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ yield return new FirmamentDiagnostic(
+ "testforge.boss-hole.seen",
+ FirmamentDiagnosticSeverity.Warning,
+ "External test forge pack validated hole<BossTest>.");
+ }
+}