Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Implement FORGE-CS-A3 runtime concept validation

Yuechen Li36f1cb6de05b
diff --git a/Aetheris.CLI.Tests/FirmamentV2RuntimeConceptValidationCliTests.cs b/Aetheris.CLI.Tests/FirmamentV2RuntimeConceptValidationCliTests.cs
new file mode 100644
index 00000000..c7dc731f
--- /dev/null
+++ b/Aetheris.CLI.Tests/FirmamentV2RuntimeConceptValidationCliTests.cs
@@ -0,0 +1,74 @@
+using System.Text.Json;
+
+namespace Aetheris.CLI.Tests;
+
+public sealed class FirmamentV2RuntimeConceptValidationCliTests
+{
+ [Fact]
+ public void ValidateJson_InvalidCountersinkFixture_ReturnsNonZeroAndRuntimeDiagnostic()
+ {
+ var fixturePath = FixturePath("Language/invalid/concept-countersink-diameter-order.invalid.firmfixture");
+ var stdout = new StringWriter();
+ var stderr = new StringWriter();
+
+ var exitCode = CliRunner.Run(["validate", fixturePath, "--json"], stdout, stderr);
+
+ Assert.Equal(1, exitCode);
+ Assert.Equal(string.Empty, stderr.ToString());
+
+ using var document = JsonDocument.Parse(stdout.ToString());
+ var validation = document.RootElement.GetProperty("firmamentV2Validation");
+ Assert.Equal("invalid", validation.GetProperty("status").GetString());
+ Assert.Contains(
+ validation.GetProperty("diagnostics").EnumerateArray(),
+ diagnostic => diagnostic.GetProperty("code").GetString() == "forge.hole.countersink.diameter-order"
+ && diagnostic.GetProperty("severity").GetString() == "fatal");
+ }
+
+ [Fact]
+ public void ValidateJson_WarningOnlyFixture_ReturnsZeroAndWarningDiagnostic()
+ {
+ var fixturePath = FixturePath("Language/valid/concept-shaft-missing-tolerance-warning.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 validation = document.RootElement.GetProperty("firmamentV2Validation");
+ Assert.Equal("valid", validation.GetProperty("status").GetString());
+ Assert.Contains(
+ validation.GetProperty("diagnostics").EnumerateArray(),
+ diagnostic => diagnostic.GetProperty("code").GetString() == "forge.hole.shaft.diameter-tolerance-recommended"
+ && diagnostic.GetProperty("severity").GetString() == "warning");
+ }
+
+ [Fact]
+ public void ValidateHelp_DoesNotAdvertiseExternalForgePackLoading()
+ {
+ var stdout = new StringWriter();
+ var stderr = new StringWriter();
+
+ var exitCode = CliRunner.Run(["validate", "--help"], stdout, stderr);
+
+ Assert.Equal(0, exitCode);
+ Assert.Equal(string.Empty, stderr.ToString());
+ Assert.DoesNotContain("--forge-pack", stdout.ToString(), StringComparison.Ordinal);
+ }
+
+ 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.Forge/Abstractions/FirmamentInterop/ForgeConceptRegistry.cs b/Aetheris.Forge/Abstractions/FirmamentInterop/ForgeConceptRegistry.cs
index 47807fb4..724a872a 100644
--- a/Aetheris.Forge/Abstractions/FirmamentInterop/ForgeConceptRegistry.cs
+++ b/Aetheris.Forge/Abstractions/FirmamentInterop/ForgeConceptRegistry.cs
@@ -47,6 +47,7 @@ public sealed class ConceptSchemaBuilder
public ConceptSchemaFieldBuilder RequiredTarget(string name) => Add(name, ConceptSchemaValueKind.Target);
public ConceptSchemaFieldBuilder RequiredLength(string name) => Add(name, ConceptSchemaValueKind.Length);
public ConceptSchemaFieldBuilder RequiredAngle(string name) => Add(name, ConceptSchemaValueKind.Angle);
+ public ConceptSchemaFieldBuilder RequiredMaterial(string name) => Add(name, ConceptSchemaValueKind.Material);
public ConceptSchemaFieldBuilder RequiredString(string name) => Add(name, ConceptSchemaValueKind.String);
public ConceptSchemaFieldBuilder RequiredBool(string name) => Add(name, ConceptSchemaValueKind.Bool);
public ConceptSchemaFieldBuilder RequiredFloat(string name) => Add(name, ConceptSchemaValueKind.Float);
@@ -100,12 +101,70 @@ public enum ConceptSchemaValueKind
Target,
Length,
Angle,
+ Material,
String,
Bool,
Float,
Int
}
-public sealed record ConceptValidationContext(
- FirmamentConceptApplicationView Application,
- IFirmamentVariables Variables);
+public sealed class ConceptValidationContext
+{
+ private readonly IReadOnlyDictionary<string, FirmamentConceptFieldView> fields;
+
+ public ConceptValidationContext(
+ FirmamentConceptApplicationView application,
+ IFirmamentVariables variables)
+ {
+ ArgumentNullException.ThrowIfNull(application);
+ ArgumentNullException.ThrowIfNull(variables);
+
+ Application = application;
+ Variables = variables;
+ fields = application.Fields.ToDictionary(field => field.Name, StringComparer.Ordinal);
+ }
+
+ public FirmamentConceptApplicationView Application { get; }
+
+ public IFirmamentVariables Variables { get; }
+
+ public IReadOnlyDictionary<string, FirmamentConceptFieldView> Fields => fields;
+
+ public bool TryGetField(string name, out FirmamentConceptFieldView field) => fields.TryGetValue(name, out field!);
+
+ public bool TryGetScalar(string name, out FirmamentScalarValue value)
+ {
+ if (TryGetField(name, out var field) && field.Value is FirmamentScalarValue scalar)
+ {
+ value = scalar;
+ return true;
+ }
+
+ value = null!;
+ return false;
+ }
+
+ public bool TryGetNumeric(string name, FirmamentValueKind expectedKind, out double numericValue)
+ {
+ numericValue = 0;
+ if (!TryGetScalar(name, out var value) || value.Kind != expectedKind || value.NumericValue is null)
+ {
+ return false;
+ }
+
+ numericValue = value.NumericValue.Value;
+ return true;
+ }
+
+ public bool TryGetTargetSource(string name, out string targetSource)
+ {
+ if (TryGetField(name, out var field) && !string.IsNullOrWhiteSpace(field.TargetSource))
+ {
+ targetSource = field.TargetSource;
+ return true;
+ }
+
+ targetSource = null!;
+ return false;
+ }
+}
diff --git a/Aetheris.Forge/Standard/CncProcessConcept.cs b/Aetheris.Forge/Standard/CncProcessConcept.cs
new file mode 100644
index 00000000..86d26aa0
--- /dev/null
+++ b/Aetheris.Forge/Standard/CncProcessConcept.cs
@@ -0,0 +1,40 @@
+using Aetheris.Forge.Abstractions.FirmamentInterop;
+
+namespace Aetheris.Forge.Standard;
+
+public sealed class CncProcessConcept : IForgeConcept
+{
+ public ConceptId Id => new("process", "CNC");
+
+ public void Define(ConceptSchemaBuilder schema)
+ {
+ ArgumentNullException.ThrowIfNull(schema);
+ schema.RequiredMaterial("material");
+ schema.RequiredLength("minimumToolRadius");
+ }
+
+ public IEnumerable<FirmamentDiagnostic> Validate(ConceptValidationContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ var diagnostics = new List<FirmamentDiagnostic>();
+
+ if (context.TryGetNumeric("minimumToolRadius", FirmamentValueKind.Length, out var minimumToolRadius)
+ && minimumToolRadius <= 0)
+ {
+ diagnostics.Add(StandardConceptValidationHelpers.Fatal(
+ "forge.process.cnc.minimum-tool-radius-positive",
+ "minimumToolRadius must be greater than zero.",
+ "minimumToolRadius"));
+ }
+
+ if (!StandardConceptValidationHelpers.HasNonEmptyString(context, "material"))
+ {
+ diagnostics.Add(StandardConceptValidationHelpers.Fatal(
+ "forge.process.cnc.material-required",
+ "material is required.",
+ "material"));
+ }
+
+ return diagnostics;
+ }
+}
diff --git a/Aetheris.Forge/Standard/CounterboreHoleConcept.cs b/Aetheris.Forge/Standard/CounterboreHoleConcept.cs
new file mode 100644
index 00000000..f97d3b1e
--- /dev/null
+++ b/Aetheris.Forge/Standard/CounterboreHoleConcept.cs
@@ -0,0 +1,79 @@
+using Aetheris.Forge.Abstractions.FirmamentInterop;
+
+namespace Aetheris.Forge.Standard;
+
+public sealed class CounterboreHoleConcept : IForgeConcept
+{
+ public ConceptId Id => new("hole", "Counterbore");
+
+ public void Define(ConceptSchemaBuilder schema)
+ {
+ ArgumentNullException.ThrowIfNull(schema);
+ schema.RequiredTarget("target");
+ schema.RequiredLength("diameter");
+ schema.RequiredLength("counterboreDiameter");
+ schema.RequiredLength("counterboreDepth");
+ }
+
+ public IEnumerable<FirmamentDiagnostic> Validate(ConceptValidationContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ var diagnostics = new List<FirmamentDiagnostic>();
+
+ var hasDiameter = StandardConceptValidationHelpers.TryGetPositiveLength(
+ context,
+ "diameter",
+ "forge.hole.counterbore.diameter-positive",
+ "diameter must be greater than zero.",
+ diagnostics,
+ out var diameter);
+
+ var hasCounterboreDiameter = StandardConceptValidationHelpers.TryGetPositiveLength(
+ context,
+ "counterboreDiameter",
+ "forge.hole.counterbore.counterbore-diameter-positive",
+ "counterboreDiameter must be greater than zero.",
+ diagnostics,
+ out var counterboreDiameter);
+
+ StandardConceptValidationHelpers.TryGetPositiveLength(
+ context,
+ "counterboreDepth",
+ "forge.hole.counterbore.counterbore-depth-positive",
+ "counterboreDepth must be greater than zero.",
+ diagnostics,
+ out _);
+
+ if (hasDiameter && hasCounterboreDiameter && counterboreDiameter < diameter)
+ {
+ diagnostics.Add(StandardConceptValidationHelpers.Fatal(
+ "forge.hole.counterbore.diameter-order",
+ "counterboreDiameter must be greater than or equal to diameter.",
+ "counterboreDiameter"));
+ }
+
+ if (!StandardConceptValidationHelpers.HasTarget(context, "target"))
+ {
+ diagnostics.Add(StandardConceptValidationHelpers.Fatal(
+ "forge.hole.counterbore.target-required",
+ "target is required.",
+ "target"));
+ }
+
+ StandardConceptValidationHelpers.AddToleranceRecommendation(
+ context,
+ "diameter",
+ "forge.hole.counterbore.diameter-tolerance-recommended",
+ "diameter should include tolerance evidence.",
+ diagnostics);
+
+ StandardConceptValidationHelpers.AddToleranceRecommendation(
+ context,
+ "counterboreDiameter",
+ "forge.hole.counterbore.diameter-tolerance-recommended",
+ "counterboreDiameter should include tolerance evidence.",
+ diagnostics);
+
+ return diagnostics;
+ }
+}
diff --git a/Aetheris.Forge/Standard/CountersinkHoleConcept.cs b/Aetheris.Forge/Standard/CountersinkHoleConcept.cs
new file mode 100644
index 00000000..c70e1400
--- /dev/null
+++ b/Aetheris.Forge/Standard/CountersinkHoleConcept.cs
@@ -0,0 +1,80 @@
+using Aetheris.Forge.Abstractions.FirmamentInterop;
+
+namespace Aetheris.Forge.Standard;
+
+public sealed class CountersinkHoleConcept : 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);
+ var diagnostics = new List<FirmamentDiagnostic>();
+
+ var hasDiameter = StandardConceptValidationHelpers.TryGetPositiveLength(
+ context,
+ "diameter",
+ "forge.hole.countersink.diameter-positive",
+ "diameter must be greater than zero.",
+ diagnostics,
+ out var diameter);
+
+ var hasCountersinkDiameter = StandardConceptValidationHelpers.TryGetPositiveLength(
+ context,
+ "countersinkDiameter",
+ "forge.hole.countersink.countersink-diameter-positive",
+ "countersinkDiameter must be greater than zero.",
+ diagnostics,
+ out var countersinkDiameter);
+
+ if (hasDiameter && hasCountersinkDiameter && countersinkDiameter <= diameter)
+ {
+ diagnostics.Add(StandardConceptValidationHelpers.Fatal(
+ "forge.hole.countersink.diameter-order",
+ "countersinkDiameter must be greater than diameter.",
+ "countersinkDiameter"));
+ }
+
+ if (context.TryGetNumeric("angle", FirmamentValueKind.Angle, out var angle)
+ && (angle <= 0 || angle >= 180))
+ {
+ diagnostics.Add(StandardConceptValidationHelpers.Fatal(
+ "forge.hole.countersink.angle-range",
+ "angle must be greater than 0 degrees and less than 180 degrees.",
+ "angle"));
+ }
+
+ if (!StandardConceptValidationHelpers.HasTarget(context, "target"))
+ {
+ diagnostics.Add(StandardConceptValidationHelpers.Fatal(
+ "forge.hole.countersink.target-required",
+ "target is required.",
+ "target"));
+ }
+
+ StandardConceptValidationHelpers.AddToleranceRecommendation(
+ context,
+ "diameter",
+ "forge.hole.countersink.diameter-tolerance-recommended",
+ "diameter should include tolerance evidence.",
+ diagnostics);
+
+ StandardConceptValidationHelpers.AddToleranceRecommendation(
+ context,
+ "countersinkDiameter",
+ "forge.hole.countersink.diameter-tolerance-recommended",
+ "countersinkDiameter should include tolerance evidence.",
+ diagnostics);
+
+ return diagnostics;
+ }
+}
diff --git a/Aetheris.Forge/Standard/ShaftHoleConcept.cs b/Aetheris.Forge/Standard/ShaftHoleConcept.cs
new file mode 100644
index 00000000..4e40ce15
--- /dev/null
+++ b/Aetheris.Forge/Standard/ShaftHoleConcept.cs
@@ -0,0 +1,46 @@
+using Aetheris.Forge.Abstractions.FirmamentInterop;
+
+namespace Aetheris.Forge.Standard;
+
+public sealed class ShaftHoleConcept : IForgeConcept
+{
+ public ConceptId Id => new("hole", "Shaft");
+
+ public void Define(ConceptSchemaBuilder schema)
+ {
+ ArgumentNullException.ThrowIfNull(schema);
+ schema.RequiredTarget("target");
+ schema.RequiredLength("diameter");
+ }
+
+ public IEnumerable<FirmamentDiagnostic> Validate(ConceptValidationContext context)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ var diagnostics = new List<FirmamentDiagnostic>();
+
+ StandardConceptValidationHelpers.TryGetPositiveLength(
+ context,
+ "diameter",
+ "forge.hole.shaft.diameter-positive",
+ "diameter must be greater than zero.",
+ diagnostics,
+ out _);
+
+ if (!StandardConceptValidationHelpers.HasTarget(context, "target"))
+ {
+ diagnostics.Add(StandardConceptValidationHelpers.Fatal(
+ "forge.hole.shaft.target-required",
+ "target is required.",
+ "target"));
+ }
+
+ StandardConceptValidationHelpers.AddToleranceRecommendation(
+ context,
+ "diameter",
+ "forge.hole.shaft.diameter-tolerance-recommended",
+ "diameter should include tolerance evidence.",
+ diagnostics);
+
+ return diagnostics;
+ }
+}
diff --git a/Aetheris.Forge/Standard/StandardConceptValidationHelpers.cs b/Aetheris.Forge/Standard/StandardConceptValidationHelpers.cs
new file mode 100644
index 00000000..055b65c4
--- /dev/null
+++ b/Aetheris.Forge/Standard/StandardConceptValidationHelpers.cs
@@ -0,0 +1,78 @@
+using Aetheris.Forge.Abstractions.FirmamentInterop;
+
+namespace Aetheris.Forge.Standard;
+
+internal static class StandardConceptValidationHelpers
+{
+ public static FirmamentDiagnostic Fatal(string code, string message, string? fieldName = null) =>
+ new(code, FirmamentDiagnosticSeverity.Fatal, message, FieldName: fieldName);
+
+ public static FirmamentDiagnostic Warning(string code, string message, string? fieldName = null) =>
+ new(code, FirmamentDiagnosticSeverity.Warning, message, FieldName: fieldName);
+
+ public static bool TryGetPositiveLength(
+ ConceptValidationContext context,
+ string fieldName,
+ string code,
+ string message,
+ List<FirmamentDiagnostic> diagnostics,
+ out double numericValue)
+ {
+ numericValue = 0;
+ if (!context.TryGetScalar(fieldName, out var value) || value.Kind != FirmamentValueKind.Length || value.NumericValue is null)
+ {
+ return false;
+ }
+
+ numericValue = value.NumericValue.Value;
+ if (numericValue > 0)
+ {
+ return true;
+ }
+
+ diagnostics.Add(Fatal(code, message, fieldName));
+ return false;
+ }
+
+ public static bool TryGetNumeric(
+ ConceptValidationContext context,
+ string fieldName,
+ FirmamentValueKind expectedKind,
+ out double numericValue)
+ {
+ numericValue = 0;
+ if (!context.TryGetScalar(fieldName, out var value) || value.Kind != expectedKind || value.NumericValue is null)
+ {
+ return false;
+ }
+
+ numericValue = value.NumericValue.Value;
+ return true;
+ }
+
+ public static bool HasTarget(ConceptValidationContext context, string fieldName) =>
+ context.TryGetTargetSource(fieldName, out _);
+
+ public static bool HasNonEmptyString(ConceptValidationContext context, string fieldName)
+ {
+ if (!context.TryGetScalar(fieldName, out var value) || value.Kind != FirmamentValueKind.String)
+ {
+ return false;
+ }
+
+ return value.Nominal is string text && !string.IsNullOrWhiteSpace(text);
+ }
+
+ public static void AddToleranceRecommendation(
+ ConceptValidationContext context,
+ string fieldName,
+ string code,
+ string message,
+ List<FirmamentDiagnostic> diagnostics)
+ {
+ if (context.TryGetScalar(fieldName, out var value) && value.Kind == FirmamentValueKind.Length && value.Tolerance is null)
+ {
+ diagnostics.Add(Warning(code, message, fieldName));
+ }
+ }
+}
diff --git a/Aetheris.Forge/Standard/StandardForgeRuntimeConceptPack.cs b/Aetheris.Forge/Standard/StandardForgeRuntimeConceptPack.cs
new file mode 100644
index 00000000..f3d76ff7
--- /dev/null
+++ b/Aetheris.Forge/Standard/StandardForgeRuntimeConceptPack.cs
@@ -0,0 +1,19 @@
+using Aetheris.Forge.Abstractions.FirmamentInterop;
+
+namespace Aetheris.Forge.Standard;
+
+public sealed class StandardForgeRuntimeConceptPack : IForgeConceptPack
+{
+ public string Id => "Aetheris.Standard";
+
+ public Version Version => new(2, 0, 0);
+
+ public void Register(IForgeRegistry registry)
+ {
+ ArgumentNullException.ThrowIfNull(registry);
+ registry.Register(new CncProcessConcept());
+ registry.Register(new ShaftHoleConcept());
+ registry.Register(new CounterboreHoleConcept());
+ registry.Register(new CountersinkHoleConcept());
+ }
+}
diff --git a/Aetheris.Kernel.Firmament.Tests/ForgeCsA3RuntimeConceptValidationTests.cs b/Aetheris.Kernel.Firmament.Tests/ForgeCsA3RuntimeConceptValidationTests.cs
new file mode 100644
index 00000000..cf1be44d
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/ForgeCsA3RuntimeConceptValidationTests.cs
@@ -0,0 +1,158 @@
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public sealed class ForgeCsA3RuntimeConceptValidationTests
+{
+ [Fact]
+ public void ForgeCsA3_ValidBuiltInConceptFixture_RemainsValidAndReportsRuntimeProvider()
+ {
+ var report = ReportFixture("Language/valid/concept-applications-forge.valid.firmfixture");
+
+ Assert.Equal("valid", report.Status);
+ Assert.DoesNotContain(report.Diagnostics, diagnostic => diagnostic.Severity == "fatal");
+ Assert.All(report.Concepts, concept =>
+ {
+ Assert.NotNull(concept.RuntimeValidation);
+ Assert.Equal("Aetheris.Standard", concept.RuntimeValidation!.Provider);
+ Assert.Equal("valid", concept.RuntimeValidation.Status);
+ Assert.Empty(concept.RuntimeValidation.Diagnostics);
+ });
+ }
+
+ [Fact]
+ public void ForgeCsA3_CountersinkDiameterOrder_IsInvalid()
+ {
+ var report = ReportFixture("Language/invalid/concept-countersink-diameter-order.invalid.firmfixture");
+
+ Assert.Equal("invalid", report.Status);
+ Assert.Contains(report.Diagnostics, diagnostic => diagnostic.Code == "forge.hole.countersink.diameter-order" && diagnostic.Severity == "fatal");
+ Assert.Contains(report.Concepts, concept => concept.Name == "badHole" && concept.Status == "invalid");
+ }
+
+ [Fact]
+ public void ForgeCsA3_CountersinkAngleRange_IsInvalid()
+ {
+ var report = ReportFixture("Language/invalid/concept-countersink-angle-range.invalid.firmfixture");
+
+ Assert.Equal("invalid", report.Status);
+ Assert.Contains(report.Diagnostics, diagnostic => diagnostic.Code == "forge.hole.countersink.angle-range" && diagnostic.Severity == "fatal");
+ }
+
+ [Fact]
+ public void ForgeCsA3_CounterboreDiameterOrder_IsInvalid()
+ {
+ var report = ReportFixture("Language/invalid/concept-counterbore-diameter-order.invalid.firmfixture");
+
+ Assert.Equal("invalid", report.Status);
+ Assert.Contains(report.Diagnostics, diagnostic => diagnostic.Code == "forge.hole.counterbore.diameter-order" && diagnostic.Severity == "fatal");
+ }
+
+ [Theory]
+ [InlineData(
+ """
+ model ZeroShaft {
+ units mm
+ solid part: Box { size: [20, 20, 6] }
+ feature h: hole<Shaft> {
+ target: part.region("holeA")
+ diameter: 0.0mm
+ }
+ }
+ """,
+ "forge.hole.shaft.diameter-positive")]
+ [InlineData(
+ """
+ model ZeroCounterbore {
+ units mm
+ solid part: Box { size: [20, 20, 6] }
+ feature h: hole<Counterbore> {
+ target: part.region("holeA")
+ diameter: 6.0mm tol 0.05mm
+ counterboreDiameter: 8.0mm tol 0.05mm
+ counterboreDepth: 0.0mm
+ }
+ }
+ """,
+ "forge.hole.counterbore.counterbore-depth-positive")]
+ [InlineData(
+ """
+ model ZeroCountersink {
+ units mm
+ solid part: Box { size: [20, 20, 6] }
+ feature h: hole<Countersink> {
+ target: part.region("holeA")
+ diameter: 0.0mm
+ countersinkDiameter: 8.0mm tol 0.05mm
+ angle: 90deg
+ }
+ }
+ """,
+ "forge.hole.countersink.diameter-positive")]
+ public void ForgeCsA3_PositiveDimensionChecks_AreReported(string source, string expectedCode)
+ {
+ var report = ReportSource(source);
+
+ Assert.Equal("invalid", report.Status);
+ Assert.Contains(report.Diagnostics, diagnostic => diagnostic.Code == expectedCode && diagnostic.Severity == "fatal");
+ }
+
+ [Fact]
+ public void ForgeCsA3_MissingToleranceRecommendation_IsWarningOnly()
+ {
+ var report = ReportFixture("Language/valid/concept-shaft-missing-tolerance-warning.valid.firmfixture");
+
+ Assert.Equal("valid", report.Status);
+ Assert.Contains(report.Diagnostics, diagnostic => diagnostic.Code == "forge.hole.shaft.diameter-tolerance-recommended" && diagnostic.Severity == "warning");
+ Assert.Contains(report.Concepts, concept => concept.Name == "h"
+ && concept.RuntimeValidation is not null
+ && concept.RuntimeValidation.Status == "valid"
+ && concept.RuntimeValidation.Diagnostics.Any(diagnostic => diagnostic.Code == "forge.hole.shaft.diameter-tolerance-recommended"));
+ }
+
+ [Fact]
+ public void ForgeCsA3_CncMinimumToolRadius_IsInvalid()
+ {
+ var report = ReportFixture("Language/invalid/concept-cnc-minimum-tool-radius.invalid.firmfixture");
+
+ Assert.Equal("invalid", report.Status);
+ Assert.Contains(report.Diagnostics, diagnostic => diagnostic.Code == "forge.process.cnc.minimum-tool-radius-positive" && diagnostic.Severity == "fatal");
+ }
+
+ [Fact]
+ public void ForgeCsA3_RuntimeValidation_UsesBuiltInStandardPackOnly()
+ {
+ var runtime = FirmamentV2RuntimeConceptValidation.Validate(ParseFixture("Language/valid/concept-applications-forge.valid.firmfixture").Document);
+
+ Assert.Equal("Aetheris.Standard", runtime.Provider);
+ Assert.Equal(2, runtime.Concepts.Count);
+ Assert.All(runtime.Concepts, concept => Assert.Equal("Aetheris.Standard", concept.Provider));
+ }
+
+ private static FirmamentV2ValidationReport ReportFixture(string relative) => Build(ParseFixture(relative), relative);
+
+ private static FirmamentV2ValidationReport ReportSource(string source) => Build(FirmamentV2Parser.Parse(source), "inline");
+
+ private static FirmamentV2ValidationReport Build(FirmamentV2ParseResult parse, string source)
+ {
+ Assert.NotNull(parse.Document);
+ return FirmamentV2ValidationReportBuilder.Build(parse, source);
+ }
+
+ private static FirmamentV2ParseResult ParseFixture(string relative)
+ {
+ var path = Path.Combine(FindRepoRoot(), "fixtures", "FirmamentV2", relative);
+ return FirmamentV2Parser.Parse(File.ReadAllText(path), Path.GetDirectoryName(path));
+ }
+
+ 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/FirmamentV2RuntimeConceptValidation.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2RuntimeConceptValidation.cs
new file mode 100644
index 00000000..60655855
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2RuntimeConceptValidation.cs
@@ -0,0 +1,100 @@
+using Aetheris.Forge.Abstractions.FirmamentInterop;
+using Aetheris.Forge.Standard;
+using Aetheris.Kernel.Firmament.FirmamentV2.FirmamentInterop;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+public sealed record FirmamentV2RuntimeConceptValidationResult(
+ string Provider,
+ IReadOnlyList<FirmamentV2RuntimeConceptValidationEntry> Concepts,
+ IReadOnlyList<FirmamentDiagnostic> Diagnostics);
+
+public sealed record FirmamentV2RuntimeConceptValidationEntry(
+ FirmamentConceptApplicationKind Kind,
+ string? Name,
+ string Family,
+ string Concept,
+ string Provider,
+ IReadOnlyList<FirmamentDiagnostic> Diagnostics)
+{
+ public string Status => Diagnostics.Any(diagnostic => diagnostic.Severity == FirmamentDiagnosticSeverity.Fatal)
+ ? "invalid"
+ : "valid";
+}
+
+public static class FirmamentV2RuntimeConceptValidation
+{
+ public static FirmamentV2RuntimeConceptValidationResult Validate(FirmamentV2Document? document)
+ {
+ if (document is null)
+ {
+ return new FirmamentV2RuntimeConceptValidationResult(string.Empty, [], []);
+ }
+
+ var registry = new ForgeConceptRegistry();
+ var pack = new StandardForgeRuntimeConceptPack();
+ pack.Register(registry);
+
+ var variables = new FirmamentV2VariablesAdapter(document);
+ var conceptResults = new List<FirmamentV2RuntimeConceptValidationEntry>();
+ var diagnostics = new List<FirmamentDiagnostic>();
+
+ foreach (var declaration in document.ManufacturingConcepts ?? [])
+ {
+ ValidateApplication(
+ FirmamentV2ConceptApplicationAdapter.Adapt(declaration),
+ variables,
+ pack.Id,
+ registry,
+ conceptResults,
+ diagnostics);
+ }
+
+ foreach (var declaration in document.FeatureConcepts ?? [])
+ {
+ ValidateApplication(
+ FirmamentV2ConceptApplicationAdapter.Adapt(declaration),
+ variables,
+ pack.Id,
+ registry,
+ conceptResults,
+ diagnostics);
+ }
+
+ return new FirmamentV2RuntimeConceptValidationResult(
+ pack.Id,
+ conceptResults,
+ diagnostics);
+ }
+
+ private static void ValidateApplication(
+ FirmamentConceptApplicationView application,
+ IFirmamentVariables variables,
+ string provider,
+ IForgeRegistry registry,
+ ICollection<FirmamentV2RuntimeConceptValidationEntry> conceptResults,
+ ICollection<FirmamentDiagnostic> diagnostics)
+ {
+ if (!registry.TryResolve(application.ConceptId, out var concept))
+ {
+ return;
+ }
+
+ var conceptDiagnostics = concept.Validate(new ConceptValidationContext(application, variables))
+ .Distinct()
+ .ToArray();
+
+ conceptResults.Add(new FirmamentV2RuntimeConceptValidationEntry(
+ application.Kind,
+ application.Name,
+ application.ConceptId.Family,
+ application.ConceptId.Concept,
+ provider,
+ conceptDiagnostics));
+
+ foreach (var diagnostic in conceptDiagnostics)
+ {
+ diagnostics.Add(diagnostic);
+ }
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
index e2161eef..4f8a727d 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2ValidationReport.cs
@@ -1,4 +1,5 @@
using System.Globalization;
+using Aetheris.Forge.Abstractions.FirmamentInterop;
namespace Aetheris.Kernel.Firmament.FirmamentV2;
@@ -13,11 +14,12 @@ public sealed record FirmamentV2ValidationReport(
FirmamentV2ValidationSummary Summary);
public sealed record FirmamentV2ValidationSummary(int LetCount, int TolerancedLetCount, int ConceptCount, int ValidConceptCount, int PmiRecordCount, int ExportSupportedPmiCount, int ExportDeferredPmiCount, int FatalDiagnosticCount, int WarningDiagnosticCount);
-public sealed record FirmamentV2ValidationDiagnostic(string Code, string Severity, string Message);
+public sealed record FirmamentV2ValidationDiagnostic(string Code, string Severity, string Message, string? FieldName = null, string? Target = null);
public sealed record FirmamentV2ValidationExportSupport(int SupportedPmiCount, int DeferredPmiCount, IReadOnlyDictionary<string, string> Matrix);
public sealed record FirmamentV2ValidationLet(string Name, string Type, string Nominal, FirmamentV2ValidationTolerance? Tolerance, string Source, IReadOnlyList<string> Dependencies, IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics);
public sealed record FirmamentV2ValidationTolerance(string Kind, string Plus, string Minus);
-public sealed record FirmamentV2ValidationConcept(string Kind, string? Name, string Family, string Concept, string Status, string DfmStatus, IReadOnlyList<FirmamentV2ValidationConceptField> Fields, IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics);
+public sealed record FirmamentV2ValidationConceptRuntimeValidation(string Provider, string Status, IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics);
+public sealed record FirmamentV2ValidationConcept(string Kind, string? Name, string Family, string Concept, string Status, string DfmStatus, IReadOnlyList<FirmamentV2ValidationConceptField> Fields, IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics, FirmamentV2ValidationConceptRuntimeValidation? RuntimeValidation = null);
public sealed record FirmamentV2ValidationConceptField(string Name, string Type, bool HasTolerance, string Source);
public sealed record FirmamentV2ValidationPmiRecord(string Kind, string Name, string Status, string ExportSupport, string? Target, IReadOnlyList<string> Targets, IReadOnlyList<string> DatumRefs, FirmamentV2ValidationDimension? Dimension, string? Reason, IReadOnlyList<FirmamentV2ValidationDiagnostic> Diagnostics);
public sealed record FirmamentV2ValidationDimension(string Nominal, FirmamentV2ValidationTolerance? Tolerance);
@@ -26,77 +28,262 @@ public static class FirmamentV2ValidationReportBuilder
{
public static FirmamentV2ValidationReport Build(FirmamentV2ParseResult parse, string source = "inline")
{
- var diagnostics = parse.Diagnostics.Distinct(StringComparer.Ordinal).Select(ToDiagnostic).ToArray();
- var fatalCount = diagnostics.Count(d => d.Severity == "fatal");
+ var runtimeValidation = FirmamentV2RuntimeConceptValidation.Validate(parse.Document);
+ var diagnostics = parse.Diagnostics
+ .Distinct(StringComparer.Ordinal)
+ .Select(ToParserDiagnostic)
+ .Concat(runtimeValidation.Diagnostics.Select(ToRuntimeDiagnostic))
+ .Distinct()
+ .ToArray();
+
+ var fatalCount = diagnostics.Count(diagnostic => diagnostic.Severity == "fatal");
var warningCount = diagnostics.Length - fatalCount;
var document = parse.Document;
var lets = document is null ? [] : BuildLets(document);
- var concepts = document is null ? [] : BuildConcepts(document);
+ var concepts = document is null ? [] : BuildConcepts(document, runtimeValidation);
var pmi = document is null ? [] : BuildPmi(document, diagnostics);
- var supported = pmi.Count(p => p.ExportSupport is "supported" or "supported-when-target-resolves");
- var deferred = pmi.Count(p => p.ExportSupport == "deferred");
+ var supported = pmi.Count(record => record.ExportSupport is "supported" or "supported-when-target-resolves");
+ var deferred = pmi.Count(record => record.ExportSupport == "deferred");
var status = fatalCount > 0 ? "invalid" : deferred > 0 ? "valid-with-deferred-export" : "valid";
- var summary = new FirmamentV2ValidationSummary(lets.Count, lets.Count(l => l.Tolerance is not null), concepts.Count, concepts.Count(c => c.Status == "valid"), pmi.Count, supported, deferred, fatalCount, warningCount);
- return new(source, status, lets, concepts, pmi, new(supported, deferred, ExportMatrix), diagnostics, summary);
+ var summary = new FirmamentV2ValidationSummary(
+ lets.Count,
+ lets.Count(row => row.Tolerance is not null),
+ concepts.Count,
+ concepts.Count(row => row.Status == "valid"),
+ pmi.Count,
+ supported,
+ deferred,
+ fatalCount,
+ warningCount);
+
+ return new FirmamentV2ValidationReport(
+ source,
+ status,
+ lets,
+ concepts,
+ pmi,
+ new FirmamentV2ValidationExportSupport(supported, deferred, ExportMatrix),
+ diagnostics,
+ summary);
}
- private static IReadOnlyList<FirmamentV2ValidationLet> BuildLets(FirmamentV2Document d)
+ private static IReadOnlyList<FirmamentV2ValidationLet> BuildLets(FirmamentV2Document document)
{
var rows = new List<FirmamentV2ValidationLet>();
- foreach (var l in d.BoundLets ?? []) rows.Add(Let(l.Name, l, "let"));
- foreach (var r in d.BoundLetRecords ?? []) foreach (var f in r.Fields.Values) rows.Add(Let($"{r.Name}.{f.Name}", f, "let-record"));
- return rows.OrderBy(l => l.Name, StringComparer.Ordinal).ToArray();
+ foreach (var boundLet in document.BoundLets ?? [])
+ {
+ rows.Add(Let(boundLet.Name, boundLet, "let"));
+ }
+
+ foreach (var record in document.BoundLetRecords ?? [])
+ {
+ foreach (var field in record.Fields.Values)
+ {
+ rows.Add(Let($"{record.Name}.{field.Name}", field, "let-record"));
+ }
+ }
+
+ return rows.OrderBy(row => row.Name, StringComparer.Ordinal).ToArray();
}
- private static IReadOnlyList<string> Dependencies(FirmamentV2BoundLet l) => l.Dependencies is null ? [] : l.Dependencies.Order(StringComparer.Ordinal).ToArray();
+ private static IReadOnlyList<string> Dependencies(FirmamentV2BoundLet boundLet) =>
+ boundLet.Dependencies is null ? [] : boundLet.Dependencies.Order(StringComparer.Ordinal).ToArray();
- private static FirmamentV2ValidationLet Let(string name, FirmamentV2BoundLet l, string source) => new(name, TypeName(l.Type), FormatValue(l.Value), ToTolerance(l.Tolerance), source, Dependencies(l), []);
+ private static FirmamentV2ValidationLet Let(string name, FirmamentV2BoundLet boundLet, string source) =>
+ new(name, TypeName(boundLet.Type), FormatValue(boundLet.Value), ToTolerance(boundLet.Tolerance), source, Dependencies(boundLet), []);
- private static IReadOnlyList<FirmamentV2ValidationConcept> BuildConcepts(FirmamentV2Document d)
+ private static IReadOnlyList<FirmamentV2ValidationConcept> BuildConcepts(
+ FirmamentV2Document document,
+ FirmamentV2RuntimeConceptValidationResult runtimeValidation)
{
+ var runtimeByKey = runtimeValidation.Concepts.ToDictionary(
+ result => ConceptKey(result.Kind, result.Name, result.Family, result.Concept),
+ StringComparer.Ordinal);
+
var rows = new List<FirmamentV2ValidationConcept>();
- foreach (var c in d.ManufacturingConcepts ?? []) rows.Add(Concept("manufacturing", null, c.Application, c.BoundFields ?? []));
- foreach (var c in d.FeatureConcepts ?? []) rows.Add(Concept("feature", c.Name, c.Application, c.BoundFields ?? []));
+ foreach (var declaration in document.ManufacturingConcepts ?? [])
+ {
+ rows.Add(Concept("manufacturing", null, declaration.Application, declaration.BoundFields ?? [], runtimeByKey));
+ }
+
+ foreach (var declaration in document.FeatureConcepts ?? [])
+ {
+ rows.Add(Concept("feature", declaration.Name, declaration.Application, declaration.BoundFields ?? [], runtimeByKey));
+ }
+
return rows;
}
- private static FirmamentV2ValidationConcept Concept(string kind, string? name, FirmamentV2ConceptApplication app, IReadOnlyList<FirmamentV2BoundConceptField> fields)
+ private static FirmamentV2ValidationConcept Concept(
+ string kind,
+ string? name,
+ FirmamentV2ConceptApplication application,
+ IReadOnlyList<FirmamentV2BoundConceptField> fields,
+ IReadOnlyDictionary<string, FirmamentV2RuntimeConceptValidationEntry> runtimeByKey)
{
- var reportFields = fields.Select(f => new FirmamentV2ValidationConceptField(f.Name, f.TargetSource is not null ? "target" : f.BoundValue is null ? "unknown" : TypeName(f.BoundValue.InferredType), f.BoundValue?.AliasTolerance is not null, f.TargetSource ?? f.Field.Source)).ToArray();
- var valid = FirmamentV2ForgeConceptRegistry.TryGet(app.FamilyName, app.ConceptName, out var descriptor) && descriptor.Fields.Values.Where(f => f.Required).All(f => reportFields.Any(r => r.Name == f.Name)) && reportFields.All(f => f.Type != "unknown");
- return new(kind, name, app.FamilyName, app.ConceptName, valid ? "valid" : "invalid", "not-run", reportFields, []);
+ var reportFields = fields
+ .Select(field => new FirmamentV2ValidationConceptField(
+ field.Name,
+ field.TargetSource is not null ? "target" : field.BoundValue is null ? "unknown" : TypeName(field.BoundValue.InferredType),
+ field.BoundValue?.AliasTolerance is not null,
+ field.TargetSource ?? field.Field.Source))
+ .ToArray();
+
+ var parserValid = FirmamentV2ForgeConceptRegistry.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");
+
+ runtimeByKey.TryGetValue(ConceptKey(kind, name, application.FamilyName, application.ConceptName), out var runtime);
+ var runtimeDiagnostics = runtime?.Diagnostics.Select(ToRuntimeDiagnostic).ToArray() ?? [];
+ var runtimeStatus = runtime is null
+ ? null
+ : new FirmamentV2ValidationConceptRuntimeValidation(runtime.Provider, runtime.Status, runtimeDiagnostics);
+
+ var status = !parserValid || runtime?.Status == "invalid" ? "invalid" : "valid";
+
+ return new FirmamentV2ValidationConcept(
+ kind,
+ name,
+ application.FamilyName,
+ application.ConceptName,
+ status,
+ "not-run",
+ reportFields,
+ runtimeDiagnostics,
+ runtimeStatus);
}
- private static IReadOnlyList<FirmamentV2ValidationPmiRecord> BuildPmi(FirmamentV2Document d, IReadOnlyList<FirmamentV2ValidationDiagnostic> diagnostics)
+ private static string ConceptKey(FirmamentConceptApplicationKind kind, string? name, string family, string concept) =>
+ ConceptKey(kind == FirmamentConceptApplicationKind.Manufacturing ? "manufacturing" : "feature", name, family, concept);
+
+ private static string ConceptKey(string kind, string? name, string family, string concept) =>
+ string.Join("|", kind, name ?? string.Empty, family, concept);
+
+ private static IReadOnlyList<FirmamentV2ValidationPmiRecord> BuildPmi(
+ FirmamentV2Document document,
+ IReadOnlyList<FirmamentV2ValidationDiagnostic> diagnostics)
{
- var bound = (d.BoundPmi?.Datums ?? []).Concat(d.BoundPmi?.Dimensions ?? []).Concat(d.BoundPmi?.Controls ?? []).ToDictionary(r => r.Name, StringComparer.Ordinal);
- return (d.PmiBlock?.Records ?? []).Select(r =>
+ var bound = (document.BoundPmi?.Datums ?? [])
+ .Concat(document.BoundPmi?.Dimensions ?? [])
+ .Concat(document.BoundPmi?.Controls ?? [])
+ .ToDictionary(record => record.Name, StringComparer.Ordinal);
+
+ return (document.PmiBlock?.Records ?? []).Select(record =>
{
- bound.TryGetValue(r.Name, out var b);
- var export = ExportSupport(r.Kind, b);
- var itemDiagnostics = b is null ? diagnostics.Where(x => x.Code.StartsWith("firmament-v2-pmi-", StringComparison.Ordinal)).ToArray() : [];
- var status = itemDiagnostics.Any(x => x.Severity == "fatal") ? "invalid" : export == "deferred" ? "export-deferred" : "valid";
- return new FirmamentV2ValidationPmiRecord(KindName(r.Kind), r.Name, status, export, b?.Targets.FirstOrDefault() ?? Field(r, "target"), b?.Targets ?? [], b?.DatumRefs ?? [], Dimension(b), export == "deferred" ? DeferredReason(r.Kind) : null, itemDiagnostics);
+ bound.TryGetValue(record.Name, out var boundRecord);
+ var exportSupport = ExportSupport(record.Kind, boundRecord);
+ var itemDiagnostics = boundRecord is null
+ ? diagnostics.Where(diagnostic => diagnostic.Code.StartsWith("firmament-v2-pmi-", StringComparison.Ordinal)).ToArray()
+ : [];
+ var status = itemDiagnostics.Any(diagnostic => diagnostic.Severity == "fatal")
+ ? "invalid"
+ : exportSupport == "deferred"
+ ? "export-deferred"
+ : "valid";
+
+ return new FirmamentV2ValidationPmiRecord(
+ KindName(record.Kind),
+ record.Name,
+ status,
+ exportSupport,
+ boundRecord?.Targets.FirstOrDefault() ?? Field(record, "target"),
+ boundRecord?.Targets ?? [],
+ boundRecord?.DatumRefs ?? [],
+ Dimension(boundRecord),
+ exportSupport == "deferred" ? DeferredReason(record.Kind) : null,
+ itemDiagnostics);
}).ToArray();
}
- private static FirmamentV2ValidationDimension? Dimension(FirmamentV2BoundPmiRecord? b)
+ private static FirmamentV2ValidationDimension? Dimension(FirmamentV2BoundPmiRecord? boundRecord)
{
- if (b is null) return null;
- if (b.DimensionValue is not null) return new(FormatValue(b.DimensionValue), ToTolerance(b.DimensionTolerance));
- if (b.ControlTolerance is not null) return new(FormatValue(b.ControlTolerance), null);
+ if (boundRecord is null)
+ {
+ return null;
+ }
+
+ if (boundRecord.DimensionValue is not null)
+ {
+ return new FirmamentV2ValidationDimension(FormatValue(boundRecord.DimensionValue), ToTolerance(boundRecord.DimensionTolerance));
+ }
+
+ if (boundRecord.ControlTolerance is not null)
+ {
+ return new FirmamentV2ValidationDimension(FormatValue(boundRecord.ControlTolerance), null);
+ }
+
return null;
}
- private static FirmamentV2ValidationDiagnostic ToDiagnostic(string code) => new(code, FirmamentV2Parser.IsFatalDiagnosticCode(code) ? "fatal" : "warning", Message(code));
- private static string Message(string code) => code switch { FirmamentV2Parser.PmiDimensionMissingTolerance => "PMI dimension resolves to a value without tolerance evidence.", FirmamentV2Parser.ConceptMissingRequiredField => "Forge concept application is missing a required descriptor field.", FirmamentV2Parser.PmiUnknownDatum => "PMI relation references an unknown datum.", FirmamentV2Parser.ToleranceDroppedThroughArithmetic => "A toleranced value was used in arithmetic and only the nominal value was preserved.", _ => code };
- private static FirmamentV2ValidationTolerance? ToTolerance(FirmamentV2Tolerance? t) => t is null ? null : new(t.Kind == FirmamentV2ToleranceKind.Bilateral ? "bilateral" : "asymmetric", FormatNumber(t.Plus) + t.Unit, FormatNumber(t.Minus) + t.Unit);
- private static string FormatValue(FirmamentV2LiteralValue v) => v.Unit is null ? Convert.ToString(v.Value, CultureInfo.InvariantCulture) ?? string.Empty : FormatNumber(v.NumericValue ?? 0) + v.Unit;
+ private static FirmamentV2ValidationDiagnostic ToParserDiagnostic(string code) =>
+ new(code, FirmamentV2Parser.IsFatalDiagnosticCode(code) ? "fatal" : "warning", Message(code));
+
+ private static FirmamentV2ValidationDiagnostic ToRuntimeDiagnostic(FirmamentDiagnostic diagnostic) =>
+ new(
+ diagnostic.Code,
+ diagnostic.Severity switch
+ {
+ FirmamentDiagnosticSeverity.Fatal => "fatal",
+ FirmamentDiagnosticSeverity.Warning => "warning",
+ _ => "info"
+ },
+ diagnostic.Message,
+ diagnostic.FieldName,
+ diagnostic.Target);
+
+ private static string Message(string code) => code switch
+ {
+ FirmamentV2Parser.PmiDimensionMissingTolerance => "PMI dimension resolves to a value without tolerance evidence.",
+ FirmamentV2Parser.ConceptMissingRequiredField => "Forge concept application is missing a required descriptor field.",
+ FirmamentV2Parser.PmiUnknownDatum => "PMI relation references an unknown datum.",
+ FirmamentV2Parser.ToleranceDroppedThroughArithmetic => "A toleranced value was used in arithmetic and only the nominal value was preserved.",
+ _ => code
+ };
+
+ private static FirmamentV2ValidationTolerance? ToTolerance(FirmamentV2Tolerance? tolerance) =>
+ tolerance is null
+ ? null
+ : new(
+ tolerance.Kind == FirmamentV2ToleranceKind.Bilateral ? "bilateral" : "asymmetric",
+ FormatNumber(tolerance.Plus) + tolerance.Unit,
+ FormatNumber(tolerance.Minus) + tolerance.Unit);
+
+ private static string FormatValue(FirmamentV2LiteralValue value) =>
+ value.Unit is null
+ ? Convert.ToString(value.Value, CultureInfo.InvariantCulture) ?? string.Empty
+ : FormatNumber(value.NumericValue ?? 0) + value.Unit;
+
private static string FormatNumber(double value) => value.ToString("0.############", CultureInfo.InvariantCulture);
- private static string TypeName(FirmamentV2PrimitiveType t) => t.ToString().ToLowerInvariant();
- private static string KindName(FirmamentV2PmiKind k) => k switch { FirmamentV2PmiKind.HoleDiameter => "diameter", FirmamentV2PmiKind.DatumPlane => "datum", _ => k.ToString().ToLowerInvariant() };
- private static string? Field(FirmamentV2PmiRecord r, string name) => r.Fields.TryGetValue(name, out var f) ? f.Source : null;
- private static string ExportSupport(FirmamentV2PmiKind kind, FirmamentV2BoundPmiRecord? bound) => kind switch { FirmamentV2PmiKind.DatumPlane or FirmamentV2PmiKind.HoleDiameter => bound is null ? "supported-when-target-resolves" : "supported", _ => "deferred" };
- private static string DeferredReason(FirmamentV2PmiKind kind) => $"AP242 lowering for {KindName(kind)} is not implemented in Phase 1 P1.";
- private static readonly IReadOnlyDictionary<string, string> ExportMatrix = new Dictionary<string, string>(StringComparer.Ordinal) { ["datum"] = "supported-when-target-resolves", ["diameter"] = "supported-when-target-resolves", ["distance"] = "deferred", ["flatness"] = "deferred", ["parallel"] = "deferred", ["perpendicular"] = "deferred", ["coplanar"] = "deferred" };
+
+ private static string TypeName(FirmamentV2PrimitiveType type) => type.ToString().ToLowerInvariant();
+
+ private static string KindName(FirmamentV2PmiKind kind) => kind switch
+ {
+ FirmamentV2PmiKind.HoleDiameter => "diameter",
+ FirmamentV2PmiKind.DatumPlane => "datum",
+ _ => kind.ToString().ToLowerInvariant()
+ };
+
+ private static string? Field(FirmamentV2PmiRecord record, string name) =>
+ record.Fields.TryGetValue(name, out var field) ? field.Source : null;
+
+ private static string ExportSupport(FirmamentV2PmiKind kind, FirmamentV2BoundPmiRecord? boundRecord) => kind switch
+ {
+ FirmamentV2PmiKind.DatumPlane or FirmamentV2PmiKind.HoleDiameter => boundRecord is null ? "supported-when-target-resolves" : "supported",
+ _ => "deferred"
+ };
+
+ private static string DeferredReason(FirmamentV2PmiKind kind) =>
+ $"AP242 lowering for {KindName(kind)} is not implemented in Phase 1 P1.";
+
+ private static readonly IReadOnlyDictionary<string, string> ExportMatrix = new Dictionary<string, string>(StringComparer.Ordinal)
+ {
+ ["datum"] = "supported-when-target-resolves",
+ ["diameter"] = "supported-when-target-resolves",
+ ["distance"] = "deferred",
+ ["flatness"] = "deferred",
+ ["parallel"] = "deferred",
+ ["perpendicular"] = "deferred",
+ ["coplanar"] = "deferred"
+ };
}
diff --git a/docs/implementation/forge-cs-a3-runtime-concept-validation.md b/docs/implementation/forge-cs-a3-runtime-concept-validation.md
new file mode 100644
index 00000000..af6b0604
--- /dev/null
+++ b/docs/implementation/forge-cs-a3-runtime-concept-validation.md
@@ -0,0 +1,182 @@
+# FORGE-CS-A3 runtime concept validation
+
+Milestone: **FORGE-CS-A3**
+
+Phase 2 doctrine remains:
+
+```text
+Firmament remains data.
+C# owns logic.
+Forge is the interop boundary.
+```
+
+## Purpose
+
+FORGE-CS-A3 wires the built-in C# Forge runtime concept validators into the existing Firmament V2 validation/report path used by:
+
+```bash
+dotnet run --project Aetheris.CLI -- validate <file.firmament|file.firmfixture> --json
+```
+
+The goal is narrow Phase 2 behavior change:
+
+- keep the current parser/binder schema validation;
+- run built-in C# concept validators after parse/bind;
+- surface structured runtime concept diagnostics in the existing R1 validation report;
+- keep AP242 export, PMI generation obligations, parser syntax, and concept-pack loading unchanged.
+
+## Invocation flow
+
+The runtime concept validation flow is now:
+
+```text
+FirmamentV2Parser.Parse
+ -> bound FirmamentV2Document
+ -> existing parser/binder schema diagnostics
+ -> FirmamentV2VariablesAdapter
+ -> FirmamentV2ConceptApplicationAdapter
+ -> built-in ForgeConceptRegistry populated by StandardForgeRuntimeConceptPack
+ -> IForgeConcept.Validate(ConceptValidationContext)
+ -> structured FirmamentDiagnostic results
+ -> FirmamentV2ValidationReportBuilder
+ -> firmamentV2Validation JSON
+```
+
+Only the built-in in-process runtime pack is used:
+
+```text
+StandardForgeRuntimeConceptPack
+```
+
+No external pack loading, plugin loading, Roslyn compilation, or parser-registry replacement is introduced.
+
+## Built-in checks
+
+Implemented A3 runtime checks:
+
+- `process<CNC>`
+ - `minimumToolRadius` must be greater than zero.
+ - `material` must be present and non-empty if runtime validation sees it.
+- `hole<Shaft>`
+ - `diameter` must be greater than zero.
+ - `target` must be present.
+ - missing diameter tolerance emits a warning recommendation.
+- `hole<Counterbore>`
+ - `diameter`, `counterboreDiameter`, and `counterboreDepth` must be greater than zero.
+ - `counterboreDiameter` must be greater than or equal to `diameter`.
+ - `target` must be present.
+ - missing diameter/counterbore-diameter tolerance emits warning recommendations.
+- `hole<Countersink>`
+ - `diameter` and `countersinkDiameter` must be greater than zero.
+ - `countersinkDiameter` must be greater than `diameter`.
+ - `angle` must be greater than `0` and less than `180`.
+ - `target` must be present.
+ - missing diameter/countersink-diameter tolerance emits warning recommendations.
+
+## Diagnostic codes and severity policy
+
+Implemented runtime diagnostic codes:
+
+- `forge.process.cnc.minimum-tool-radius-positive` (`fatal`)
+- `forge.process.cnc.material-required` (`fatal`)
+- `forge.hole.shaft.diameter-positive` (`fatal`)
+- `forge.hole.shaft.target-required` (`fatal`)
+- `forge.hole.shaft.diameter-tolerance-recommended` (`warning`)
+- `forge.hole.counterbore.diameter-positive` (`fatal`)
+- `forge.hole.counterbore.counterbore-diameter-positive` (`fatal`)
+- `forge.hole.counterbore.counterbore-depth-positive` (`fatal`)
+- `forge.hole.counterbore.diameter-order` (`fatal`)
+- `forge.hole.counterbore.target-required` (`fatal`)
+- `forge.hole.counterbore.diameter-tolerance-recommended` (`warning`)
+- `forge.hole.countersink.diameter-positive` (`fatal`)
+- `forge.hole.countersink.countersink-diameter-positive` (`fatal`)
+- `forge.hole.countersink.diameter-order` (`fatal`)
+- `forge.hole.countersink.angle-range` (`fatal`)
+- `forge.hole.countersink.target-required` (`fatal`)
+- `forge.hole.countersink.diameter-tolerance-recommended` (`warning`)
+
+Policy:
+
+- parser/binder still owns missing-field, unknown-field, duplicate-field, and type-mismatch diagnostics;
+- runtime C# validators own semantic checks over already-bound values;
+- warnings stay visible and do not make the report invalid;
+- fatal runtime diagnostics make the top-level report status `invalid`.
+
+Because parser-required fields already fail deterministically, the runtime validators are intentionally biased toward semantic checks rather than repeating every parser-required-field error.
+
+## Report integration
+
+`FirmamentV2ValidationReport` keeps the same root shape:
+
+```text
+firmamentV2Validation
+ source
+ status
+ lets[]
+ concepts[]
+ pmi[]
+ exportSupport
+ diagnostics[]
+ summary
+```
+
+A3 extends the report minimally:
+
+- runtime concept diagnostics are appended to the existing top-level `diagnostics[]`;
+- concept rows now include `runtimeValidation` with:
+ - `provider`
+ - `status`
+ - `diagnostics[]`
+- runtime diagnostic rows preserve `code`, `severity`, `message`, and optional `fieldName`/`target`.
+
+Status policy remains:
+
+- any fatal parser or runtime concept diagnostic => `invalid`
+- otherwise any export-deferred PMI => `valid-with-deferred-export`
+- otherwise => `valid`
+
+## CLI behavior
+
+`aetheris validate ... --json` now reports built-in runtime concept validation results through the existing `firmamentV2Validation` payload.
+
+Warning-only runtime findings still return CLI exit code `0`.
+Fatal runtime findings return CLI exit code `1` because the report status becomes `invalid`.
+
+No `--forge-pack` option was added.
+
+## Tests and fixtures
+
+Focused coverage was added for:
+
+- existing valid built-in concept fixture remains valid;
+- countersink diameter-order failure;
+- countersink angle-range failure;
+- counterbore diameter-order failure;
+- positive-value checks;
+- shaft missing-tolerance warning;
+- `process<CNC>.minimumToolRadius` failure;
+- CLI invalid/warning exit behavior;
+- explicit confirmation that validation uses `Aetheris.Standard` built-ins and does not advertise external pack loading.
+
+Added fixtures:
+
+- `fixtures/FirmamentV2/Language/invalid/concept-countersink-diameter-order.invalid.firmfixture`
+- `fixtures/FirmamentV2/Language/invalid/concept-countersink-angle-range.invalid.firmfixture`
+- `fixtures/FirmamentV2/Language/invalid/concept-counterbore-diameter-order.invalid.firmfixture`
+- `fixtures/FirmamentV2/Language/invalid/concept-cnc-minimum-tool-radius.invalid.firmfixture`
+- `fixtures/FirmamentV2/Language/valid/concept-shaft-missing-tolerance-warning.valid.firmfixture`
+
+## Explicit non-scope
+
+FORGE-CS-A3 does not add:
+
+- external concept-pack loading;
+- plugin discovery;
+- Roslyn compilation;
+- template generation;
+- PMI obligation generation;
+- AP242 export changes;
+- parser registry replacement;
+- Firmament syntax changes;
+- document mutation;
+- opaque validator log output.
diff --git a/fixtures/FirmamentV2/Language/invalid/concept-cnc-minimum-tool-radius.invalid.firmfixture b/fixtures/FirmamentV2/Language/invalid/concept-cnc-minimum-tool-radius.invalid.firmfixture
new file mode 100644
index 00000000..d5687ec2
--- /dev/null
+++ b/fixtures/FirmamentV2/Language/invalid/concept-cnc-minimum-tool-radius.invalid.firmfixture
@@ -0,0 +1,23 @@
+// fixture-id: concept-cnc-minimum-tool-radius
+// case: forge-cs-a3-cnc-minimum-tool-radius
+// category: Language
+// syntax-version: FirmamentV2
+// validity: invalid
+
+model CncMinimumToolRadiusInvalid {
+ units mm
+
+ let Process {
+ minimumToolRadius: length = 0.0mm
+ materialName: string = "Aluminum6061"
+ }
+
+ solid part: Box {
+ size: [20, 20, 6]
+ }
+
+ manufacturing process<CNC> {
+ material: Process.materialName
+ minimumToolRadius: Process.minimumToolRadius
+ }
+}
diff --git a/fixtures/FirmamentV2/Language/invalid/concept-counterbore-diameter-order.invalid.firmfixture b/fixtures/FirmamentV2/Language/invalid/concept-counterbore-diameter-order.invalid.firmfixture
new file mode 100644
index 00000000..8975bbfd
--- /dev/null
+++ b/fixtures/FirmamentV2/Language/invalid/concept-counterbore-diameter-order.invalid.firmfixture
@@ -0,0 +1,24 @@
+// fixture-id: concept-counterbore-diameter-order
+// case: forge-cs-a3-counterbore-diameter-order
+// category: Language
+// syntax-version: FirmamentV2
+// validity: invalid
+
+model CounterboreDiameterOrderInvalid {
+ units mm
+
+ let d: length = 8.0mm tol 0.05mm
+ let cbd: length = 6.0mm tol 0.05mm
+ let depth: length = 2.0mm
+
+ solid part: Box {
+ size: [20, 20, 6]
+ }
+
+ feature badHole: hole<Counterbore> {
+ target: part.region("holeA")
+ diameter: d
+ counterboreDiameter: cbd
+ counterboreDepth: depth
+ }
+}
diff --git a/fixtures/FirmamentV2/Language/invalid/concept-countersink-angle-range.invalid.firmfixture b/fixtures/FirmamentV2/Language/invalid/concept-countersink-angle-range.invalid.firmfixture
new file mode 100644
index 00000000..8c67ff34
--- /dev/null
+++ b/fixtures/FirmamentV2/Language/invalid/concept-countersink-angle-range.invalid.firmfixture
@@ -0,0 +1,23 @@
+// fixture-id: concept-countersink-angle-range
+// case: forge-cs-a3-countersink-angle-range
+// category: Language
+// syntax-version: FirmamentV2
+// validity: invalid
+
+model CountersinkAngleRangeInvalid {
+ units mm
+
+ let d: length = 6.0mm tol 0.05mm
+ let csd: length = 10.0mm tol 0.05mm
+
+ solid part: Box {
+ size: [20, 20, 6]
+ }
+
+ feature badHole: hole<Countersink> {
+ target: part.region("holeA")
+ diameter: d
+ countersinkDiameter: csd
+ angle: 180deg
+ }
+}
diff --git a/fixtures/FirmamentV2/Language/invalid/concept-countersink-diameter-order.invalid.firmfixture b/fixtures/FirmamentV2/Language/invalid/concept-countersink-diameter-order.invalid.firmfixture
new file mode 100644
index 00000000..5a2aea97
--- /dev/null
+++ b/fixtures/FirmamentV2/Language/invalid/concept-countersink-diameter-order.invalid.firmfixture
@@ -0,0 +1,23 @@
+// fixture-id: concept-countersink-diameter-order
+// case: forge-cs-a3-countersink-diameter-order
+// category: Language
+// syntax-version: FirmamentV2
+// validity: invalid
+
+model CountersinkDiameterOrderInvalid {
+ units mm
+
+ let d: length = 10.0mm tol 0.05mm
+ let csd: length = 8.0mm tol 0.05mm
+
+ solid part: Box {
+ size: [20, 20, 6]
+ }
+
+ feature badHole: hole<Countersink> {
+ target: part.region("holeA")
+ diameter: d
+ countersinkDiameter: csd
+ angle: 90deg
+ }
+}
diff --git a/fixtures/FirmamentV2/Language/valid/concept-shaft-missing-tolerance-warning.valid.firmfixture b/fixtures/FirmamentV2/Language/valid/concept-shaft-missing-tolerance-warning.valid.firmfixture
new file mode 100644
index 00000000..06222b20
--- /dev/null
+++ b/fixtures/FirmamentV2/Language/valid/concept-shaft-missing-tolerance-warning.valid.firmfixture
@@ -0,0 +1,18 @@
+// fixture-id: concept-shaft-missing-tolerance-warning
+// case: forge-cs-a3-shaft-missing-tolerance-warning
+// category: Language
+// syntax-version: FirmamentV2
+// validity: valid
+
+model ShaftMissingToleranceWarning {
+ units mm
+
+ solid part: Box {
+ size: [20, 20, 6]
+ }
+
+ feature h: hole<Shaft> {
+ target: part.region("holeA")
+ diameter: 6.0mm
+ }
+}