Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Improve CLI help and source diagnostic reporting
Yuechen Liaaaa2cce756e
diff --git a/Aetheris.CLI.Tests/CliHelpAndUsageTests.cs b/Aetheris.CLI.Tests/CliHelpAndUsageTests.csindex a43404e0..3edac45f 100644--- a/Aetheris.CLI.Tests/CliHelpAndUsageTests.cs+++ b/Aetheris.CLI.Tests/CliHelpAndUsageTests.cs@@ -34,6 +34,15 @@ public sealed class CliHelpAndUsageTests[Theory][InlineData("build")]+ [InlineData("format")]+ [InlineData("mesh")]+ [InlineData("lock")]+ [InlineData("measure")]+ [InlineData("inspect-3dm")]+ [InlineData("recover-3dm")]+ [InlineData("fea")]+ [InlineData("drawing")]+ [InlineData("scene")][InlineData("canon")][InlineData("asm")][InlineData("asm", "export")]diff --git a/Aetheris.CLI.Tests/ReleaseAdmissionRegressionTests.cs b/Aetheris.CLI.Tests/ReleaseAdmissionRegressionTests.csindex 6ddae095..31419327 100644--- a/Aetheris.CLI.Tests/ReleaseAdmissionRegressionTests.cs+++ b/Aetheris.CLI.Tests/ReleaseAdmissionRegressionTests.cs@@ -110,6 +110,52 @@ public sealed class ReleaseAdmissionRegressionTestsAssert.Equal(JsonValueKind.Null, diagnostic.GetProperty("sourceSpan").ValueKind);}+ [Theory]+ [InlineData("build")]+ [InlineData("measure")]+ [InlineData("verify")]+ [InlineData("format")]+ [InlineData("lock")]+ [InlineData("mesh")]+ public void MissingInputTextIsShortAndActionable(string verb)+ {+ var missing = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".firmament");+ var stdout = new StringWriter(); var stderr = new StringWriter();+ Assert.Equal(1, CliRunner.Run([verb, missing], stdout, stderr));+ Assert.Empty(stdout.ToString());+ Assert.Contains("source-file-not-found", stderr.ToString());+ Assert.Contains(missing, stderr.ToString());+ Assert.DoesNotContain("Exception", stderr.ToString());+ Assert.InRange(stderr.ToString().Split('\n', StringSplitOptions.RemoveEmptyEntries).Length, 1, 2);+ }++ [Theory]+ [InlineData("Regression/FeatureAccounting/extrude-hole.firmament", "to: 8mm", "to: 8deg", "to")]+ [InlineData("Canonical/SectionChain/explicit-sketch-ruled.firmament", "position: [2mm, -2mm]", "position: [2mm, -2deg]", "position")]+ public void WrongUnitsAreReportedAtTheField(string fixture, string before, string after, string field)+ {+ var source = File.ReadAllText(Path.Combine(Root(), "fixtures", fixture)).Replace(before, after);+ var directory = Directory.CreateTempSubdirectory("aetheris-wrong-unit-").FullName;+ try+ {+ var path = Path.Combine(directory, "wrong-unit.firmament"); File.WriteAllText(path, source);+ foreach (var verb in new[] { "validate", "build" })+ {+ var result = Run(verb, path);+ Assert.Equal(1, result.Exit);+ using var json = JsonDocument.Parse(result.Output);+ var payload = json.RootElement.TryGetProperty("firmamentV2Validation", out var validation) ? validation : json.RootElement;+ var diagnostic = Assert.Single(payload.GetProperty("diagnostics").EnumerateArray(),+ d => d.GetProperty("code").GetString()!.StartsWith("firmament-v2-field-unit-mismatch"));+ Assert.Contains("requires mm; received deg", diagnostic.GetProperty("message").GetString());+ var span = diagnostic.GetProperty("sourceSpan");+ var text = source.Substring(span.GetProperty("start").GetInt32(), span.GetProperty("length").GetInt32());+ Assert.Contains(field + ":", text, StringComparison.OrdinalIgnoreCase);+ }+ }+ finally { Directory.Delete(directory, true); }+ }+private static (int Exit, string Output) Run(string verb, string path, string? output = null){var stdout = new StringWriter();diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 61acc091..8e21ed21 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -190,6 +190,14 @@ public static class CliRunnerpublic static int Run(string[] args, TextWriter stdout, TextWriter stderr)=> Run(args, stdout, stderr, new SystemCadmataProcessLauncher(), AppContext.BaseDirectory);+ private static int WriteThreeDmHelp(string operation, TextWriter stdout)+ {+ CommandHelp.Write(stdout, $"aetheris-3dm {operation} <model.3dm> [--json]",+ "3DM interoperability is an optional tool. Install it with: dotnet tool install --global Aetheris.ThreeDm.CLI --prerelease",+ $"aetheris-3dm {operation} model.3dm --json");+ return 0;+ }+private static int MissingThreeDmTool(TextWriter stderr){stderr.WriteLine("aetheris-3dm-required: 3DM interoperability is an optional tool. Install with 'dotnet tool install --global Aetheris.ThreeDm.CLI --prerelease', then use 'aetheris-3dm inspect' or 'aetheris-3dm recover'.");@@ -230,8 +238,8 @@ public static class CliRunner"lock" => DependencyLockCommand.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),"inspect" => RunInspect(args.Skip(1).ToArray(), stdout, stderr),"measure" => FirmamentMeasureCommand.Run(args.Skip(1).ToArray(), stdout, stderr, JsonOptions),- "inspect-3dm" => MissingThreeDmTool(stderr),- "recover-3dm" => MissingThreeDmTool(stderr),+ "inspect-3dm" => args.Length == 2 && IsHelpFlag(args[1]) ? WriteThreeDmHelp("inspect", stdout) : MissingThreeDmTool(stderr),+ "recover-3dm" => args.Length == 2 && IsHelpFlag(args[1]) ? WriteThreeDmHelp("recover", stdout) : MissingThreeDmTool(stderr),"inspect-profile" => RunInspectProfile(args.Skip(1).ToArray(), stdout, stderr),"inspect-spans" => RunInspectSpans(args.Skip(1).ToArray(), stdout, stderr),"inspect-compose" => RunInspectCompose(args.Skip(1).ToArray(), stdout, stderr),@@ -280,7 +288,7 @@ public static class CliRunnerprivate static int RunFormat(string[] args, TextWriter stdout, TextWriter stderr){const string usage = "Usage: aetheris format <file.firmament|file.firmasm>... [--write] [--json] (convention spellings; preserves layout and authored identities)";- if (args.Length == 0 || IsHelpFlag(args[0])) { stdout.WriteLine(usage); return args.Length == 0 ? 1 : 0; }+ if (args.Length == 0 || IsHelpFlag(args[0])) { CommandHelp.Write(stdout, usage, "Format canonical Firmament spellings while preserving layout and authored names. Add --write to update the source.", "aetheris format bracket.firmament --write"); return args.Length == 0 ? 1 : 0; }var write = args.Contains("--write", StringComparer.Ordinal);var json = args.Contains("--json", StringComparer.Ordinal);var paths = args.Where(a => a is not ("--write" or "--json")).ToArray();@@ -601,6 +609,7 @@ public static class CliRunnergeometryAssertions = build.Value.Export.GeometryAssertions,features = build.Value.Export.Features,engineeringFeatures = build.Value.Export.EngineeringFeatures,+ materializedFeatures = build.Value.Export.MaterializedFeatures,edgeFinishPlanning = build.Value.Export.EdgeFinishPlanning,patterns = build.Value.Export.Patterns,perforation = build.Value.Export.Perforation,@@ -673,8 +682,12 @@ public static class CliRunnervar authored = SectionChainAuthoringParser.CompileFile(witness);if (!authored.IsSuccess || authored.Chain is null || authored.Materialization is null){- var failure = new { command = $"section-chain {operation}", success = false, input = Path.GetFullPath(witness), diagnostics = authored.Diagnostics };- if (json) stdout.WriteLine(JsonSerializer.Serialize(failure, JsonOptions)); else foreach (var diagnostic in authored.Diagnostics) stderr.WriteLine("error: " + diagnostic);+ var source = File.ReadAllText(witness);+ var diagnostics = authored.Diagnostics.Select(message => FirmamentBuildAdmissionValidation.Present(+ new KernelDiagnostic(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, message, "Firmament.SectionChain"), witness, source)).ToArray();+ var failure = new { command = $"section-chain {operation}", success = false, input = Path.GetFullPath(witness), diagnostics };+ if (json) stdout.WriteLine(JsonSerializer.Serialize(failure, JsonOptions));+ else WriteFrontendDiagnostics(diagnostics, stderr);return 1;}chain = authored.Chain; materialized = authored.Materialization;@@ -1197,7 +1210,7 @@ Model CanonicalPanel {if (args.Length > 0 && args[0] is not ("compile" or "generate") && !IsHelpFlag(args[0])) return DrawingNotesCli.Run(args, stdout, stderr);if (args.Length == 0 || IsHelpFlag(args[0])){- (args.Length == 0 ? stderr : stdout).WriteLine(DrawingUsage);+ CommandHelp.Write(args.Length == 0 ? stderr : stdout, DrawingUsage, "Compile an authored drawing or generate dimensioned drawing artifacts from a model. Rendering existing PDFs requires the optional drawing-notes renderer.", "aetheris drawing generate bracket.firmament --out-dir artifacts/local/drawing");return args.Length == 0 ? 1 : 0;}if (args[0] is not ("compile" or "generate") || args.Length < 2)@@ -1254,7 +1267,7 @@ Model CanonicalPanel {private static int RunFea(string[] args, TextWriter stdout, TextWriter stderr){- if (args.Length == 0 || IsHelpFlag(args[0])) { stdout.WriteLine(FeaUsage); return args.Length == 0 ? 1 : 0; }+ if (args.Length == 0 || IsHelpFlag(args[0])) { CommandHelp.Write(stdout, FeaUsage, "Run the bounded engineering analysis declared by a Firmament source and save its reports.", "aetheris fea checked-part.firmament --out-dir artifacts/local/analysis --json"); return args.Length == 0 ? 1 : 0; }var input = Path.GetFullPath(args[0]); string? outDir = null; var json = false;Vector3D? rotationDegrees=null;(int X,int Y,int Z)? latticeOverride=null;ExperimentalPreconditionerKind? experimentalPreconditioner=null;bool? experimentalEquilibration=null;for (var index = 1; index < args.Length; index++){@@ -1364,7 +1377,7 @@ Model CanonicalPanel {private static int RunMesh(string[] args, TextWriter stdout, TextWriter stderr){- if (args.Length == 0 || IsHelpFlag(args[0])) { stdout.WriteLine(MeshUsage); return args.Length == 0 ? 1 : 0; }+ if (args.Length == 0 || IsHelpFlag(args[0])) { CommandHelp.Write(stdout, MeshUsage, "Build or import a part and export a display mesh. The target format must be admitted by the compiled product.", "aetheris mesh bracket.firmament --format stl --output bracket.stl"); return args.Length == 0 ? 1 : 0; }var input = args[0]; var format = "stl"; string? output = null; string? debugIr = null; var json = false;for (var i = 1; i < args.Length; i++){@@ -5506,7 +5519,7 @@ Model CanonicalPanel {private static void WriteViewHelp(TextWriter stdout){- stdout.WriteLine("Open a STEP model in Cadmata.");+ stdout.WriteLine("Build and open Firmament, or open an existing STEP model, in Cadmata.");stdout.WriteLine("Firmament input is built to its adjacent .step artifact before launch; STEP input opens directly.");stdout.WriteLine();stdout.WriteLine(ViewUsage);diff --git a/Aetheris.CLI/CommandHelp.cs b/Aetheris.CLI/CommandHelp.csnew file mode 100644index 00000000..ec90f68b--- /dev/null+++ b/Aetheris.CLI/CommandHelp.cs@@ -0,0 +1,14 @@+namespace Aetheris.CLI;++internal static class CommandHelp+{+ internal static void Write(TextWriter output, string usage, string description, string example)+ {+ output.WriteLine(description);+ output.WriteLine();+ output.WriteLine(usage.StartsWith("Usage:", StringComparison.Ordinal) ? usage : "Usage: " + usage);+ output.WriteLine();+ output.WriteLine("Options are listed in the usage above. -h, --help shows this help.");+ output.WriteLine("Example: " + example);+ }+}diff --git a/Aetheris.CLI/DependencyLockCommand.cs b/Aetheris.CLI/DependencyLockCommand.csindex b8967bfe..a76daab9 100644--- a/Aetheris.CLI/DependencyLockCommand.cs+++ b/Aetheris.CLI/DependencyLockCommand.cs@@ -12,7 +12,7 @@ internal static class DependencyLockCommand{const string usage = "Usage: aetheris lock <root.firmament|root.firmasm> [--update] [--json]";if (args.Length == 0 || args[0] is "--help" or "-h")- { (args.Length == 0 ? stderr : stdout).WriteLine(usage); return args.Length == 0 ? 1 : 0; }+ { CommandHelp.Write(args.Length == 0 ? stderr : stdout, usage, "Inspect local module dependencies; --update writes the optional lockfile with current content hashes.", "aetheris lock assembly.firmasm --update --json"); return args.Length == 0 ? 1 : 0; }var json = args.Contains("--json");if (args.Skip(1).Any(a => a is not ("--update" or "--json"))) { stderr.WriteLine(usage); return 1; }var inspected = FirmamentDependencies.InspectFile(args[0], args.Contains("--update"));diff --git a/Aetheris.CLI/FirmamentMeasureCommand.cs b/Aetheris.CLI/FirmamentMeasureCommand.csindex 48ead35d..9b08cb50 100644--- a/Aetheris.CLI/FirmamentMeasureCommand.cs+++ b/Aetheris.CLI/FirmamentMeasureCommand.cs@@ -13,7 +13,7 @@ internal static class FirmamentMeasureCommandinternal static int Run(string[] args, TextWriter stdout, TextWriter stderr, JsonSerializerOptions jsonOptions){if (args.Length == 0 || args[0] is "--help" or "-h")- { (args.Length == 0 ? stderr : stdout).WriteLine(Usage); return args.Length == 0 ? 1 : 0; }+ { CommandHelp.Write(args.Length == 0 ? stderr : stdout, Usage, "Compile a part and report authoritative geometry measurements for inspection or assertions.", "aetheris measure bracket.firmament --json"); return args.Length == 0 ? 1 : 0; }var json = args.Contains("--json"); var sdf = false; var mesh = false; double? error = null;for (var i = 1; i < args.Length; i++)switch (args[i])diff --git a/Aetheris.CLI/SceneCommand.cs b/Aetheris.CLI/SceneCommand.csindex 0a839507..35ab66e7 100644--- a/Aetheris.CLI/SceneCommand.cs+++ b/Aetheris.CLI/SceneCommand.cs@@ -10,7 +10,7 @@ internal static class SceneCommandinternal const string Usage="aetheris scene <inspect|export-usd|export-glb> <scene.firmament> [out.usda|out.glb] [--repeat 1..16] [--hide-boundary room.boundary] [--json]";internal static int Run(string[] args,TextWriter stdout,TextWriter stderr){- if (args.Length == 0 || args[0] is "--help" or "-h") { stdout.WriteLine(Usage); return args.Length == 0 ? 1 : 0; }+ if (args.Length == 0 || args[0] is "--help" or "-h") { CommandHelp.Write(stdout, Usage, "Inspect a Scene or export its placed display products to GLB or USDA.", "aetheris scene export-glb room.firmament room.glb"); return args.Length == 0 ? 1 : 0; }try{if (args.Length < 2 || args[0] is not ("inspect" or "export-usd" or "export-glb")) throw new ArgumentException(Usage);diff --git a/Aetheris.Kernel.Core/Step242/Step242Importer.cs b/Aetheris.Kernel.Core/Step242/Step242Importer.csindex a55ac187..8725db2a 100644--- a/Aetheris.Kernel.Core/Step242/Step242Importer.cs+++ b/Aetheris.Kernel.Core/Step242/Step242Importer.cs@@ -690,7 +690,9 @@ public static class Step242Importer}var body = new BrepBody(builder.Model, geometry, bindings, vertexMap.Values.ToDictionary(entry => entry.VertexId, entry => entry.Point), shellRepresentation: shellRepresentation);- var orientation = StepFaceOrientationResolver.Resolve(body, importedFacePatches, supportAlignedBoundary, supportAlignedLoopBoundary);+ KernelResult<BrepBody> orientation;+ using (BuildPerfTrace.Phase("step.orientation-qualification"))+ orientation = StepFaceOrientationResolver.Resolve(body, importedFacePatches, supportAlignedBoundary, supportAlignedLoopBoundary);if (!orientation.IsSuccess){return KernelResult<BrepBody>.Failure(shellRoleDiagnostics@@ -719,6 +721,7 @@ public static class Step242Importerif (orientation.Value.Topology.Coedges.Any(coedge =>!orientation.Value.Bindings.TryGetPcurveBinding(coedge.Id, out _))){+ using var recoveryPhase = BuildPerfTrace.Phase("step.pcurve-recovery-and-qualification");var recovery = BrepPcurveRecovery.Populate(orientation.Value.Topology, orientation.Value.Geometry, orientation.Value.Bindings,tolerance: document.PcurveQualificationToleranceMillimetres);diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentFeatureAccountingTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentFeatureAccountingTests.csnew file mode 100644index 00000000..dd8189a6--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentFeatureAccountingTests.cs@@ -0,0 +1,114 @@+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Core.Step242;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentFeatureAccountingTests+{+ private static string Fixture(string relative) => Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../fixtures", relative));++ [Theory]+ [InlineData("Regression/FrontendX4/cases/e01-pocket-through.firmament", "Body", "Pocket", "Slot")]+ [InlineData("Regression/DemoRegression/concept-materialization-m2.firmament", "Base", "Hole", "LeftMount")]+ [InlineData("Canonical/Pipeline/manual-profile-parity.firmament", "Body", "Remove", "ThroughCutout")]+ [InlineData("Canonical/Pipeline/profile-pipeline-flagship.firmament", "Body", "Remove", "ThroughCutout")]+ [InlineData("Regression/FeatureAccounting/extrude-hole.firmament", "Body", "Hole", "Mount")]+ [InlineData("Canonical/Features/Composition/box-counterbore-chamfer.firmament", "Base", "EdgeFinish", "TopBreak")]+ [InlineData("Regression/CanonicalGeometry/profile-compose-l-bracket-external-modify-counterbore.firmament", "BracketBody", "Hole", "LocatingPin")]+ [InlineData("Regression/FeatureAccounting/coaxial.firmament", "Body", "EdgeFinish", "tip")]+ [InlineData("Canonical/Features/EdgeFinish/semantic-selection-chamfer.firmament", "MainPlate", "EdgeFinish", "TopEdgeBreak")]+ [InlineData("Canonical/Patterns/four-hole-pattern.firmament", "Plate", "Hole", "MountPattern_0")]+ [InlineData("Regression/CanonicalGeometry/profile-chamfer-reflex-junction-top.firmament", "Body", "EdgeFinish", "ReflexTopBreak")]+ [InlineData("Canonical/Perforation/cylindrical-grid-8.firmament", "Body", "Perforation", "Vents")]+ public void RealRoutesAccountForExecutedFeatures(string relative, string host, string kind, string name)+ {+ var path = Fixture(relative);+ var source = File.ReadAllText(path);+ var built = FirmamentBuildAndExport.CompileSource(source, Path.GetDirectoryName(path));+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));+ Assert.Contains(new FirmamentFeatureReceipt(host, kind, name), built.Value.MaterializedFeatures);+ var validation = FirmamentBuildAdmissionValidation.Admit(+ FirmamentV2ValidationReportBuilder.Build(FirmamentV2Parser.Parse(source), path), source, Path.GetDirectoryName(path));+ Assert.NotEqual("invalid", validation.Status);+ }++ [Fact]+ public void CompatibilityKindCasingDoesNotDuplicateMissingFeatureDiagnostics()+ {+ var source = File.ReadAllText(Fixture("Regression/DemoRegression/concept-materialization-m2.firmament"));+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));+ var result = FirmamentFeatureAccounting.Verify(FirmamentV2Parser.Parse(source), source,+ built.Value with { MaterializedFeatures = built.Value.MaterializedFeatures.Where(r => r.Name != "LeftMount").ToArray() });+ Assert.False(result.IsSuccess);+ var diagnostic = Assert.Single(result.Diagnostics);+ Assert.Contains("LeftMount", diagnostic.Message);+ }++ [Fact]+ public void ImportedGeometryAndPmiDoNotInventMaterialFeatures()+ {+ var path = Fixture("Regression/ImportedPartPmi/annotated-part.firmament");+ var source = File.ReadAllText(path);+ var built = FirmamentBuildAndExport.CompileSource(source, Path.GetDirectoryName(path));+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));+ Assert.Empty(built.Value.MaterializedFeatures);+ Assert.NotEmpty(built.Value.DatumInspection!);+ }++ [Theory]+ [InlineData(false)]+ [InlineData(true)]+ public void OldBareExtrudeResultCannotSatisfyHoleSourceEvenWithAuthoredDisplayReports(bool importedLibrary)+ {+ var source = (importedLibrary ? "Use Profile.Modifications;\n" : "")+ + File.ReadAllText(Fixture("Regression/FeatureAccounting/extrude-hole.firmament"));+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.True(parsed.IsSuccess);+ var full = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(full.IsSuccess, string.Join("; ", full.Diagnostics.Select(d => d.Message)));+ var bare = FirmamentBuildAndExport.CompileSource(source[..source.IndexOf(" Modify", StringComparison.Ordinal)] + "}");+ Assert.True(bare.IsSuccess);+ Assert.NotEqual(full.Value.StepText, bare.Value.StepText);+ // Simulates the old producer returning the prism and attaching source-derived reports.+ var rejected = FirmamentFeatureAccounting.Verify(parsed, source, bare.Value with+ { Features = full.Value.Features, EngineeringFeatures = full.Value.EngineeringFeatures });+ Assert.False(rejected.IsSuccess);+ var error = Assert.Single(rejected.Diagnostics);+ Assert.StartsWith("firmament-feature-not-materialized:Hole:Mount:", error.Message);+ Assert.NotNull(error.OriginalSourceSpan);+ Assert.Equal("Mount", source.Substring(error.OriginalSourceSpan.Start, error.OriginalSourceSpan.Length));+ }++ [Fact]+ public void DifferentFeatureKindsWithTheSameNameNeedIndependentReceipts()+ {+ var source = File.ReadAllText(Fixture("Regression/FeatureAccounting/same-name-different-kinds.firmament"));+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));+ Assert.Contains(new FirmamentFeatureReceipt("Body", "Hole", "Mount"), built.Value.MaterializedFeatures);+ Assert.Contains(new FirmamentFeatureReceipt("Body", "EdgeFinish", "Mount"), built.Value.MaterializedFeatures);+ foreach (var kind in new[] { "Hole", "EdgeFinish" })+ {+ var result = FirmamentFeatureAccounting.Verify(FirmamentV2Parser.Parse(source), source,+ built.Value with { MaterializedFeatures = built.Value.MaterializedFeatures.Where(r => r.Kind != kind).ToArray() });+ Assert.False(result.IsSuccess);+ Assert.StartsWith("firmament-feature-not-materialized:" + kind + ":Mount:", Assert.Single(result.Diagnostics).Message);+ }+ }++ [Fact]+ public void AReceiptForAnotherHostOrAnotherPatternInstanceCannotCoverAnOmittedHole()+ {+ var path = Fixture("Canonical/Patterns/four-hole-pattern.firmament");+ var source = File.ReadAllText(path);+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));+ Assert.Equal(4, built.Value.MaterializedFeatures.Count);+ var first = built.Value.MaterializedFeatures[0];+ var incomplete = built.Value with { MaterializedFeatures = built.Value.MaterializedFeatures.Skip(1).Append(first with { Host = "Other" }).ToArray() };+ var result = FirmamentFeatureAccounting.Verify(FirmamentV2Parser.Parse(source), source, incomplete);+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, d => d.Message.Contains(first.Name, StringComparison.Ordinal));+ }+}diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.csindex cb0e5dd7..2884511f 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs@@ -298,7 +298,16 @@ internal static partial class AssemblyDefinitionMaterializerif (!build.IsSuccess || build.Value is null){foreach (var diagnostic in build.Diagnostics)- diagnostics.Add(new("assembly-definition-materialization-failed", $"Definition '{definitionIdentity}' failed ordinary Firmament materialization: {diagnostic.Message}"));+ {+ var presented = FirmamentBuildAdmissionValidation.Present(diagnostic, sourceIdentity, module);+ var message = diagnostic.Message == presented.Message || diagnostic.Message.Contains(": ", StringComparison.Ordinal)+ ? diagnostic.Message : diagnostic.Message + ": " + presented.Message;+ diagnostics.Add(new("assembly-definition-materialization-failed", $"Definition '{definitionIdentity}' failed ordinary Firmament materialization: {message}")+ {+ SourceSpan = presented.SourceSpan is { } span ? new(sourceIdentity + "#definition:" + definitionIdentity, span.Start, span.Length) : null,+ LocationNote = "Offsets identify the specialized definition source; exact original-file expansion mapping is unavailable."+ });+ }return null;}var import = importBody(build.Value.StepText);diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 8365ff92..c9074e70 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -46,6 +46,7 @@ public static partial class FirmamentBuildAndExportif (lockDiagnostics.Count > 0) return KernelResult<FirmamentBuildAndExportResult>.Failure(lockDiagnostics.Select(d => SchemaDiagnostic(d.Code + ": " + d.Message)).ToArray());var sourceText = File.ReadAllText(fullSourcePath, Encoding.UTF8);+ var authoredSource = sourceText;// The lexer accepts authored line endings. Keep their offsets intact for// admission diagnostics and runtime assertion spans on Windows as well.var frontend = FirmamentFrontendSchemas.Select(sourceText);@@ -86,7 +87,7 @@ public static partial class FirmamentBuildAndExportif (library is null)return KernelResult<FirmamentBuildAndExportResult>.Failure(LibraryDiagnostics(libraryDiagnostics));sourceText = library.Source;- var exportResult = ExportSource(sourceText, Path.GetDirectoryName(fullSourcePath), allowV1Compatibility: true, frontend.Schema);+ var exportResult = ExportSource(sourceText, Path.GetDirectoryName(fullSourcePath), allowV1Compatibility: true, frontend.Schema, authoredSource: authoredSource);if (!exportResult.IsSuccess){return KernelResult<FirmamentBuildAndExportResult>.Failure(exportResult.Diagnostics);@@ -163,7 +164,7 @@ public static partial class FirmamentBuildAndExport// In-memory compilation is the canonical V2 boundary used by Forge,// assemblies, and drawings. Historical V1 execution is intentionally// available only to the explicitly versioned file compatibility route.- var export = ExportSource(normalized, sourceDirectory, allowV1Compatibility: false, frontend.Schema, resources);+ var export = ExportSource(normalized, sourceDirectory, allowV1Compatibility: false, frontend.Schema, resources, sourceText);if (!export.IsSuccess) return export;var enrichedExport = AttachAuthoredFeatureReports(normalized, sourceDirectory, export.Value, resources);var pmiParity = VerifyV2PmiExportParity(normalized, sourceDirectory, enrichedExport, resources);@@ -261,8 +262,10 @@ public static partial class FirmamentBuildAndExportstring sourceText,string? sourceDirectory = null,bool allowV1Compatibility = false,- FirmamentFrontendSchema? explicitSchema = null, IReadOnlyDictionary<string, string>? resources = null)+ FirmamentFrontendSchema? explicitSchema = null, IReadOnlyDictionary<string, string>? resources = null,+ string? authoredSource = null){+ authoredSource ??= sourceText;// Production mechanical execution consumes the result of AST admission.// Its expansion pipeline runs once in the frontend. Unmigrated domain owners// retain their existing expansion boundary until their own cutover.@@ -270,6 +273,16 @@ public static partial class FirmamentBuildAndExportvar canonicalParseWatch = System.Diagnostics.Stopwatch.StartNew();var v2Parse = FirmamentV2Parser.Parse(sourceText, sourceDirectory, null, explicitSchema, resources);canonicalParseWatch.Stop();+ var built = ExportAdmittedSource(sourceText, sourceDirectory, allowV1Compatibility, explicitSchema, resources, v2Parse, canonicalParseWatch);+ if (!built.IsSuccess) return built;+ var accounting = FirmamentFeatureAccounting.Verify(v2Parse, authoredSource, built.Value);+ return accounting.IsSuccess ? KernelResult<FirmamentStepExportResult>.Success(accounting.Value, built.Diagnostics) : accounting;+ }++ private static KernelResult<FirmamentStepExportResult> ExportAdmittedSource(+ string sourceText, string? sourceDirectory, bool allowV1Compatibility, FirmamentFrontendSchema? explicitSchema,+ IReadOnlyDictionary<string, string>? resources, FirmamentV2ParseResult v2Parse, Stopwatch canonicalParseWatch)+ {var templateBindWatch = new System.Diagnostics.Stopwatch();string materializerSource;if (v2Parse.OwnsUnifiedAdmission)@@ -358,7 +371,7 @@ public static partial class FirmamentBuildAndExport.Concat(coaxial.Chamfers.Select(chamfer => new FirmamentEngineeringFeatureReport(chamfer.Name, "Chamfer","compose:" + coaxial.Name + "." + chamfer.Name, coaxial.Name, chamfer.On, null, chamfer.Distance, "Distance", "Remove",MaterializationRoute: "RevolvedProfileStack"))).ToArray())- { RuntimeBody = built.Body, RuntimeBodySourceName = coaxial.Name });+ { RuntimeBody = built.Body, RuntimeBodySourceName = coaxial.Name, MaterializedFeatures = coaxial.Spans.Select(s => new FirmamentFeatureReceipt(coaxial.Name, s.Kind, s.Name)).Concat(coaxial.Chamfers.Select(c => new FirmamentFeatureReceipt(coaxial.Name, "EdgeFinish", c.Name))).ToArray() });}if (v2Parse.BoundRevolve is { } boundRevolve){@@ -508,7 +521,7 @@ public static partial class FirmamentBuildAndExportDimensionInspection: v2Parse.Document?.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.HoleDiameter).Select(p => new FirmamentPmiInspectionDimension("Diameter", p.Target, null, p.Value ?? 0d, "explicit-v2-record-pmi", p.Name)).ToArray() ?? [],Features: CompositionHoleReports(stack.Feature, completedBody, emitted.Correspondence),EngineeringFeatures: EngineeringFeatureReports(stack.Feature))- { RuntimeBody = completedBody, RuntimeCorrespondence = emitted.Correspondence, RuntimeBodySourceName = stack.Feature.Name });+ { RuntimeBody = completedBody, RuntimeCorrespondence = emitted.Correspondence, RuntimeBodySourceName = stack.Feature.Name, MaterializedFeatures = FirmamentFeatureAccounting.Composition(stack, emitted.Correspondence) });}if (v2Parse.BoundProfile is not null || (!v2Parse.OwnsUnifiedAdmission && ProfileAuthoringParser.IsProfileSource(materializerSource))){@@ -640,6 +653,7 @@ public static partial class FirmamentBuildAndExportDimensionInspection: []){RuntimeBody = executedPrimitive.Body,+ MaterializedFeatures = (v2Parse.Document.ModifyBlocks ?? []).SelectMany(m => (m.EdgeFinishes ?? []).Where(f => f.Target == "AllEdges").Select(f => new FirmamentFeatureReceipt(m.TargetSolid, "EdgeFinish", f.Name))).ToArray(),Cir = FirmamentCirRetention.FromRoot(execution.Value.NativeGeometryState.CirMirror.RuntimeRoot, step.Value,exportedPrimitive: execution.Value.ExecutedPrimitives.Count == 1 && execution.Value.ExecutedBooleans.Count == 0)};@@ -1174,9 +1188,14 @@ public static partial class FirmamentBuildAndExport"Distance","Remove",PolicySource: "Chamfer",- MaterializationRoute: "ComposedProfileBoundaryChamfer")).ToArray()));+ MaterializationRoute: "ComposedProfileBoundaryChamfer")).ToArray()) { MaterializedFeatures = FirmamentFeatureAccounting.Composition(stack, plannedEmission.Correspondence).Concat(FirmamentFeatureAccounting.ProfileFinish(source, target.StableId["edgefinish:".Length..], target.HostBodyId)).ToArray() });}if (emitted.Body is null || emitted.Correspondence is null) return Fail("MissingCorrespondenceEvidence");+ // The legacy rectangular-face compiler below rebuilds a single stock prism.+ // Additional operations must use the section-stack boundary planner above;+ // its box bridge cannot retain cavities or changes at other height levels.+ if (stack.Feature.Operations.Count != 1 || (stack.Feature.ConstructionPlaneBlindDrills?.Count ?? 0) > 0)+ return Fail("ComposedBoundaryRebuildUnsupported: This boundary selector uses a single-stock prism rebuild. Use an EdgeFinish on Top/Bottom through the section-stack planner to retain Compose operations and holes.");var composedCurves = stack.Slabs.MaxBy(s => s.To)!.Region.Outer.Loops.Single().Segments.Select(segment => segment.Geometry).ToArray();if (!IsAdmittedPrimitiveBoundary(composedCurves))return Fail($"{EdgeFinishProfileComposeBoundaryUnsupported}:host={stack.Feature.Name}:construction=Compose:face=+Z:target=Boundary: EdgeFinish on a Profile-based body is supported on four-sided boundaries; this boundary has curved or extra segments. Use Box stock for a rounded or chamfered rim, or shape the corners in the Profile itself.");@@ -1199,7 +1218,7 @@ public static partial class FirmamentBuildAndExportif (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);var reimport = Step242Importer.ImportBody(step.Value);if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value)) return Fail("semantic-compose-finish-step-reimport-failed");- return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, compiled.Feature.FeatureId, 0, "semantic-compose-edge-finish", "source-grounded-composed-top-boundary-chamfer"));+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, compiled.Feature.FeatureId, 0, "semantic-compose-edge-finish", "source-grounded-composed-top-boundary-chamfer") { MaterializedFeatures = FirmamentFeatureAccounting.Composition(stack, emitted.Correspondence).Concat(FirmamentFeatureAccounting.Receipts(stack.Feature.Name, "EdgeFinish", finish.Groups["name"].Value)).ToArray() });}private static KernelResult<FirmamentStepExportResult> ExportProfileSemanticTopBoundaryChamfer(@@ -1261,6 +1280,7 @@ public static partial class FirmamentBuildAndExport{RuntimeBody = fillet.Body, RuntimeCorrespondence = fillet.Correspondence,EdgeFinishPlanning = fillet.PlanningEvidence,+ MaterializedFeatures = FirmamentFeatureAccounting.ProfileFinish(source, filletTarget.StableId["edgefinish:".Length..], filletTarget.HostBodyId),EngineeringFeatures = [new(filletTarget.StableId["edgefinish:".Length..], "EdgeFinish", filletTarget.StableId,filletTarget.HostBodyId, filletTarget.Side.ToString(), $"{profile.Name}.{filletTarget.LoopId}", radius,"Radius", "Remove", PolicySource: "Fillet", MaterializationRoute: fillet.PlanningEvidence?.Decision.Strategy ?? route)]@@ -1286,6 +1306,7 @@ public static partial class FirmamentBuildAndExport{RuntimeBody = planned.Body, RuntimeCorrespondence = planned.Correspondence,EdgeFinishPlanning = planned.PlanningEvidence,+ MaterializedFeatures = FirmamentFeatureAccounting.ProfileFinish(source, target.StableId["edgefinish:".Length..], target.HostBodyId),EngineeringFeatures = [new(target.StableId["edgefinish:".Length..], "EdgeFinish", target.StableId,target.HostBodyId, target.Side.ToString(), $"{profile.Name}.{target.LoopId}", distance,"Distance", "Remove", PolicySource: "Chamfer", MaterializationRoute: planned.PlanningEvidence?.Decision.Strategy ?? "ProfileBoundaryChamfer")]@@ -1317,7 +1338,7 @@ public static partial class FirmamentBuildAndExportif (!step.IsSuccess || step.Value is null) return KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);var reimport = Step242Importer.ImportBody(step.Value);if (!reimport.IsSuccess || reimport.Value is null || !FirmamentManifoldChecker.IsManifold(reimport.Value)) return Fail("semantic-selection-finish-step-reimport-failed");- return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, compiled.Feature.FeatureId, 0, "semantic-profile-edge-finish", "source-grounded-top-boundary-chamfer"));+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, compiled.Feature.FeatureId, 0, "semantic-profile-edge-finish", "source-grounded-top-boundary-chamfer") { MaterializedFeatures = FirmamentFeatureAccounting.ProfileFinish(source, finish.Groups["name"].Value, profile.Name) });}private static bool IsAdmittedPrimitiveBoundary(IReadOnlyList<LineArcProfileCurve2D> curves) =>@@ -1574,7 +1595,7 @@ public static partial class FirmamentBuildAndExportDimensionInspection: document.Pmi?.Where(p => p.Kind == FirmamentV2PmiKind.HoleDiameter).Select(p => new FirmamentPmiInspectionDimension("Diameter", p.Target, null, p.Value ?? 0d, "explicit-v2-semantic-pmi", p.Name)).ToArray() ?? [],ConceptIr: document.ConceptIr,Features: featureReports,- Combined: report) { RuntimeBody = body, RuntimeCorrespondence = correspondence });+ Combined: report) { RuntimeBody = body, RuntimeCorrespondence = correspondence, MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "Hole", holes.Select(h => h.Name).ToArray()).Append(new FirmamentFeatureReceipt(solid.Name, "EdgeFinish", finish.Name)).ToArray() });}private static KernelResult<FirmamentStepExportResult> ExportV2TopBoundaryFillet(@@ -1602,7 +1623,7 @@ public static partial class FirmamentBuildAndExportif (!imported.IsSuccess || imported.Value is null || !FirmamentManifoldChecker.IsManifold(imported.Value))return CombinedFailure("CombinedFeatureMaterializerDiverged: top-boundary fillet STEP round trip failed.", imported.Diagnostics.Select(d => d.Message), finish.SourceSpan);return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(- step.Value, document.ModelName, 0, "top-boundary-fillet", "TopBoundaryFillet") { RuntimeBody = built.Value });+ step.Value, document.ModelName, 0, "top-boundary-fillet", "TopBoundaryFillet") { RuntimeBody = built.Value, MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", finish.Name) });}private static KernelResult<FirmamentStepExportResult> CombinedFailure(string message, IEnumerable<string>? details = null, FirmamentV2SourceSpan? sourceSpan = null) =>@@ -1723,7 +1744,7 @@ public static partial class FirmamentBuildAndExportreimported.Topology.Vertices.Count(), reimported.Topology.Edges.Count(), reimported.Topology.Faces.Count(), reimportedBounds, reimportedManifold));return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(- step.Value, compiled.Feature.FeatureId, 0, "air-chamfer", "top-face-boundary-chamfer", Air: report, ConceptIr: document.ConceptIr));+ step.Value, compiled.Feature.FeatureId, 0, "air-chamfer", "top-face-boundary-chamfer", Air: report, ConceptIr: document.ConceptIr) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", finish.Name) });}private static KernelResult<FirmamentStepExportResult> ExportV2LocalizedPlanarSingleEdgeChamfer(@@ -1770,7 +1791,7 @@ public static partial class FirmamentBuildAndExportnew("AP242", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true, reimport.Value.Topology.Vertices.Count(), reimport.Value.Topology.Edges.Count(), reimport.Value.Topology.Faces.Count(), Bounds(reimport.Value), true),new("SharedEdge(+X,+Z)", "LocalizedPlanarReplacement", "Direct", 2, 1, "ExplicitOwnedEndpoints", new(true, plan.DeterministicSignature), "valid", false),LocalizedEdgeFinish: new("Chamfer", "SharedEdge(+X,+Z)", "EqualDistance", finish.Distance, "LocalizedEdgeReplacement", "PlanarChamfer", "Direct", 2, 1, "ExplicitOwnedEndpoints", new(true, plan.DeterministicSignature), "valid", false));- return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, compiled.Feature.FeatureId, 0, "air-chamfer", "localized-planar-single-edge-chamfer", Air: report, ConceptIr: document.ConceptIr));+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, compiled.Feature.FeatureId, 0, "air-chamfer", "localized-planar-single-edge-chamfer", Air: report, ConceptIr: document.ConceptIr) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", finish.Name) });}private static KernelResult<FirmamentStepExportResult> ExportV2LocalizedEdgeJunctionChamfer(@@ -1817,7 +1838,7 @@ public static partial class FirmamentBuildAndExportnew("AP242", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true, reimport.Value.Topology.Vertices.Count(), reimport.Value.Topology.Edges.Count(), reimport.Value.Topology.Faces.Count(), Bounds(reimport.Value), true),LocalizedEdgeJunction: new(["SharedEdge(+X,+Z)", "SharedEdge(+Y,+Z)"], "Chamfer", "EqualDistance", first.Distance, "Direct", "LocalizedEdgeJunction", compiled.Construction.CornerPatch.Kind, 2, 0,new(true, topology.DeterministicSignature), "valid", false, 1, 1));- return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, $"{solid.Name}.{first.Name}.{second.Name}", 0, "air-chamfer", "localized-edge-junction-chamfer", Air: report, ConceptIr: document.ConceptIr));+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, $"{solid.Name}.{first.Name}.{second.Name}", 0, "air-chamfer", "localized-edge-junction-chamfer", Air: report, ConceptIr: document.ConceptIr) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", first.Name, second.Name) });}private static KernelResult<FirmamentStepExportResult> ExportV2LocalizedEdgeJunctionFillet(@@ -1866,7 +1887,7 @@ public static partial class FirmamentBuildAndExportLocalizedEdgeJunction: new(["SharedEdge(+X,+Z)", "SharedEdge(+Y,+Z)"], "Fillet", "ConstantRadius", first.Distance, "Direct", "LocalizedEdgeJunction", "None(DirectIntersection)", 2, 0,new(true, topology.DeterministicSignature), "valid", false, 1, 1,new("DirectIntersection", "Cylinder", "Cylinder", "Ellipse", true, 1, compiled.Construction.Closure.Branch)));- return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, $"{solid.Name}.{first.Name}.{second.Name}", 0, "air-fillet", "localized-edge-junction-fillet", Air: report, ConceptIr: document.ConceptIr));+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, $"{solid.Name}.{first.Name}.{second.Name}", 0, "air-fillet", "localized-edge-junction-fillet", Air: report, ConceptIr: document.ConceptIr) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", first.Name, second.Name) });}private static KernelResult<FirmamentStepExportResult>? TryExportV2HollowBody(FirmamentV2Document document)@@ -2026,7 +2047,7 @@ public static partial class FirmamentBuildAndExportnew(plan.IsAuthoritative, plan.DeterministicSignature, plan.ExpectedVertexCount, plan.ExpectedEdgeCount, plan.ExpectedFaceCount, plan.ExpectedLoopCount, plan.ExpectedCoedgeCount, plan.FaceRoles),new(Bounds(body), true, surfaces.Count(x => x == SurfaceGeometryKind.Plane), surfaces.Count(x => x == SurfaceGeometryKind.Cylinder), surfaces.Count(x => x == SurfaceGeometryKind.Torus), RoundedBoxAnalyticVolume(rounded.Size[0], rounded.Size[1], rounded.Size[2], rounded.CornerRadius, fillet), preflight.IsValid ? "valid" : "invalid"),new(Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true, true, imported.Value.Topology.Faces.Count(), Bounds(imported.Value)));- return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, solid.Name, 0, "air-rounded-box", fillet is null ? "rounded-box-primitive" : "rounded-box-top-boundary-fillet", RoundedBox: report));+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, solid.Name, 0, "air-rounded-box", fillet is null ? "rounded-box-primitive" : "rounded-box-top-boundary-fillet", RoundedBox: report) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", finishes.Select(f => f.Name).ToArray()) });}private static KernelResult<FirmamentStepExportResult> RoundedBoxFailure(string message) =>@@ -2098,7 +2119,7 @@ public static partial class FirmamentBuildAndExportLocalizedEdgeJunction: new(["SharedEdge(+X,+Z)", "SharedEdge(+Y,+Z)", "SharedEdge(+X,+Y)"], "Fillet", "EqualConstantRadius", xz.Distance, "Direct", "LocalizedTrihedralFillet", "SphericalOctant", 3, 1,new(true, topology.DeterministicSignature), "valid", false, 1, 1,new("SphericalOctant", "Sphere", "Cylinder", "Circle", true, 3, "+X,+Y,+Z octant")));- return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, $"{solid.Name}.{xz.Name}.{yz.Name}.{xy.Name}", 0, "air-fillet", "localized-trihedral-fillet", Air: report, ConceptIr: document.ConceptIr));+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, $"{solid.Name}.{xz.Name}.{yz.Name}.{xy.Name}", 0, "air-fillet", "localized-trihedral-fillet", Air: report, ConceptIr: document.ConceptIr) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", finishes.Select(f => f.Name).ToArray()) });}private static KernelResult<FirmamentStepExportResult> ExportV2LocalizedTangentBlendSingleEdgeFillet(@@ -2146,7 +2167,7 @@ public static partial class FirmamentBuildAndExportnew("AP242", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true, reimport.Value.Topology.Vertices.Count(), reimport.Value.Topology.Edges.Count(), reimport.Value.Topology.Faces.Count(), Bounds(reimport.Value), true),LocalizedFillet: new("SharedEdge(+X,+Z)", "ConstantRadius", finish.Distance, "LocalizedTangentBlend", "QuarterCircle", "Linear", "Direct", 2, 1, "ExplicitOwnedEndpoints", new(true, plan.DeterministicSignature), "valid", false),LocalizedEdgeFinish: new("Fillet", "SharedEdge(+X,+Z)", "ConstantRadius", finish.Distance, "LocalizedEdgeReplacement", "CylindricalFillet", "Direct", 2, 1, "ExplicitOwnedEndpoints", new(true, plan.DeterministicSignature), "valid", false));- return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, compiled.Feature.FeatureId, 0, "air-fillet", "localized-tangent-blend-single-edge-fillet", Air: report, ConceptIr: document.ConceptIr));+ return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, compiled.Feature.FeatureId, 0, "air-fillet", "localized-tangent-blend-single-edge-fillet", Air: report, ConceptIr: document.ConceptIr) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", finish.Name) });}private static KernelResult<FirmamentStepExportResult> ExportV2CircularRimChamfer(@@ -2205,7 +2226,7 @@ public static partial class FirmamentBuildAndExportnew("AP242", Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(step.Value))), true,reimport.Value.Topology.Vertices.Count(), reimport.Value.Topology.Edges.Count(), reimport.Value.Topology.Faces.Count(), CircularBounds(cylinder.Radius, cylinder.Height), reimportedManifold));return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(- step.Value, compiled.Feature.FeatureId, 0, "air-chamfer", "circular-top-rim-chamfer", Air: report, ConceptIr: document.ConceptIr));+ step.Value, compiled.Feature.FeatureId, 0, "air-chamfer", "circular-top-rim-chamfer", Air: report, ConceptIr: document.ConceptIr) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(solid.Name, "EdgeFinish", finish.Name) });}private static string CircularBounds(double radius, double height) =>@@ -2424,7 +2445,7 @@ public static partial class FirmamentBuildAndExport"boolean","side-hole-controlled-x",DatumInspection: [],- DimensionInspection: []));+ DimensionInspection: []) { MaterializedFeatures = FirmamentFeatureAccounting.Receipts(intent.TargetSolid, "Region", intent.RegionName) });}private static BrepBody ReorientCanonicalSideHoleBodyFromZToX(BrepBody body)@@ -2574,7 +2595,7 @@ public static partial class FirmamentBuildAndExport};return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(cylindricalStep.Value,cylindricalFeatureId, 0, "perforation-cylindrical", "local-radial-through-wall", Perforation: cylindricalReport)- { RuntimeBody = cylindricalBody, RuntimeCorrespondence = cylindricalCorrespondence });+ { RuntimeBody = cylindricalBody, RuntimeCorrespondence = cylindricalCorrespondence, MaterializedFeatures = FirmamentFeatureAccounting.Receipts(target, "Perforation", feature.Name) });}if (document.Solid.Name != target || document.Solid.Box is not { Size.Count: 3 } box)return Failure("perforation-cylindrical-topology-unavailable: the piping authority constructs constant-thickness annular stock, but the current BRep Boolean route does not materialize radial cylinder-to-cylinder intersections on its wall");@@ -2622,7 +2643,7 @@ public static partial class FirmamentBuildAndExportfeature.Margin, feature.MinimumLigament, plan.Instances.Count, holes.Select(hole => hole.FeatureId!).ToArray(),body.Topology.Vertices.Count(), body.Topology.Edges.Count(), body.Topology.Faces.Count(), true, true, hash);return KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, featureId, 0,- "perforation", "circular-through", Perforation: report) { RuntimeBody = body, RuntimeCorrespondence = correspondence });+ "perforation", "circular-through", Perforation: report) { RuntimeBody = body, RuntimeCorrespondence = correspondence, MaterializedFeatures = FirmamentFeatureAccounting.Receipts(target, "Perforation", feature.Name) });}private static KernelResult<FirmamentStepExportResult>? TryExportV2SemanticHoleBody(FirmamentV2Document document)@@ -2776,7 +2797,8 @@ public static partial class FirmamentBuildAndExportFeatures: featureReports){RuntimeBody = runtimeCorrespondence is null ? null : body,- RuntimeCorrespondence = runtimeCorrespondence+ RuntimeCorrespondence = runtimeCorrespondence,+ MaterializedFeatures = FirmamentFeatureAccounting.Receipts(modifyTargets[0], "Hole", semanticHoles.Select(h => h.Name).ToArray())});}diff --git a/Aetheris.Kernel.Firmament/FirmamentFeatureAccounting.cs b/Aetheris.Kernel.Firmament/FirmamentFeatureAccounting.csnew file mode 100644index 00000000..8606bd3d--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentFeatureAccounting.cs@@ -0,0 +1,132 @@+using Aetheris.Kernel.Core.Diagnostics;+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Results;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament;++/// <summary>A receipt from a completed geometry route, before authored display reports are attached.+/// Names are scoped to the material host; expanded Pattern keys remain part of the name.</summary>+public sealed record FirmamentFeatureReceipt(string Host, string Kind, string Name);++internal static class FirmamentFeatureAccounting+{+ internal static IReadOnlyList<FirmamentFeatureReceipt> Receipts(string host, string kind, params string[] names) =>+ names.Select(name => new FirmamentFeatureReceipt(host, kind, name)).Distinct().ToArray();++ internal static IReadOnlyList<FirmamentFeatureReceipt> Composition(+ PrismaticSectionStackConstruction stack, SemanticTopologyCorrespondence? correspondence)+ {+ var feature = stack.Feature;+ var active = stack.Slabs.SelectMany(s => s.ActiveOperations).ToHashSet(StringComparer.Ordinal);+ var realized = (correspondence?.Descendants ?? []).Where(d => d.Face.HasValue || d.Edge.HasValue)+ .Select(d => d.SourceStableId).ToHashSet(StringComparer.Ordinal);+ // Slabs identify operations consumed by the material arrangement. Semantic+ // cavities additionally need their actual topology descendants, including+ // the blind-drill bridge which is applied after ordinary stack emission.+ var receipts = feature.Operations.Where(o => active.Contains(o.Name) && o.SemanticFeatureId is null)+ .Select(o => new FirmamentFeatureReceipt(feature.Name, o.SemanticFeatureKind ?? o.Intent.ToString(), o.Name));+ receipts = receipts.Concat((feature.Bosses ?? []).Where(h => active.Contains(h.Name)).Select(h => new FirmamentFeatureReceipt(feature.Name, "Boss", h.Name)))+ .Concat((feature.Pockets ?? []).Where(h => active.Contains(h.Name)).Select(h => new FirmamentFeatureReceipt(feature.Name, "Pocket", h.Name)))+ .Concat((feature.MaterialOffsets ?? []).Where(h => active.Contains(h.Name)).Select(h => new FirmamentFeatureReceipt(feature.Name, h.OperationKind + "Offset", h.Name)))+ .Concat(feature.AllSlotProfiles.Where(h => realized.Contains(h.StableId)).Select(h => new FirmamentFeatureReceipt(feature.Name, "Slot", h.Name)))+ .Concat((feature.ConstructionPlaneBlindDrills ?? []).Where(h => realized.Contains(h.StableId)).Select(h => new FirmamentFeatureReceipt(feature.Name, "Hole", h.Name)))+ .Concat((feature.ShaftHoles ?? []).Where(h => realized.Contains(h.StableId)).Select(h => new FirmamentFeatureReceipt(feature.Name, "Hole", h.Name)))+ .Concat((feature.CounterboreHoles ?? []).Where(h => realized.Contains(h.StableId)).Select(h => new FirmamentFeatureReceipt(feature.Name, "Hole", h.Name)))+ .Concat((feature.CountersinkHoles ?? []).Where(h => realized.Contains(h.StableId)).Select(h => new FirmamentFeatureReceipt(feature.Name, "Hole", h.Name)));+ return receipts.Distinct().ToArray();+ }++ internal static IReadOnlyList<FirmamentFeatureReceipt> ProfileFinish(string source, string name, string materialHost)+ {+ var owners = FirmamentV2Parser.MechanicalDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements)+ .Where(d => d.Type.Name.Text == "Modify" && d.Body?.Statements.OfType<DeclarationSyntax>()+ .Any(f => f.Type.Name.Text == "EdgeFinish" && f.Name?.Text == name) == true).ToArray();+ if (owners.Length == 1) return Receipts(owners[0].Name!.Text, "EdgeFinish", name);+ if (owners.Length > 1) return [];+ var roots = FirmamentV2Parser.MechanicalDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements)+ .Count(d => d.Type.Name.Text == "EdgeFinish" && d.Name?.Text == name);+ return roots == 1 ? Receipts(materialHost, "EdgeFinish", name) : [];+ }++ internal static KernelResult<FirmamentStepExportResult> Verify(+ FirmamentV2ParseResult parsed, string source, FirmamentStepExportResult result)+ {+ if (!parsed.IsSuccess || parsed.Document is null) return KernelResult<FirmamentStepExportResult>.Success(result);+ var original = FirmamentSyntaxParser.Parse(FirmamentSourceSpelling.Normalize(source)).Document;+ // This is the admitted expansion, before materializer-specific source transport.+ // Checking only Document.ModifyBlocks misses the profile/composition binder's operations.+ var expanded = FirmamentSyntaxParser.Parse(parsed.DiagnosticSource ?? parsed.BoundSource ?? source).Document;+ var origins = new FirmamentSyntaxOrigins(original, expanded);+ // The admitted compatibility grammar retains lowercase construct tokens.+ // Construct kind casing is not an operation identity; authored names are.+ static (string Host, string Kind, string Name) Identity(FirmamentFeatureReceipt receipt) =>+ (receipt.Host, receipt.Kind.ToUpperInvariant(), receipt.Name);+ var actual = result.MaterializedFeatures.Select(Identity).ToHashSet();+ var errors = new List<KernelDiagnostic>();+ var missing = new HashSet<(string Host, string Kind, string Name)>();+ void Missing(string host, string kind, string name, FirmamentV2SourceSpan span)+ {+ if (actual.Contains(Identity(new(host, kind, name))) || !missing.Add(Identity(new(host, kind, name)))) return;+ var authored = origins.Find(span);+ var enclosing = authored is null ? FirmamentSyntaxTraversal.Declarations(original)+ .Where(d => d.Type.Name.Text is "Modify" or "Compose" && d.Name?.Text == host).ToArray() : [];+ var location = authored ?? (enclosing.Length == 1 ? enclosing[0].Name!.Span : null);+ errors.Add(new(KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error,+ $"firmament-feature-not-materialized:{kind}:{name}: {kind} {name} was accepted but not built on '{host}'.",+ "Firmament.FeatureAccounting")+ {+ OriginalSourceSpan = location is null ? null : new(location.Start, location.Length)+ { LocationNote = authored is null ? "Enclosing material operation; the expanded instance has no exact original declaration span." : null },+ SourceSpan = new(span.Start, span.Length)+ { LocationNote = authored is null ? "Expanded feature; original declaration mapping is unavailable." : null }+ });+ }+ // Semantic point Patterns expand into bound instances rather than source text.+ // Demand every bound instance, then independently check the declared expansion count.+ foreach (var modify in parsed.Document.ModifyBlocks ?? [])+ foreach (var hole in modify.SemanticHoles)+ Missing(modify.TargetSolid, "Hole", hole.Name, hole.SourceSpan ?? new(0, 0));+ foreach (var pattern in parsed.Document.ConceptIr?.PatternExpansions ?? [])+ {+ var generated = pattern.GeneratedDeclarations.Select(p => p.Split("::")[^1]).ToArray();+ if (pattern.Count == 0 && generated.Length == 0) continue;+ var host = (parsed.Document.ModifyBlocks ?? []).SingleOrDefault(m => m.SemanticHoles.Any(h => generated.Contains(h.Name)))?.TargetSolid;+ if (host is not null && generated.Length == pattern.Count && generated.Distinct().Count() == pattern.Count+ && generated.All(name => actual.Contains(Identity(new(host, "Hole", name))))) continue;+ var name = pattern.Pattern.Split("::")[^1];+ Missing(host ?? pattern.Pattern.Split("::")[0], "Pattern", name, pattern.SourceSpan);+ }+ void Scope(IEnumerable<StatementSyntax> statements)+ {+ foreach (var declaration in statements.OfType<DeclarationSyntax>())+ {+ // Definitions are not executions. Their instantiated bodies are in the admitted expansion.+ if (declaration.Type.Name.Text is "Template" or "Feature" or "Record" or "Interface"+ || declaration.Modifiers.Any(m => m.Name.Text is "Concept" or "Template")) continue;+ if (declaration.Type.Name.Text is "Modify" or "Compose")+ {+ var host = declaration.Name?.Text ?? "";+ foreach (var feature in declaration.Body?.Statements.OfType<DeclarationSyntax>() ?? [])+ {+ // Guides are compile-time input, owned and checked by the Profile binder.+ if (ProfileAuthoringParser.OwnsDeclaration(feature)) continue;+ if (feature.Type.Name.Text == "Pattern" && (parsed.Document.ConceptIr?.PatternExpansions ?? [])+ .Any(p => p.Pattern.EndsWith("::" + feature.Name?.Text, StringComparison.Ordinal))) continue;+ Missing(host, feature.Type.Name.Text, feature.Name?.Text ?? "", feature.Name?.Span ?? feature.Span);+ }+ }+ else if (declaration.Type.Name.Text == "EdgeFinish")+ Missing(parsed.BoundProfile?.Name ?? parsed.BoundComposition?.Feature?.Name+ ?? parsed.BoundCoaxialComposition?.Name ?? parsed.Document.Solids.SingleOrDefault()?.Name ?? "",+ "EdgeFinish", declaration.Name?.Text ?? "", declaration.Name?.Span ?? declaration.Span);+ else if (declaration.Body is not null) Scope(declaration.Body.Statements);+ }+ }+ Scope(expanded.Statements);+ return errors.Count > 0 ? KernelResult<FirmamentStepExportResult>.Failure(errors)+ : KernelResult<FirmamentStepExportResult>.Success(result);+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.csindex 4e026ffe..2cc78483 100644--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs@@ -38,6 +38,7 @@ public sealed record FirmamentStepExportResult(FirmamentThreadReport? Thread = null){public string? DocumentName { get; init; }+ public IReadOnlyList<FirmamentFeatureReceipt> MaterializedFeatures { get; init; } = [];public FirmamentImportedHoleRevisionReport? ImportedHoleRevision { get; init; }public FirmamentImportedHoleRemovalReport? ImportedHoleRemoval { get; init; }// Lowerer-owned receipts distinguish generated feature PMI from authored projections.diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.csindex 4860b4e1..3a314d69 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs@@ -82,6 +82,17 @@ public static class FirmamentBuildAdmissionValidationvar parameters = code.Split(": ", 2)[0].Split(':').Skip(1).Select(part => part.Contains('=') ? part[(part.IndexOf('=') + 1)..] : part).ToArray();if (parameters.Length == 0) return null;+ if (code.StartsWith("firmament-v2-field-unit-mismatch:", StringComparison.Ordinal) && parameters.Length >= 3)+ {+ var fields = Syntax.FirmamentSyntaxTraversal.Declarations(Syntax.FirmamentSyntaxParser.Parse(source).Document)+ .Where(d => d.Type.Name.Text == parameters[0] && d.Name?.Text == parameters[1])+ .SelectMany(d => d.Body?.Statements.OfType<Syntax.FieldSyntax>() ?? [])+ .Where(f => Syntax.FirmamentSyntaxFields.SameField(f.Name.Text, parameters[2])).ToArray();+ if (fields.Length > 1 && parameters.Length >= 5)+ fields = fields.Where(f => Syntax.FirmamentSyntaxTraversal.Expressions(f.Value)+ .OfType<Syntax.QuantitySyntax>().Any(q => q.Unit.Text == parameters[4])).ToArray();+ if (fields.Length == 1) return fields[0].Span;+ }var declarations = Syntax.FirmamentSyntaxTraversal.Declarations(Syntax.FirmamentSyntaxParser.Parse(source).Document).Where(d => d.Name is not null).ToArray();// A Kind:Name pair is the most specific; otherwise the first parameter that names one declaration.diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.csindex 2e601ebd..3bdcdd48 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs@@ -1389,6 +1389,8 @@ public static class ProfileAuthoringParservar profile = fields.Take("Profile");var from = fields.Take("From");var to = fields.Take("To");+ fields.CheckUnit("From", from, "mm");+ fields.CheckUnit("To", to, "mm");fields.Complete();return (profile, from, to);}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.csindex 89940d74..158982cb 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxValues.cs@@ -65,13 +65,24 @@ public sealed class FirmamentSyntaxFields(DeclarationSyntax declaration, List<stif (fields.Length > 1) diagnostics.Add($"firmament-v2-field-duplicate:{declaration.Type.Name.Text}:{name}");return fields.Length == 1 ? bind?.Invoke(fields[0].Value) ?? fields[0].Value : null;}- public bool Measure(string name, string unit, out double value) => FirmamentSyntaxValues.TryMeasure(Take(name), unit, out value, implicitUnit);+ public bool Measure(string name, string unit, out double value)+ {+ var expression = Take(name);+ if (FirmamentSyntaxValues.TryMeasure(expression, unit, out value, implicitUnit)) return true;+ CheckUnit(name, expression, unit); return false;+ }+ internal void CheckUnit(string name, ExpressionSyntax? expression, string expected)+ {+ if (expression is null || !FirmamentNumericEvaluation.TryEvaluate(expression, out var value)+ || value.Unit.Length == 0 || value.Unit == expected) return;+ diagnostics.Add($"firmament-v2-field-unit-mismatch:{declaration.Type.Name.Text}:{declaration.Name?.Text}:{name}:expected={expected}:actual={value.Unit}: Field '{FirmamentSourceSpelling.PreferredField(name)}' in {declaration.Type.Name.Text} '{declaration.Name?.Text}' requires {expected}; received {value.Unit}.");+ }public double Number(string name, string unit, double fallback = double.NaN){var expression = Take(name);if (expression is null) return fallback;if (FirmamentSyntaxValues.TryMeasure(expression, unit, out var value, implicitUnit)) return value;- Invalid(name); return double.NaN;+ CheckUnit(name, expression, unit); Invalid(name); return double.NaN;}public IReadOnlyList<FieldSyntax> TakeAll(string name){@@ -91,7 +102,19 @@ public sealed class FirmamentSyntaxFields(DeclarationSyntax declaration, List<stif (value is null) Invalid(name);return value;}- public bool Vector(string name, string unit, out double[] values) => FirmamentSyntaxValues.Vector(Take(name), unit, out values, implicitUnit);+ public bool Vector(string name, string unit, out double[] values)+ {+ var expression = Take(name);+ if (FirmamentSyntaxValues.Vector(expression, unit, out values, implicitUnit)) return true;+ IEnumerable<ExpressionSyntax> elements = expression switch+ {+ SequenceSyntax list => list.Items.Select(i => i.Value),+ CallSyntax call => call.Arguments.Select(i => i.Value),+ _ => expression is null ? [] : [expression]+ };+ foreach (var element in elements) CheckUnit(name, element, unit);+ return false;+ }public void Complete(IReadOnlySet<StatementSyntax>? consumedStatements = null, bool admitAnnotation = false, bool admitInitializer = false, bool admitPlacement = false){if (declaration.Occurrence || declaration.Parameters.Count > 0 || (!admitAnnotation && declaration.Annotation is not null) || declaration.ResultType is not null || (!admitInitializer && declaration.Initializer is not null))diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.csindex 449920de..0f08cbb5 100644--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs@@ -461,7 +461,7 @@ public static class PrismaticProfileCompositionParservar selectedSupport = candidates[0];if (through){- operations.Add(new(name, PrismaticProfileIntent.Remove, profileName, stock.From, selectedSupport.To, "ThroughCut", $"offset:{declaration.Span.Start}"));+ operations.Add(new(name, PrismaticProfileIntent.Remove, profileName, stock.From, selectedSupport.To, "ThroughCut", $"offset:{declaration.Span.Start}", SemanticFeatureKind: "Pocket"));continue;}var hostThickness = selectedSupport.To - selectedSupport.From; var remaining = hostThickness - depth;diff --git a/Aetheris.Web.Runtime/sdk/src/runtime.js b/Aetheris.Web.Runtime/sdk/src/runtime.jsindex 0e6b2162..c0e51e5b 100644--- a/Aetheris.Web.Runtime/sdk/src/runtime.js+++ b/Aetheris.Web.Runtime/sdk/src/runtime.js@@ -44,7 +44,7 @@ export function reviveBinary(value, bytes) {export async function createRuntime(runtimeBase = new URL('./runtime/', import.meta.url)) {const dotnetUrl = new URL('_framework/dotnet.js', runtimeBase);const importStart = performance.now();- const { dotnet } = await import(dotnetUrl.href);+ const { dotnet } = await import(/* @vite-ignore */ dotnetUrl.href);const moduleImportMilliseconds = performance.now() - importStart;const createStart = performance.now();const runtime = await dotnet.withApplicationArguments().create();diff --git a/docs/development/reports/2026-10/demo-polish-qualification.md b/docs/development/reports/2026-10/demo-polish-qualification.mdnew file mode 100644index 00000000..c8a80f85--- /dev/null+++ b/docs/development/reports/2026-10/demo-polish-qualification.md@@ -0,0 +1,211 @@+# Demo polish qualification — 2026-10-26++Verdict: **Meaningful progression**. The compiler-honesty, diagnostic and local+package changes are implemented. The requested twofold cold-validation speedup+is not achieved; the unsafe temptation to weaken STEP qualification was rejected.+No packages or releases were published in this pass.++Baseline: Aetheris `1547048f`; paired HeliosCAD `85947e6`. Claude's brief reports+373 canonical sources; the current checkout contains **380**. Older release+blocker claims are historical observations, not the current baseline.++## Disposition of the seven requested items++| Item | Current finding and disposition |+|---|---|+| 1. Materialized feature accounting | Fixed. Successful mechanical routes now issue typed `(host, kind, name)` receipts before source-derived display reports are attached. A mandatory guard compares admitted Modify/Compose operations and concrete Pattern instances against them. Missing features reject normal validation and build. |+| 2. Field closure | Required Semantic, Assembly/Subassembly/expose and SectionChain owners already reject the reported fields in this checkout. Wrong-unit Point2 also already rejects. Preserve those fixes; improve unit messages and locations. The mutation probe below shows no new acceptance. |+| 3. WebGL fallback | Already implemented upstream. Sanity-qualified in the real Helios browser; no production viewport rewrite. See the paired Helios report. |+| 4. Fresh-clone SDK | Fixed in Helios: directory link, reproducible Telos prerequisite build, coherent Vite dependency resolution. Aetheris marks its intentionally dynamic runtime import for Vite. |+| 5. Cold-validation performance | **Honest stop for this item.** A bounded optimization experiment failed the target and was reverted. Retain only opt-in performance phase instrumentation. See the measured prerequisite below. |+| 6. CLI and diagnostics | Fixed remaining wrong-unit messages, field locations, structured SectionChain build diagnostics, specialized Assembly failure context and nine short help commands. Existing missing-file and lowercase-model fixes are retained and regression-tested. |+| 7. Release lane | The old preview-only/version/dependency findings were already repaired upstream. Repack the dependency-closed 25-library graph and CLI at 2.0.0, test a genuinely isolated consumer with nuget.org enabled, install the local tool, and run all six Learn lessons from an unrelated working directory. Local candidate source mapping prevents an existing remote 2.0.0 from hiding a broken candidate. |++## Compiler accounting contract++The admitted expansion supplies expected operations; the materializer supplies+receipts only after its geometry route succeeds. Ordinary section-stack operations+use the slabs' active operation identities. Semantic holes, slots and blind drills+also require realized topology correspondence. Profile-boundary finishes report+their actual host rather than receiving an exemption. Imported geometry and PMI+do not invent material operations. A successful Pattern needs every unique+expanded instance and the admitted expansion count.++`Features`/`EngineeringFeatures` remain useful display metadata, but cannot prove+that a feature was built: some are attached by reading source. `build --json`+therefore exposes the independent `materializedFeatures` ledger. Errors retain+`firmament-feature-not-materialized:Kind:Name` in the diagnostic message and use+the common structured diagnostic presentation. Original declaration spans are+preferred; unavailable expansion provenance is disclosed at the enclosing owner.++The guard is not a second geometry engine. It proves that the owning route+consumed the admitted operation, while existing geometric and interchange checks+prove that route's output. Future routes must report their actual executions.++Qualification found and repaired two accounting mistakes before acceptance:++- Two different feature kinds can legitimately share a name on one host. A Hole+ and EdgeFinish named Mount now require separate typed receipts; either missing+ receipt rejects.+- `Remove` with `role: ThroughCut` remains a Remove operation. It must not be+ relabeled Pocket merely because it shares that semantic role. Both existing+ Pipeline fixtures are explicit regression cases. Through-Pocket lowering now+ retains its existing SemanticFeatureKind metadata independently of that role.+ Admitted lowercase construct aliases compare as the same kind while host and+ feature names remain case-sensitive; one omitted feature yields one error.++A legacy composed rectangular-boundary box rebuild cannot preserve additional+cavities or height-changing operations. It now rejects that combination with+`ComposedBoundaryRebuildUnsupported` and directs authors to the section-stack+Top/Bottom EdgeFinish route. It does not silently rebuild only the stock box.++The reversion witness constructs the old bare Extrude output, attaches even the+full source-derived display reports, and submits it against source declaring a+hole. The guard rejects it at the original Mount declaration, including when a+library Use precedes the source. Separate tests cover wrong hosts, missing Pattern+instances, Box, Extrude, Compose, coaxial Compose, profile finish, hollow+perforation and imported STEP/PMI routes. These are behavior/geometry tests, not+exact-sentence snapshots.++## Field and diagnostic reproduction++The old Learn/06 examples now reject unknown Extrude fields, Semantic members,+Assembly root fields, SectionChain Point2 fields and explicit `deg` in a Point2+length vector. Field rejection precedes geometry execution. Normal lowercase V2+`model` validates and builds through its actual domain owner.++For explicit unit failures the diagnostic names construct, declaration, field,+expected unit and received unit. Extrude `to: 8deg` and SectionChain+`position: [2mm, -2deg]` are tested through both real CLI commands, including the+field location. Unitless values retain only the aliases/implicit-unit rules+already admitted by their owner. Ambiguous or generated locations are not invented.++Build failures for SectionChain now use structured objects equivalent to validate;+Assembly specialization preserves the original diagnostic and message, marking+expanded-definition offsets explicitly. Missing-file text is short and exits 1;+JSON remains structured. Help now supplies purpose, usage, options and an example+for format, mesh, lock, measure, inspect-3dm, recover-3dm, fea, drawing and scene.+View help describes both Firmament builds and existing STEP.++### Unknown-field probe++`scripts/qualify-unknown-fields.py` mutates actual brace token boundaries outside+comments/strings and invokes the real CLI. It copies only repository-contained+relative resources into ignored evidence directories. A failing control never+counts as successful field rejection.++All **322** baseline-valid seeds have passing resource-complete controls. Both+before and after runs contain **3,449** mutations, **66** accepted mutations and+no timeouts. All final accepted cases were rechecked after the typed-ledger fix:+66 accepted, no outcome changes.++| Runtime owner | Before accepted | After accepted |+|---|---:|---:|+| UnifiedMechanical | 42 | 42 |+| Assembly | 5 | 5 |+| UnifiedSectionChain | 16 | 16 |+| Garment | 1 | 1 |+| UnifiedRevolve | 1 | 1 |+| WireForm | 1 | 1 |++These are not 66 ignored built-in fields: **60** add legitimate named Concept+Struct publications, **one** adds a legitimate named station, and **five** occur+inside an unused Plate recipe while the source instantiates Disc. Recipe material+checks are specialization-dependent. Required closed field owners have no+accepted mutation in this run.++The token probe does not exhaust value-object expression syntax. A separate+minimal witness, `fixtures/Regression/FeatureAccounting/value-object-plane-known-gap.firmament`,+confirms that an extra field in an unused published inline Plane value still+accepts. This is an explicitly excluded value-object closure gap, documented in+`docs/public/reference/language/compatibility.md`. Existing WireForm operation+field closure is stronger than the old brief; it was not rewritten here.++## Performance: measured limit, no weakened verification++Fresh-process observations below were collected during qualification and are+single samples under competing load, not a controlled speed benchmark:++| Input | Baseline seconds | Experimental candidate seconds |+|---|---:|---:|+| WireForm/axis-coil validate | 10.422 | 8.375 |+| WireForm/helix validate | 10.109 | 7.797 |+| Assembly/coil-on-stem validate | 9.203 | 11.328 |+| GuitarX0 cold build | 12.906 | 9.078 |++The candidate used bounded coarse orientation witnesses only on the immediate+exporter-owned roundtrip, with disagreement falling back to full qualification.+It did not meet the requested 2× reduction, and the assembly sample regressed.+**All candidate behavior changes were reverted.** These are not final shipping+performance gains.++A separate real compiler profile measured 8.609 s total: 1.891 s in orientation+qualification, 5.323 s in pcurve recovery/qualification, and 7.647 s in STEP body+import overall. Even deleting orientation entirely cannot meet the target.+Existing recovery already caches seeds; dense spline lift qualification still+performs 8,193 samples per coedge. Added BuildPerfTrace scopes expose the two+costs without changing admission or STEP output.++The smallest justified next performance project is proof-preserving pcurve+qualification optimization or producer-owned trim/coedge witnesses across the+export/reimport boundary. Skipping external STEP checks, weakening tolerances or+adding a public trusted-import switch is not a demo-polish fix.++## Final qualification++Final results and evidence are recorded under ignored+`artifacts/local/demo-polish/`; see the completion addendum below. Earlier+interrupted or intermediate runs are not the acceptance evidence. The full+corpus compares **both** validate/build exit status and successful STEP SHA-256,+not just compilation success. Existing recipe fragments, domain-specific exports+and known invalid/speculative sources retain their baseline classification. The+25 baseline-valid sources declined by this STEP-output command are seven Scenes,+seven Garments, and eleven Drawing/Analysis artifact-directory products. Their+diagnostics request the correct export command or output directory; they are not+frontend admission contradictions.++No source migration, kernel construction change, new parser route, global error+allowlist or global rewrite was introduced. A dedicated diff review checked+receipt provenance, diagnostic constructors/locations, schema duplication,+source/build ownership and process cleanup.++### Completion evidence++- `final4-build.log`: full Release solution build, zero errors.+- `final4-focused.log`: 59 accounting/X4 tests passed; `final4-concept-cli.log`:+ four real CLI semantic-hole tests passed.+- `final4-fast.log`: 1,111 Core tests passed.+- `final4-full.log`: **6,099 passed, zero failed, two existing Drawing skips**,+ across 20 nonempty test projects. The intentionally empty FrictionLab project+ remains empty. The full test command exited 0.+- `final4-corpus/summary.json` and `differences.json`: **380 sources**, 322+ validate successfully, 297 STEP builds succeed, **zero exit/hash differences**+ against the pristine baseline; no timeouts. Intermediate failed/superseded+ qualification runs are not counted as final evidence.+- The separate through-Pocket regression's STEP is byte-identical between+ `baseline-cli` and `final4-cli`, despite its newly retained kind metadata.+- `fields-before`, `fields-after`, `fields-qualified-accepted.json`: the full+ before/after 3,449-case probe and final-binary recheck of all 66 accepted cases.+- `packages-qualified.log`: 25 dependency-closed public libraries at 2.0.0.+ `consumer-qualified.log`: fresh isolated restore with candidate/nuget.org source+ mapping, build and execution succeed, including packaged material catalog and+ a reimportable STEP API result.+- `tool-install-qualified.log` and `qualified-lessons/summary.json`: the locally+ installed 2.0.0 tool validates/builds all six Learn lessons from the system temp+ working directory; all six STEP hashes match the pristine corpus. The installed+ Firmament assembly matches the candidate tool ZIP, excluding stale-cache success.+- `clean-bootstrap-qualified.log` / `clean-browser-qualified.log`: source trees+ refreshed with the final patch, generated SDK/Telos dist and JavaScript+ dependency trees removed, README bootstrap succeeds, and all three real `/local`+ WebGL fallback tests pass. **This is clean Windows source-tree qualification,+ not the requested clean Linux container.** Docker's daemon was unavailable and+ the installed WSL environment had no Linux Node/.NET toolchain; that platform+ acceptance remains unqualified.+- Paired frontend/backend logs are summarized in their own reports. Test hosts+ are temporary process-owned hosts; no service/startup hook was installed.++Remaining work is bounded and explicit: the unachieved cold-validation target,+the excluded nested value-object closure family, and Linux-container bootstrap+qualification. Existing accepted engineering geometry is preserved in the tested+corpus; this report does not claim static validation prevents every runtime+geometry failure.diff --git a/docs/public/reference/language/compatibility.md b/docs/public/reference/language/compatibility.mdindex 798ed28f..2ccf5a8f 100644--- a/docs/public/reference/language/compatibility.md+++ b/docs/public/reference/language/compatibility.md@@ -90,3 +90,24 @@ A WireForm part admits one wire product. Its named operations require fieldbodies; unsupported placement or parameter headers reject. Use StartFrame forthe authored frame and an Assembly for separate Parts. Comments never contributewire operations or operation provenance.++## Admission limits++Normal validation of a mechanical part runs its engineering build. The build+also checks its materialized feature receipts against the admitted operations:+missing Modify or Compose features reject the build. Pattern instances retain+individual identities; one built instance cannot stand in for another.+`build --json` exposes those receipts as `materializedFeatures` separately from+source-derived display reports.++Field closure does not yet cover every value-object body nested in a published+Concept Struct. For example, an extra field inside an inline `Plane { ... }`+value can currently be accepted without affecting that plane. Use only the+listed fields of these value objects; validation does not yet prove that their+entire bodies were consumed. This differs from adding a legitimate new named+member to an open Concept Struct, which is supported authoring data.++Diagnostics for specialized definitions and expanded Pattern instances use the+original field or declaration when it can be mapped. Otherwise they identify+the enclosing material operation or the specialized definition and disclose+that the offsets describe expanded source.diff --git a/fixtures/Regression/FeatureAccounting/coaxial.firmament b/fixtures/Regression/FeatureAccounting/coaxial.firmamentnew file mode 100644index 00000000..d436b088--- /dev/null+++ b/fixtures/Regression/FeatureAccounting/coaxial.firmament@@ -0,0 +1,8 @@+Model Coaxial {+ units: mm+ Compose Body {+ Cylinder shaft { radius: 3mm; height: 12mm }+ Frustum head { on: shaft.Top; bottomRadius: 3mm; topRadius: 6mm; height: 3mm }+ }+ Modify Body { EdgeFinish<Chamfer> tip { on: shaft.Bottom; target: Boundary; distance: 0.5mm } }+}diff --git a/fixtures/Regression/FeatureAccounting/extrude-hole.firmament b/fixtures/Regression/FeatureAccounting/extrude-hole.firmamentnew file mode 100644index 00000000..43d2d54c--- /dev/null+++ b/fixtures/Regression/FeatureAccounting/extrude-hole.firmament@@ -0,0 +1,11 @@+Model ExtrudeHole {+ units: mm+ Concept Struct layout on XY {+ Rect2 outline { center: [0mm, 0mm]; size: [40mm, 30mm] }+ }+ Profile section using layout { Loop Outer { outline |> TraceLoop } }+ Extrude Body { profile: section; from: 0mm; to: 8mm }+ Modify Body {+ Hole<Shaft> Mount { on: +Z; center: Point2(0mm, 0mm); diameter: 6mm; end: ThroughAll }+ }+}diff --git a/fixtures/Regression/FeatureAccounting/same-name-different-kinds.firmament b/fixtures/Regression/FeatureAccounting/same-name-different-kinds.firmamentnew file mode 100644index 00000000..7517176f--- /dev/null+++ b/fixtures/Regression/FeatureAccounting/same-name-different-kinds.firmament@@ -0,0 +1,7 @@+Model SameName { units: mm+ Box Body { size: [40mm,30mm,8mm] }+ Modify Body {+ Hole<Shaft> Mount { on: +Z; center: Point2(0mm,0mm); diameter: 6mm; end: ThroughAll }+ EdgeFinish Mount { face: +Z; target: Boundary; kind: Chamfer; distance: 1mm }+ }+}\ No newline at end of filediff --git a/fixtures/Regression/FeatureAccounting/value-object-plane-known-gap.firmament b/fixtures/Regression/FeatureAccounting/value-object-plane-known-gap.firmamentnew file mode 100644index 00000000..49b7d7bf--- /dev/null+++ b/fixtures/Regression/FeatureAccounting/value-object-plane-known-gap.firmament@@ -0,0 +1,4 @@+Model PlaneValue { units: mm+ Concept Struct layout { support: Plane { origin: [0mm,0mm,0mm]; normal: [0,0,1]; up: [0,1,0]; zzUnknownField: 3mm } }+ Box Body { size: [20mm,20mm,5mm] }+}\ No newline at end of filediff --git a/scripts/Test-PublicPackageConsumer.ps1 b/scripts/Test-PublicPackageConsumer.ps1index 630543b6..1f81b147 100644--- a/scripts/Test-PublicPackageConsumer.ps1+++ b/scripts/Test-PublicPackageConsumer.ps1@@ -14,7 +14,7 @@ foreach ($name in @('PublicPackageSmoke.csproj', 'Program.cs')) {Copy-Item -LiteralPath (Join-Path $root "test-support/PublicPackageSmoke/$name") -Destination $output}$escaped = [Security.SecurityElement]::Escape($feed)-[IO.File]::WriteAllText((Join-Path $output 'NuGet.Config'), "<configuration><packageSources><clear/><add key='candidate' value='$escaped'/><add key='nuget.org' value='https://api.nuget.org/v3/index.json'/></packageSources></configuration>")+[IO.File]::WriteAllText((Join-Path $output 'NuGet.Config'), "<configuration><packageSources><clear/><add key='candidate' value='$escaped'/><add key='nuget.org' value='https://api.nuget.org/v3/index.json'/></packageSources><packageSourceMapping><packageSource key='candidate'><package pattern='Aetheris.*'/></packageSource><packageSource key='nuget.org'><package pattern='*'/></packageSource></packageSourceMapping></configuration>")$cache = Join-Path $output 'packages'$project = Join-Path $output 'PublicPackageSmoke.csproj'dotnet restore $project --configfile (Join-Path $output 'NuGet.Config') --packages $cache --no-cache -m:1 -nr:false -p:ImportDirectoryBuildProps=false -p:ImportDirectoryBuildTargets=false -p:AetherisReleaseVersion=$Versiondiff --git a/scripts/qualify-unknown-fields.py b/scripts/qualify-unknown-fields.pynew file mode 100644index 00000000..1604d740--- /dev/null+++ b/scripts/qualify-unknown-fields.py@@ -0,0 +1,95 @@+"""Mutate every real opening brace in admitted canonical seeds through the real CLI.++This is a qualification mutator, not a language validator. Strings and comments+are skipped; the compiler owns all admission decisions and route classification.+"""+import argparse+import collections+import json+from pathlib import Path+import re+import shutil+import subprocess+++def run(args):+ root = Path(__file__).resolve().parents[1]+ output = args.output.resolve()+ output.mkdir(parents=True, exist_ok=args.resume)+ sources = output / 'sources' / 'Canonical'+ shutil.copytree(root / 'fixtures' / 'Canonical', sources, dirs_exist_ok=args.resume)+ baseline = json.loads(args.seeds.read_text(encoding='utf-8'))+ seeds = [r['source'] for r in baseline if r['validate']['exit'] == 0]+ previous = json.loads((output / 'summary.json').read_text(encoding='utf-8')) if args.resume else {}+ rows = previous.get('probes', [])+ controls = previous.get('controls', [])+ completed = {r['source'] for r in controls if r['exit'] == 0}+ controls = [r for r in controls if r['source'] in completed]+ # Mirror referenced repository files without copying an entire STEP corpus.+ # Paths outside the repository or the qualification directory are never copied.+ for relative in seeds:+ original = root / relative+ destination = sources / Path(relative).relative_to('fixtures/Canonical')+ for literal in re.findall(r'"([^"\n]+)"', original.read_text(encoding='utf-8')):+ requested = Path(literal)+ if requested.is_absolute():+ continue+ dependency = (original.parent / requested).resolve()+ target = (destination.parent / requested).resolve()+ if dependency.is_relative_to(root) and target.is_relative_to(output) and dependency.is_file() and not target.exists():+ target.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(dependency, target)+ # Token-shaped mutation boundaries only; never insert into strings/comments.+ token = re.compile(r'//[^\r\n]*|/\*[\s\S]*?\*/|"(?:\\.|[^"\\])*"|\{')++ def validate(path):+ try:+ p = subprocess.run(['dotnet', str(args.cli.resolve()), 'validate', str(path), '--json'],+ capture_output=True, text=True, encoding='utf-8', timeout=60)+ try:+ payload = json.loads(p.stdout)+ except json.JSONDecodeError:+ payload = {'stderr': p.stderr, 'stdout': p.stdout}+ report = payload.get('firmamentV2Validation', payload)+ return p.returncode, report.get('parserRoute', report.get('domain', 'unreported')), payload+ except subprocess.TimeoutExpired:+ return 'timeout', 'timeout', {}++ for index, relative in enumerate(seeds):+ if relative in completed:+ continue+ source = (root / relative).read_text(encoding='utf-8')+ path = sources / Path(relative).relative_to('fixtures/Canonical')+ exit_code, route, payload = validate(path)+ controls.append({'source': relative, 'exit': exit_code, 'route': route})+ if exit_code != 0:+ (path.parent / (path.name + '.control.json')).write_text(json.dumps(payload, indent=2), encoding='utf-8')+ continue # Missing external resources must not masquerade as field rejection.+ try:+ for match in token.finditer(source):+ if match.group() != '{':+ continue+ position = match.end()+ path.write_text(source[:position] + ' zzUnknownField: 3mm; ' + source[position:], encoding='utf-8')+ code, selected, evidence = validate(path)+ row = {'source': relative, 'offset': position, 'exit': code, 'route': selected}+ rows.append(row)+ if code == 0 or code == 'timeout':+ evidence_path = output / ('accepted' if code == 0 else 'timeouts') / (str(len(rows)) + '.json')+ evidence_path.parent.mkdir(exist_ok=True)+ evidence_path.write_text(json.dumps(evidence, indent=2), encoding='utf-8')+ finally:+ path.write_text(source, encoding='utf-8')+ summary = {'seeds': len(seeds), 'controls': controls, 'probes': rows,+ 'acceptedByRoute': dict(collections.Counter(r['route'] for r in rows if r['exit'] == 0))}+ (output / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n', encoding='utf-8')+ print(f'{index+1}/{len(seeds)} {relative}: {len(rows)} probes', flush=True)+++if __name__ == '__main__':+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--cli', type=Path, required=True)+ parser.add_argument('--seeds', type=Path, required=True, help='Frozen corpus summary.json')+ parser.add_argument('--output', type=Path, required=True)+ parser.add_argument('--resume', action='store_true', help='Resume completed seeds and retry unavailable controls')+ run(parser.parse_args())