Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Correct Firmament validation levels and runtime provenance
Yuechen Lice004be82612
diff --git a/Aetheris.CLI.Tests/BodyStateDebtCliTests.cs b/Aetheris.CLI.Tests/BodyStateDebtCliTests.csnew file mode 100644index 00000000..fd382f69--- /dev/null+++ b/Aetheris.CLI.Tests/BodyStateDebtCliTests.cs@@ -0,0 +1,114 @@+using System.Text.Json;+using Aetheris.CLI;++namespace Aetheris.CLI.Tests;++public sealed class BodyStateDebtCliTests+{+ [Theory]+ [InlineData("box", true)]+ [InlineData("cylinder", true)]+ [InlineData("profile", true)]+ [InlineData("explicit-pmi", true)]+ [InlineData("counterbore-chamfer", true)]+ [InlineData("plain-offset", true)]+ [InlineData("second-hole-after-add", true)]+ [InlineData("unknown-field", false)]+ [InlineData("unsupported-cylinder-edit", false)]+ [InlineData("history-drop", false)]+ public void ValidateBuildAndInspectAgreeOnActualAdmission(string name, bool accepted)+ {+ var path = Path.Combine(Root(), "fixtures/Regression/BodyStateDebt", name + ".firmament");+ var directory = Path.Combine(Root(), "artifacts/local/tests/body-state-debt", Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(directory);+ var output = Path.Combine(directory, "body.step");+ try+ {+ foreach (var command in new[] { "validate", "build", "inspect" })+ {+ var stdout = new StringWriter(); var stderr = new StringWriter();+ string[] args = command == "build" ? [command, path, "--out", output, "--json"] : [command, path, "--json"];+ Assert.True(CliRunner.Run(args, stdout, stderr) == (accepted ? 0 : 1), command + ": " + stdout + stderr);+ using var json = JsonDocument.Parse(stdout.ToString());+ var report = command == "validate" ? json.RootElement.GetProperty("firmamentV2Validation") : json.RootElement;+ if (!accepted)+ Assert.All(report.GetProperty("diagnostics").EnumerateArray(), d =>+ { Assert.False(string.IsNullOrWhiteSpace(d.GetProperty("message").GetString())); Assert.Equal(Path.GetFullPath(path), Path.GetFullPath(d.GetProperty("sourceFile").GetString()!)); });+ }+ Assert.Equal(accepted, File.Exists(output));+ }+ finally { Directory.Delete(directory, true); }+ }++ [Theory]+ [InlineData("Sculpting/sculpted-housing")]+ [InlineData("Structural/square-tube-member")]+ [InlineData("PlasticShell/plastic-shell-basic")]+ public void CommonScalarRequirementsAreAdmittedAndEnforced(string fixture)+ {+ var original = File.ReadAllText(Path.Combine(Root(), "fixtures/Canonical", fixture + ".firmament"));+ var requirements = File.ReadAllText(Path.Combine(Root(), "fixtures/Regression/BodyStateDebt/requirements.fragment.firmament"));+ var directory = Path.Combine(Root(), "artifacts/local/tests/domain-requirements", Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(directory);+ var path = Path.Combine(directory, "source.firmament");+ var output = Path.Combine(directory, "part.step");+ try+ {+ // Compare the same authoritative product before and after a true requirement.+ File.WriteAllText(path, original);+ Assert.Equal(0, CliRunner.Run(["build", path, "--out", output, "--json"], new StringWriter(), new StringWriter()));+ var expectedStep = File.ReadAllText(output);+ foreach (var accepted in new[] { true, false })+ {+ File.Delete(output);+ File.WriteAllText(path, (accepted ? requirements : requirements.Replace("Positive(1mm)", "Positive(-1mm)")) + original);+ foreach (var command in new[] { "validate", "build" })+ {+ var stdout = new StringWriter();+ string[] args = command == "build" ? [command, path, "--out", output, "--json"] : [command, path, "--json"];+ Assert.Equal(accepted ? 0 : 1, CliRunner.Run(args, stdout, new StringWriter()));+ if (!accepted) Assert.Contains("firmament-concept-requirement", stdout.ToString());+ }+ Assert.Equal(accepted, File.Exists(output));+ if (accepted) Assert.Equal(expectedStep, File.ReadAllText(output));+ }+ }+ finally { Directory.Delete(directory, true); }+ }++ [Theory]+ [InlineData("Sculpting/sculpted-housing")]+ [InlineData("PlasticShell/plastic-shell-basic")]+ public void StaticOnlyOptionCannotSilentlyRunTheGeometryCompiler(string fixture)+ {+ var path = Path.Combine(Root(), "fixtures/Canonical", fixture + ".firmament");+ var stdout = new StringWriter();+ Assert.Equal(1, CliRunner.Run(["validate", path, "--parse-only", "--json"], stdout, new StringWriter()));+ using var json = JsonDocument.Parse(stdout.ToString());+ var report = json.RootElement.GetProperty("firmamentV2Validation");+ Assert.Equal("not-validated", report.GetProperty("status").GetString());+ Assert.Equal("NotValidated", report.GetProperty("validationLevel").GetString());+ Assert.Equal("firmament-validation-option-unsupported", report.GetProperty("diagnostics")[0].GetProperty("code").GetString());+ }++ [Theory]+ [InlineData("Structural/square-tube-member")]+ [InlineData("Garment/skirt")]+ public void ExistingStaticDomainAnalyzersRemainAvailable(string fixture)+ {+ var path = Path.Combine(Root(), "fixtures/Canonical", fixture + ".firmament");+ var stdout = new StringWriter(); var stderr = new StringWriter();+ Assert.True(CliRunner.Run(["validate", path, "--parse-only", "--json"], stdout, stderr) == 0, stdout + stderr.ToString());+ using var json = JsonDocument.Parse(stdout.ToString());+ var report = json.RootElement.GetProperty("firmamentV2Validation");+ Assert.Equal("parsed-not-built", report.GetProperty("status").GetString());+ Assert.Equal("ParsedNotBuilt", report.GetProperty("validationLevel").GetString());+ }++ private static string Root()+ {+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;+ return directory!.FullName;+ }+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 149f72b6..ea5f945e 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -834,7 +834,7 @@ public static class CliRunnersurfacePatches = compile.OutputState.SurfacePatches,blendJudgment = compile.OutputState.BlendJudgment,surfaceInventory = export.Inventory,- productBoundary = new { rationalNurbs = export.Inventory.RationalNurbs, admitted = export.Inventory.RationalNurbs == 0 },+ productBoundary = new { rationalNurbs = export.Inventory.RationalNurbs, admitted = export.IsSuccess },timingsMilliseconds = compile.Timings with { StepExportMilliseconds = exportClock.Elapsed.TotalMilliseconds }}, JsonOptions));if (json) stdout.WriteLine(JsonSerializer.Serialize(new@@ -901,7 +901,7 @@ public static class CliRunnerdelta = new { operation.Delta.Preserves, operation.Delta.Replaces, operation.Delta.Removes, operation.Delta.Introduces }})},- realizedHousingEvidence = new { state.Construction.Width, state.Construction.Depth, state.Construction.BaseHeight, state.Construction.CrownWidth, state.Construction.CrownDepth, state.Construction.CrownOffset, state.Construction.FinalHeight },+ realizedHousingEvidence = state.Construction is {} housing ? new { housing.Width, housing.Depth, housing.BaseHeight, housing.CrownWidth, housing.CrownDepth, housing.CrownOffset, housing.FinalHeight } : null,semanticInventory = state.SemanticInventory.Values, surfacePatches = state.SurfacePatches, blendJudgment = state.BlendJudgment, hasDelta = state.Delta is not null};@@ -2395,12 +2395,23 @@ Model CanonicalPanel {if (forgePackPaths.Count > 0 || parseOnly) { stderr.WriteLine("--shadow uses normal production validation; --forge-pack/--parse-only are not supported together with it."); return 1; }return FrontendShadowCommand.Run([sourcePath, "--validate", .. (json ? new[] { "--json" } : []), .. (shadowAst ? new[] { "--ast" } : [])], stdout, stderr);}+ int RejectParseOnly(string domain)+ {+ var diagnostic = new FirmamentV2ValidationDiagnostic("firmament-validation-option-unsupported", "error",+ $"{domain} has no static-only admission path. Omit --parse-only to run its actual validator; no engineering validation was performed.")+ { SourceFile = Path.GetFullPath(sourcePath), Stage = "Validation options" };+ var payload = new { source = sourcePath, status = "not-validated", domain, validationLevel = "NotValidated", diagnostics = new[] { diagnostic } };+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));+ else stderr.WriteLine($"{diagnostic.SourceFile}: {diagnostic.Severity} {diagnostic.Code}: {diagnostic.Message}");+ return 1;+ }var validationSource=File.ReadAllText(sourcePath);var authoredValidationSource = validationSource;var frontend = FirmamentFrontendSchemas.Select(validationSource);if (!frontend.IsSuccess) return WriteFrontendRejection(frontend, validationSource, sourcePath, "validate", json, stdout, stderr);if(FirmamentDrawingCompiler.IsDrawingSource(validationSource)){+ if (parseOnly) return RejectParseOnly("Drawing");var output=Path.GetFullPath(Path.Combine("artifacts","local","drawing-validation",Guid.NewGuid().ToString("N")));try{@@ -2415,6 +2426,7 @@ Model CanonicalPanel {}if (FirmamentAnalysisCompiler.IsAnalysisSource(validationSource)){+ if (parseOnly) return RejectParseOnly("Analysis");var analysis=FirmamentAnalysisCompiler.Compile(frontend.Source,Path.GetFullPath(sourcePath),Path.GetDirectoryName(Path.GetFullPath(sourcePath)));var diagnostics=FirmamentAnalysisCompiler.KernelDiagnostics(analysis).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,validationSource)).ToArray();var payload=new {source=sourcePath,status=analysis.IsSuccess?"bound-not-solved":"invalid",domain="Analysis",validationLevel=analysis.IsSuccess?"BoundNotSolved":"BindingRejected",parserRoute="UnifiedAnalysis",diagnostics};@@ -2424,7 +2436,20 @@ Model CanonicalPanel {}if (Aetheris.Kernel.Firmament.Garment.GarmentAuthoring.HasRoot(validationSource)|| frontend.Schema == FirmamentFrontendSchema.Garment)+ {+ if (parseOnly)+ {+ var garment = Aetheris.Kernel.Firmament.Garment.GarmentAuthoring.Parse(validationSource, Path.GetFullPath(sourcePath));+ var diagnostics = garment.Diagnostics.Select(d => FirmamentBuildAdmissionValidation.Present(new KernelDiagnostic(+ KernelDiagnosticCode.ValidationFailed, KernelDiagnosticSeverity.Error, d.Code + ": " + d.Message, "Firmament.Garment"), sourcePath, validationSource)).ToArray();+ var payload = new { source = sourcePath, status = garment.IsSuccess ? "parsed-not-built" : "invalid", domain = "Garment",+ validationLevel = garment.IsSuccess ? "ParsedNotBuilt" : "BindingRejected", parserRoute = "UnifiedGarment", diagnostics };+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));+ else { stdout.WriteLine("Garment static analysis: " + payload.status); WriteFrontendDiagnostics(diagnostics, stderr); }+ return garment.IsSuccess ? 0 : 1;+ }return GarmentCommand.Run(["inspect", sourcePath, .. (json ? new[] { "--json" } : Array.Empty<string>())], stdout, stderr);+ }if (FirmamentLanguageAnalysisService.HasAssemblyRoot(validationSource, sourcePath)){var sheetMetalAssembly = validationSource.Contains("Use SheetMetal.ProductFamilies", StringComparison.Ordinal);@@ -2454,14 +2479,16 @@ Model CanonicalPanel {validationSource = frontend.Source;if (PlasticShellFirmament.LooksLikePlasticShell(validationSource)){+ if (parseOnly) return RejectParseOnly("PlasticShell");var plastic = PlasticShellFirmament.Compile(validationSource, Path.GetFullPath(sourcePath));- var payload = new { source = sourcePath, status = plastic.IsSuccess ? "valid" : "invalid", domain = "PlasticShell", summary = new { fatalDiagnosticCount = plastic.Diagnostics.Count(x => x.Severity == PlasticDiagnosticSeverity.Error), warningDiagnosticCount = plastic.Diagnostics.Count(x => x.Severity == PlasticDiagnosticSeverity.Warning), gates = plastic.Intent?.Gates.Count ?? 0, standoffs = plastic.Intent?.Standoffs.Count ?? 0, ejectors = plastic.Intent?.Ejectors.Count ?? 0, ribCandidates = plastic.State?.Evidence.RibNetwork?.Candidates.Count ?? 0 }, diagnostics = PlasticShellFirmament.KernelDiagnostics(plastic).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,authoredValidationSource)).ToArray() };+ var payload = new { source = sourcePath, status = plastic.IsSuccess ? "valid" : "invalid", domain = "PlasticShell", validationLevel = plastic.IsSuccess ? "Built" : "BuildRejected", parserRoute = "UnifiedPlasticShell", summary = new { fatalDiagnosticCount = plastic.Diagnostics.Count(x => x.Severity == PlasticDiagnosticSeverity.Error), warningDiagnosticCount = plastic.Diagnostics.Count(x => x.Severity == PlasticDiagnosticSeverity.Warning), gates = plastic.Intent?.Gates.Count ?? 0, standoffs = plastic.Intent?.Standoffs.Count ?? 0, ejectors = plastic.Intent?.Ejectors.Count ?? 0, ribCandidates = plastic.State?.Evidence.RibNetwork?.Candidates.Count ?? 0 }, diagnostics = PlasticShellFirmament.KernelDiagnostics(plastic).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,authoredValidationSource)).ToArray() };if (json) stdout.WriteLine(JsonSerializer.Serialize(new { plasticShellValidation = payload }, JsonOptions));else {stdout.WriteLine($"PlasticShell validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, {payload.summary.warningDiagnosticCount} warning)");WriteFrontendDiagnostics(payload.diagnostics,stderr);}return plastic.IsSuccess ? 0 : 1;}if (SculptingAuthoring.IsSculptingSource(validationSource)){+ if (parseOnly) return RejectParseOnly("Sculpting");var sculpt = SculptingAuthoring.Compile(validationSource,Path.GetFullPath(sourcePath));var payload = new { source = sourcePath, status = sculpt.IsSuccess ? "valid" : "invalid", domain = "Sculpting", validationLevel=sculpt.IsSuccess?"Built":"BuildRejected", parserRoute="UnifiedSculpting", summary = new { fatalDiagnosticCount = sculpt.Diagnostics.Count, warningDiagnosticCount = 0, states = sculpt.States.Count }, diagnostics = SculptingAuthoring.KernelDiagnostics(sculpt).Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,authoredValidationSource)).ToArray() };if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));@@ -2470,6 +2497,7 @@ Model CanonicalPanel {}if (PlateauAuthoring.IsSource(validationSource) && !System.Text.RegularExpressions.Regex.IsMatch(validationSource, @"\bAssembly\s+")){+ if (parseOnly) return RejectParseOnly("Plateau");var plateau = FirmamentBuildAndExport.CompileSource(validationSource, Path.GetDirectoryName(Path.GetFullPath(sourcePath)));var payload = new { source = sourcePath, status = plateau.IsSuccess ? "valid" : "invalid", domain = "Plateau", diagnostics = plateau.Diagnostics };if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));@@ -2478,6 +2506,7 @@ Model CanonicalPanel {}if (PipingAuthoring.IsPipingSource(validationSource)){+ if (parseOnly) return RejectParseOnly("Piping");var piping = PipingAuthoring.Compile(validationSource, Path.GetFullPath(sourcePath));var payload = new { source = sourcePath, status = piping.IsSuccess ? "valid" : "invalid", domain = "Piping", validationLevel = piping.IsSuccess ? "Built" : "BuildRejected", parserRoute = "UnifiedPiping", summary = new { fatalDiagnosticCount = piping.Diagnostics.Count, warningDiagnosticCount = 0, connections = piping.Report?.Connections.Count ?? 0, routes = piping.Report?.Routes.Count ?? 0 }, diagnostics = piping.KernelDiagnostics().Select(d => FirmamentBuildAdmissionValidation.Present(d, Path.GetFullPath(sourcePath), validationSource)).ToArray() };if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));@@ -2490,6 +2519,17 @@ Model CanonicalPanel {}if (StructuralAuthoring.IsStructuralSource(validationSource)){+ if (parseOnly)+ {+ var diagnostics = StructuralAuthoring.Analyze(validationSource, Path.GetFullPath(sourcePath))+ .Select(d => FirmamentBuildAdmissionValidation.Present(d, sourcePath, validationSource)).ToArray();+ var accepted = diagnostics.All(d => d.Severity is not ("error" or "fatal"));+ var staticReport = new { source = sourcePath, status = accepted ? "parsed-not-built" : "invalid", domain = "Structural",+ validationLevel = accepted ? "ParsedNotBuilt" : "BindingRejected", parserRoute = "UnifiedStructural", diagnostics };+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = staticReport }, JsonOptions));+ else { stdout.WriteLine("Structural static analysis: " + staticReport.status); WriteFrontendDiagnostics(diagnostics, stderr); }+ return accepted ? 0 : 1;+ }var structural = StructuralAuthoring.Compile(validationSource, Path.GetFullPath(sourcePath));var payload = new { source = sourcePath, status = structural.IsSuccess ? "valid" : "invalid", domain = "Structural", validationLevel=structural.IsSuccess?"Built":"BuildRejected", parserRoute="UnifiedStructural", summary = new { fatalDiagnosticCount = structural.Diagnostics.Count, warningDiagnosticCount = 0, members = structural.Report?.Members.Count ?? 0, joints = structural.Report?.Joints.Count ?? 0 }, diagnostics = structural.KernelDiagnostics().Select(d=>FirmamentBuildAdmissionValidation.Present(d,sourcePath,authoredValidationSource)).ToArray() };if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));@@ -5211,7 +5251,7 @@ Model CanonicalPanel {stdout.WriteLine(TopLevelUsage);stdout.WriteLine();stdout.WriteLine("Commands:");- stdout.WriteLine(" validate Check Firmament source without materializing geometry.");+ stdout.WriteLine(" validate Validate source through its engineering admission path.");stdout.WriteLine(" format Prefer mixed-case vocabulary spellings; preserve layout and authored names.");stdout.WriteLine(" build Compile Firmament to exact STEP AP242.");stdout.WriteLine(" mesh Export a supported exact B-rep as STL or topology-preserving OBJ.");@@ -5309,7 +5349,7 @@ Model CanonicalPanel {stdout.WriteLine(" --explain Show V2 parser route, admission level and available instance counts.");stdout.WriteLine(" --shadow Developer report with separate original-source AST, bounded comparison and normal production validation.");stdout.WriteLine(" --ast Include the detailed AST with --shadow. Structural parsing does not establish semantic admission.");- stdout.WriteLine(" --parse-only Check static semantics only; success is labelled parsed-not-built.");+ stdout.WriteLine(" --parse-only Use an available static analyzer; success is labelled parsed-not-built.");stdout.WriteLine(" --forge-pack <path> Load a trusted local .NET assembly containing IForgeConceptPack implementations. This executes local code; Aetheris does not sandbox external packs. Do not load untrusted packs.");}diff --git a/Aetheris.Kernel.Firmament.Tests/ProfileTemplateProjectionTests.cs b/Aetheris.Kernel.Firmament.Tests/ProfileTemplateProjectionTests.csnew file mode 100644index 00000000..7488f4b8--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/ProfileTemplateProjectionTests.cs@@ -0,0 +1,49 @@+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;+using Xunit;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class ProfileTemplateProjectionTests+{+ [Fact]+ public void RecordMemberValidationDoesNotInterpretStringContentsAsReferences()+ {+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;+ var source = File.ReadAllText(Path.Combine(directory!.FullName, "fixtures/Regression/BodyStateDebt/record-member-string.firmament"));+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.True(parsed.IsSuccess, string.Join(";", parsed.Diagnostics));+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, string.Join(";", built.Diagnostics.Select(d => d.Message)));+ Assert.Equal(new[] { 40d, 20d, 5d }, parsed.Document!.Solid.Box!.Size);+ var invalid = FirmamentV2Parser.Parse(source.Replace("[spec.width,", "[spec.Missing,"));+ Assert.False(invalid.IsSuccess);+ Assert.Contains(invalid.Diagnostics, d => d.StartsWith("firmament-template-unknown-record-member:spec.Missing", StringComparison.Ordinal));+ }++ [Fact]+ public void SpecializationRewritesBoundGuidesWithoutCorruptingFieldsOrStrings()+ {+ var directory = new DirectoryInfo(AppContext.BaseDirectory);+ while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "Aetheris.slnx"))) directory = directory.Parent;+ var body = File.ReadAllText(Path.Combine(directory!.FullName, "fixtures/Regression/BodyStateDebt/profile-hygiene.fragment.firmament"));+ var errors = new List<string>();+ var output = ProfileTemplateProjection.Render("P", "", body, errors);+ Assert.Empty(errors);+ var syntax = FirmamentSyntaxParser.Parse(output);+ Assert.True(syntax.IsSuccess);+ var declarations = FirmamentSyntaxTraversal.Declarations(syntax.Document).ToArray();+ Assert.Contains(declarations, d => d.Name?.Text == "P_Local");+ Assert.Equal(2, declarations.Count(d => d.Type.Name.Text == "Point2" && d.Name?.Text == "P_A"));+ Assert.Contains(declarations, d => d.Type.Name.Text == "Segment" && d.Name?.Text == "P_A");+ var members = FirmamentSyntaxTraversal.Expressions(syntax.Document).OfType<MemberSyntax>()+ .Select(m => FirmamentSyntaxValues.Reference(m)).ToArray();+ Assert.Contains("P_Local.P_A", members);+ Assert.Contains("External.A", members);+ Assert.DoesNotContain("External.P_A", members);+ Assert.Contains("\"A Local.A External.A\"", output);+ Assert.Contains("A: \"A\"", output);+ Assert.DoesNotContain(declarations.Single(d => d.Type.Name.Text == "Profile").Body!.Statements.OfType<DeclarationSyntax>(), d => d.Type.Name.Text == "Point2");+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 251c3c9f..855dc9b3 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -168,7 +168,7 @@ public static class FirmamentBuildAndExport{var parsed = ParseSemanticSource(source, sourceDirectory);if (!parsed.IsSuccess || parsed.Document is null) return export;- export = export with { DocumentName = parsed.Document.ModelName };+ export = export with { DocumentName = parsed.Document.ModelName, RuntimeAdmissionDocument = parsed.Document };var edgeFinishes = (parsed.Document.ModifyBlocks ?? []).SelectMany(modification => (modification.EdgeFinishes ?? []).Select(finish => new FirmamentEngineeringFeatureReport(@@ -338,7 +338,7 @@ public static class FirmamentBuildAndExportreturn KernelResult<FirmamentStepExportResult>.Failure(materialized.Diagnostics.Select(d => SchemaDiagnostic(d.Code + ":" + d.Message)).ToArray());var step = Step242Exporter.ExportBody(materialized.Body, new Step242ExportOptions { ProductName = chain.StableId });return step.IsSuccess- ? KernelResult<FirmamentStepExportResult>.Success(new(step.Value, chain.StableId, 0, "section-chain", "section-chain"))+ ? KernelResult<FirmamentStepExportResult>.Success(new(step.Value, chain.StableId, 0, "section-chain", "section-chain") { RuntimeBodySourceName = chain.StableId }): KernelResult<FirmamentStepExportResult>.Failure(step.Diagnostics);}if (v2Parse.BoundGear is { } gear) return ExportGear(gear);@@ -375,7 +375,7 @@ public static class FirmamentBuildAndExportreimportedManifold, hash);return KernelResult<FirmamentStepExportResult>.Success(new(step.Value, authored.Name, 0, "bounded-revolve", "revolve", Revolve: report,EngineeringFeatures: [new(authored.Name, "Revolve", authored.StableId, authored.Name, authored.Axis.StableId, authored.Profile.Name,- authored.SweepRadians, "SweepRadians", "Base", PolicySource: "ResolvedProfileRevolveEmitter", MaterializationRoute: "RevolveBRepPlan")]));+ authored.SweepRadians, "SweepRadians", "Base", PolicySource: "ResolvedProfileRevolveEmitter", MaterializationRoute: "RevolveBRepPlan")]) { RuntimeBodySourceName = authored.Name });}if (explicitSchema == FirmamentFrontendSchema.WireForm || !v2Parse.OwnsUnifiedAdmission && WireFormAuthoring.IsWireFormSource(materializerSource)){@@ -409,7 +409,7 @@ public static class FirmamentBuildAndExportoperation.Name, operation switch { WireStraightAir => "Straight", WireBendAir => "Bend", WireAxisCoilAir => "Helix", WireSurfaceCoilAir => "SurfaceCoil", WireKnotPathAir => "KnotPath", _ => "Unknown" }, operation.StableId(authored.Value.Name),authored.Value.Name, "WireState", "CircularSection", operation.LengthMm, "CenterlineLength", "Add",PolicySource: "WireFormFeatureAir", MaterializationRoute: "WireFormCenterlineAir->CircularSweepBRepPlan")).ToArray())- { RuntimeBody = reimport.Value }, []);+ { RuntimeBody = reimport.Value, RuntimeBodySourceName = authored.Value.Name }, []);}if (explicitSchema == FirmamentFrontendSchema.Sweep || !v2Parse.OwnsUnifiedAdmission && CircularSweepAuthoring.IsSweepSource(materializerSource)){@@ -449,7 +449,7 @@ public static class FirmamentBuildAndExportreturn KernelResult<FirmamentStepExportResult>.Success(new FirmamentStepExportResult(step.Value, authored.Value.Name, 0,"circular-sweep", "sweep", Sweep: report,EngineeringFeatures: [new(authored.Value.Name, "Sweep", "sweep:" + authored.Value.Name, authored.Value.Name,- authored.Value.Path.StableId, "Circle", authored.Value.Diameter, "Diameter", "Add", PolicySource: "CircularSweepFeatureAir", MaterializationRoute: "CircularSweepBRepPlan")]),+ authored.Value.Path.StableId, "Circle", authored.Value.Diameter, "Diameter", "Add", PolicySource: "CircularSweepFeatureAir", MaterializationRoute: "CircularSweepBRepPlan")]) { RuntimeBodySourceName = authored.Value.Name },[]);}if (v2Parse.BoundComposition is not null || (!v2Parse.OwnsUnifiedAdmission && PrismaticProfileCompositionParser.IsCompositionSource(materializerSource)))@@ -721,7 +721,7 @@ public static class FirmamentBuildAndExportsurfaces.Count(kind => kind == SurfaceGeometryKind.Cone), surfaces.Count(kind => kind == SurfaceGeometryKind.BSplineSurfaceWithKnots),surfaces.Count(kind => kind == SurfaceGeometryKind.LinearExtrusion), FirmamentManifoldChecker.IsManifold(materialized.Body),true, true, hash, "DeterministicExactBRepAP242", gear.Family is GearFamily.BevelGear or GearFamily.MiterGear ? "BoundedStraightBevel" : "QualifiedX0");- return KernelResult<FirmamentStepExportResult>.Success(new(step.Value, $"gear:{gear.Name}", 0, "gear", gear.Family.ToString(), Gear: report));+ return KernelResult<FirmamentStepExportResult>.Success(new(step.Value, $"gear:{gear.Name}", 0, "gear", gear.Family.ToString(), Gear: report) { RuntimeBodySourceName = gear.Name });}private static FirmamentV2ParseResult ParseSemanticSource(string source, string? sourceDirectory)diff --git a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.csindex 3cf095fa..8fee46db 100644--- a/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs+++ b/Aetheris.Kernel.Firmament/FirmamentStepExportResult.cs@@ -42,6 +42,10 @@ public sealed record FirmamentStepExportResult(// It is intentionally absent from CLI/JSON artifact serialization.[JsonIgnore] public BrepBody? RuntimeBody { get; init; }[JsonIgnore] public SemanticTopologyCorrespondence? RuntimeCorrespondence { get; init; }+ // Named product identity supplied by the actual native materializer. Separate+ // from diagnostic feature ids such as "gear:Name" and primitive bridge names.+ [JsonIgnore] public string? RuntimeBodySourceName { get; init; }+ [JsonIgnore] internal Aetheris.Kernel.Firmament.FirmamentV2.FirmamentV2Document? RuntimeAdmissionDocument { get; init; }public FirmamentCirRetention? Cir { get; init; }public FirmamentMakerMarkReport? MakerMark { get; init; }}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.csindex 4da4ba08..791abdcc 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/CanonicalStaticAuthoring.cs@@ -489,7 +489,12 @@ internal static class CanonicalStaticAuthoringinternal static string ExpandDomainPatterns(string source,string ownerType,FirmamentCompileTimeValues scalars,List<string> diagnostics,IReadOnlySet<string> domainResults){var syntax=FirmamentSyntaxParser.Parse(source).Document;- var patterns=FirmamentSyntaxTraversal.Declarations(syntax).Where(d=>d.Type.Name.Text=="Pattern" && d.Clauses.Any(c=>c.Kind==ClauseKind.Over)).ToArray();+ var declarations = FirmamentSyntaxTraversal.Declarations(syntax).ToArray();+ // Each owner expands only its direct Pattern children. Patterns inside+ // an engineering Compose/Modify retain that owner's admission semantics.+ // Unsupported placements remain in the AST for scope closure to reject.+ var patterns=declarations.Where(d=>d.Type.Name.Text=="Pattern" && d.Clauses.Any(c=>c.Kind==ClauseKind.Over)+ && declarations.Any(owner => owner.Type.Name.Text == ownerType && owner.Body?.Statements.Contains(d) == true)).ToArray();if(patterns.Length==0)return source;var catalog=FirmamentV2TemplateExpansion.ReadDataCatalog(source,diagnostics,scalars);var types=catalog.Types.ToDictionary(p=>p.Key,p=>new FirmamentV2RecordTypeDecl(p.Key,p.Value.Fields,p.Value.SourceSpan),StringComparer.Ordinal);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentDomainBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentDomainBinding.csindex bb66293f..bac36b78 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentDomainBinding.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentDomainBinding.cs@@ -70,6 +70,18 @@ public sealed class FirmamentDomainBindinginternal FirmamentV2TemplateExpansion.DataCatalog DataCatalog(List<string> diagnostics) => FirmamentV2TemplateExpansion.ReadDataCatalog(Source, diagnostics, values);internal string DataName(string identity) => values.DataBindings.FirstOrDefault(d => d.Identity == identity)?.Name ?? identity;public bool OwnsData(DeclarationSyntax declaration) => FirmamentDataBinding.NamespaceFor(declaration) is not null;+ public bool OwnsCommonDeclaration(DeclarationSyntax declaration) => OwnsData(declaration)+ || declaration.Type.Name.Text is "Concept" or "Require";++ /// <summary>Common requirements use the existing Concept evaluator and shared+ /// compile-time values. Domain geometry is not fabricated as scalar data.</summary>+ public IReadOnlyList<FirmamentV2ValidationDiagnostic> BindCommonRequirements(IEnumerable<StatementSyntax> statements)+ {+ var previous = Diagnostics.ToHashSet();+ foreach (var requirement in statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Require"))+ CheckRequirement(requirement);+ return Diagnostics.Where(d => !previous.Contains(d)).ToArray();+ }public FirmamentV2SourceSpan? OriginalSpan(FirmamentV2SourceSpan span){if(!IsExpanded)return span;diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.csindex c8248dd6..500ea93a 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2TemplateExpansion.cs@@ -311,7 +311,7 @@ internal static class FirmamentV2TemplateExpansionStart: declaration.SourceSpan.Start,Length: declaration.SourceSpan.Length,Text: ReferenceEquals(declaration, template)- ? RenderOutput(template.TargetKind, instanceName, template.HeaderTail, body) + liftedPmi+ ? RenderOutput(template.TargetKind, instanceName, template.HeaderTail, body, diagnostics) + liftedPmi: string.Empty)).OrderByDescending(change => change.Start).ToArray();@@ -424,7 +424,7 @@ internal static class FirmamentV2TemplateExpansionbody = ExpandNestedApplications(body, template, source, enums, recordTypes, staticRecords,diagnostics, instantiations, [template], scalars);var liftedPmi = LiftPmi(body, out body);- changes.Add((application.SourceSpan.Start, application.SourceSpan.Length, RenderOutput(template.TargetKind, application.InstanceName, template.HeaderTail, body) + liftedPmi));+ changes.Add((application.SourceSpan.Start, application.SourceSpan.Length, RenderOutput(template.TargetKind, application.InstanceName, template.HeaderTail, body, diagnostics) + liftedPmi));}if (HasErrors(diagnostics)) return null;foreach (var change in changes.OrderByDescending(c => c.Start)) source = source.Remove(change.Start, change.Length).Insert(change.Start, change.Text);@@ -458,30 +458,10 @@ internal static class FirmamentV2TemplateExpansionreturn syntax.Declarations.Where(d => ReferenceEquals(d.DefinitionScope, syntax.ExportScope));}- private static string RenderOutput(string kind, string instance, string tail, string body)+ private static string RenderOutput(string kind, string instance, string tail, string body, List<string> diagnostics){- // Profile guides belong to each specialization; span identities stay shared.- if (kind == "Profile")- {- var names = Regex.Matches(body, @"\b(?:Concept\s+Struct|Curve2|Point2|Line2|CubicBezier2|Circle2|Arc2|Rect2|RoundedRect2|Ellipse2|Path2)\s+(?<name>[A-Za-z_]\w*)\s*\{")- .Select(m => m.Groups["name"].Value).Distinct(StringComparer.Ordinal).ToArray();- foreach (var name in names)- body = Regex.Replace(body, $@"\b{Regex.Escape(name)}\b", instance + "_" + name);- }- var prelude = "";- if (kind == "Profile")- {- for (var offset = 0; offset < body.Length;)- {- var match = Regex.Match(body[offset..], @"\b(?:Concept\s+Struct|Point2|Line2|CubicBezier2|Circle2|Arc2|Rect2|RoundedRect2|Ellipse2|Path2)\s+[A-Za-z_]\w*\s*\{");- if (!match.Success) break;- var start = offset + match.Index; var open = body.IndexOf('{', start); var close = Matching(body, open, '{', '}');- if (close < 0) break;- prelude += body[start..(close + 1)] + "\n";- body = body.Remove(start, close - start + 1); offset = start;- }- }- return prelude + $"{kind} {instance}{tail} {{{body}}}";+ if (kind == "Profile") return ProfileTemplateProjection.Render(instance, tail, body, diagnostics);+ return $"{kind} {instance}{tail} {{{body}}}";}private static BoundTemplateArguments? Bind(TemplateDeclarationIr template, TemplateApplicationIr application, string source, IReadOnlyDictionary<string, ImmutableHashSet<string>> enums,@@ -959,10 +939,20 @@ internal static class FirmamentV2TemplateExpansion}private static bool ValidateRecordMembers(string body, BoundTemplateArguments bound, List<string> diagnostics){+ var syntax = FirmamentSyntaxParser.Parse(body).Document;+ var declarations = FirmamentSyntaxTraversal.Declarations(syntax).ToArray();+ var mappings = FirmamentSyntaxTraversal.Statements(syntax).OfType<MappingSyntax>().ToArray();foreach (var record in bound.RecordArguments.Values)- foreach (var member in Regex.Matches(body, $@"\b{Regex.Escape(record.Parameter)}\s*\.\s*(?<member>[A-Za-z_]\w*)", RegexOptions.CultureInvariant)- .Cast<Match>().Select(match => match.Groups["member"].Value).Distinct(StringComparer.Ordinal))+ {+ bool Shadowed(MemberSyntax member) => declarations.Any(d => FirmamentCompileTimeValues.Encloses(d.Span, member.Span)+ && (d.Parameters.Any(p => p.Name?.Text == record.Parameter)+ || d.Modifiers.Where(m => m.Name.Text == "Template").SelectMany(m => m.Arguments).Any(p => p.Name?.Text == record.Parameter)))+ || mappings.Any(m => m.Key.Text == record.Parameter && FirmamentCompileTimeValues.Encloses(m.Span, member.Span));+ foreach (var member in FirmamentSyntaxTraversal.Expressions(syntax).OfType<MemberSyntax>()+ .Where(m => m.Target is ReferenceSyntax r && r.Name.Text == record.Parameter && !Shadowed(m))+ .Select(m => m.Member.Text).Distinct(StringComparer.Ordinal))if (!record.Fields.ContainsKey(member)) diagnostics.Add(UnknownRecordMember + $":{record.Parameter}.{member}:record-{record.TypeName}");+ }return !HasErrors(diagnostics);}private static string? ResolveTemplateMatches(string body, BoundTemplateArguments bound, List<string> diagnostics,@@ -1131,7 +1121,7 @@ internal static class FirmamentV2TemplateExpansion// Feature AIR. The instantiation record above preserves the semantic boundary;// material grammar receives concrete declarations without unsupported nested Structs.changes.Add((application.SourceSpan.Start, application.SourceSpan.Length,- (template.TargetKind == "Profile" ? RenderOutput("Profile", application.InstanceName, template.HeaderTail, specializedBody) : specializedBody) + liftedPmi));+ (template.TargetKind == "Profile" ? RenderOutput("Profile", application.InstanceName, template.HeaderTail, specializedBody, diagnostics) : specializedBody) + liftedPmi));}foreach (var change in changes.OrderByDescending(change => change.Start))body = body.Remove(change.Start, change.Length).Insert(change.Start, change.Text);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileTemplateProjection.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileTemplateProjection.csnew file mode 100644index 00000000..6b5fa4e9--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileTemplateProjection.cs@@ -0,0 +1,102 @@+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++/// <summary>Specialization hygiene for Profile-local construction. References and+/// published segment names are distinct from fields, types and string contents.</summary>+internal sealed class ProfileTemplateProjection(string instance) : FirmamentSyntaxRewriter+{+ private readonly Dictionary<BlockSyntax, FirmamentBindingScope> scopes = new(ReferenceEqualityComparer.Instance);+ private readonly Dictionary<DeclarationSyntax, string> names = new(ReferenceEqualityComparer.Instance);+ private readonly Stack<HashSet<string>> parameters = new();+ private FirmamentBindingScope scope = new(null, "profile");++ internal static string Render(string instance, string tail, string body, List<string> diagnostics)+ {+ var syntax = FirmamentSyntaxParser.Parse(body);+ if (!syntax.IsSuccess)+ {+ diagnostics.AddRange(syntax.Diagnostics.Select(d => d.Code + ": " + d.Message));+ return "Profile " + instance + tail + " {" + body + "}";+ }+ var block = new BlockSyntax(syntax.Document.Statements, syntax.Document.Span) { Delimited = false };+ var projection = new ProfileTemplateProjection(instance);+ projection.Collect(block, null);+ var result = projection.Block(block).Statements;+ var guides = result.OfType<DeclarationSyntax>().Where(IsGuide).ToHashSet<StatementSyntax>();+ return FirmamentSyntaxWriter.Statements(result.Where(guides.Contains), body) + "\nProfile " + instance + tail + " {\n"+ + FirmamentSyntaxWriter.Statements(result.Where(s => !guides.Contains(s)), body) + "\n}";+ }++ private static bool IsGuide(DeclarationSyntax d) =>+ d.Type.Name.Text == "Struct" && d.Modifiers.Any(m => m.Name.Text == "Concept")+ || ProfileAuthoringParser.OwnsDeclaration(d) && d.Type.Name.Text is not ("Profile" or "Span");++ private void Collect(BlockSyntax block, FirmamentBindingScope? parent)+ {+ var local = new FirmamentBindingScope(parent, "profile specialization");+ scopes.Add(block, local);+ foreach (var declaration in block.Statements.OfType<DeclarationSyntax>())+ {+ // Loop and Segment labels have their own identity namespace. They do+ // not shadow the construction guide a trace inside them references.+ if (declaration.Type.Name.Text is not ("Loop" or "Segment")) local.Declare("value", declaration);+ if (declaration.Name is {} name && IsGuide(declaration)) names.Add(declaration, instance + "_" + name.Text);+ }+ foreach (var declaration in block.Statements.OfType<DeclarationSyntax>())+ if (declaration.Body is {} child) Collect(child, local);+ foreach (var nested in block.Statements.OfType<StatementBlockSyntax>()) Collect(nested.Body, local);+ }++ internal override BlockSyntax Block(BlockSyntax block)+ {+ var enclosing = scope;+ if (!scopes.TryGetValue(block, out var local)) { Collect(block, enclosing); local = scopes[block]; }+ scope = local;+ var result = base.Block(block);+ scope = enclosing;+ return result;+ }++ internal override StatementSyntax Statement(StatementSyntax statement)+ {+ var shadowed = statement is DeclarationSyntax d ? d.Parameters.Select(p => p.Name?.Text).OfType<string>()+ : statement is MappingSyntax m ? [m.Key.Text] : Enumerable.Empty<string>();+ parameters.Push(shadowed.ToHashSet(StringComparer.Ordinal));+ var result = base.Statement(statement);+ parameters.Pop();+ if (statement is DeclarationSyntax original && result is DeclarationSyntax { Name: {} label } rewritten)+ {+ if (names.TryGetValue(original, out var renamed)) return rewritten with { Name = label with { Text = renamed } };+ // Retain existing published specialization identities when a Segment+ // was named after a local guide. Do not rename unrelated labels.+ if (original.Type.Name.Text == "Segment" && Resolve(label.Text) is {} guide && names.TryGetValue(guide, out renamed))+ return rewritten with { Name = label with { Text = renamed } };+ }+ return result;+ }++ private DeclarationSyntax? Resolve(string name) => parameters.Any(p => p.Contains(name)) ? null : scope.Resolve("value", name);+ private DeclarationSyntax? Referent(ExpressionSyntax expression) => expression switch+ {+ ReferenceSyntax r => Resolve(r.Name.Text),+ MemberSyntax m => Referent(m.Target)?.Body?.Statements.OfType<DeclarationSyntax>().FirstOrDefault(d => d.Name?.Text == m.Member.Text),+ _ => null+ };++ internal override ExpressionSyntax Expression(ExpressionSyntax expression)+ {+ if (expression is ReferenceSyntax r && Resolve(r.Name.Text) is {} declaration && names.TryGetValue(declaration, out var name))+ return r with { Name = r.Name with { Text = name } };+ if (expression is MemberSyntax m)+ return m with { Target = Expression(m.Target), Member = Referent(m) is {} member && names.TryGetValue(member, out var renamed)+ ? m.Member with { Text = renamed } : m.Member };+ if (expression is AliasSyntax alias && Resolve(alias.Name.Text) is {} guide && names.TryGetValue(guide, out var label))+ return alias with { Value = Expression(alias.Value), Name = alias.Name with { Text = label } };+ // Constructor names and typed object names occupy the type namespace.+ if (expression is CallSyntax { Target: ReferenceSyntax } call) return call with { Arguments = call.Arguments.Select(Argument).ToArray() };+ if (expression is ObjectSyntax obj) return obj with { Body = Block(obj.Body) };+ if (expression is TypedValueSyntax typed) return typed with { Value = Expression(typed.Value) };+ return base.Expression(expression);+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxOrigins.cs b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxOrigins.csindex af2aab7a..60b11ee2 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxOrigins.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/Syntax/FirmamentSyntaxOrigins.cs@@ -33,8 +33,14 @@ internal sealed class FirmamentSyntaxOrigins(DocumentSyntax original, DocumentSyvar ordinal = counts.GetValueOrDefault(label); counts[label] = ordinal + 1;var identity = path + "/" + label + "#" + ordinal;result[identity] = statement.Span;+ if (statement is FieldSyntax field)+ {+ result[identity + "/name"] = field.Name.Span;+ result[identity + "/value"] = field.Value.Span;+ }if (statement is DeclarationSyntax d){+ if (d.Name is {} name) result[identity + "/name"] = name.Span;if (d.Body is not null) Scope(d.Body.Statements, identity);if (d.Initializer is CallSyntax call) result[identity + "/invocation"] = call.Span;}diff --git a/Aetheris.Kernel.Firmament/Structural/StructuralAuthoring.cs b/Aetheris.Kernel.Firmament/Structural/StructuralAuthoring.csindex fa18e1b8..5b9bbf58 100644--- a/Aetheris.Kernel.Firmament/Structural/StructuralAuthoring.cs+++ b/Aetheris.Kernel.Firmament/Structural/StructuralAuthoring.cs@@ -195,8 +195,10 @@ public static class StructuralAuthoringforeach(var scope in scopes){var units=scope.Word("Units");if(units is not null && units!="mm")d.Add("structural-units-invalid: structural authoring uses millimetres");- foreach(var data in scope.Declaration.Body?.Statements.OfType<DeclarationSyntax>().Where(binding.OwnsData)??[])scope.Consume(data);+ foreach(var data in scope.Declaration.Body?.Statements.OfType<DeclarationSyntax>().Where(binding.OwnsCommonDeclaration)??[])scope.Consume(data);}+ var requirements = binding.BindCommonRequirements(scopes.SelectMany(scope => scope.Declaration.Body?.Statements ?? []));+ frontend.AddRange(requirements); d.AddRange(requirements.Select(e => e.Code + ": " + e.Message));IReadOnlyList<Block> Blocks(string kind)=>owner.Children(kind);var structures=Blocks("Structure");if(structures.Count!=1){d.Add("structural-missing-structure: exactly one Structure is required");return null;}diff --git a/Aetheris.Kernel.Firmament/Surfacing/ConstructionStateReplayer.cs b/Aetheris.Kernel.Firmament/Surfacing/ConstructionStateReplayer.csnew file mode 100644index 00000000..512b2b68--- /dev/null+++ b/Aetheris.Kernel.Firmament/Surfacing/ConstructionStateReplayer.cs@@ -0,0 +1,126 @@+using Aetheris.Kernel.Firmament;++namespace Aetheris.Surfacing;++public sealed record ConstructionReplayStep(+ int Index,+ string OperationId,+ string OperationKind,+ BodyStateId AuthoredPredecessor,+ BodyStateId RealizedPredecessor,+ BodyStateId? RealizedOutput,+ bool Succeeded,+ IReadOnlyList<SculptDiagnostic> Diagnostics);++public sealed record ConstructionReplayResult(+ bool IsSuccess,+ BodyState? OutputState,+ BodyState? AuthoritativePredecessor,+ ConstructionOperationState? FailedOperation,+ IReadOnlyList<ConstructionReplayStep> Steps,+ IReadOnlyList<SculptDiagnostic> Diagnostics);++/// <summary>Correctness-baseline full replay of one linear typed construction program.</summary>+public static class ConstructionStateReplayer+{+ public static ConstructionReplayResult Replay(ConstructionState constructionState, string? outputName = null)+ {+ ArgumentNullException.ThrowIfNull(constructionState);+ if (!StringComparer.Ordinal.Equals(constructionState.SchemaId, ConstructionState.CurrentSchemaId)+ || constructionState.SchemaVersion != ConstructionState.CurrentSchemaVersion)+ return Failure(null, null, null, [], "bodystate-construction-version-unsupported",+ $"ConstructionState schema '{constructionState.SchemaId}' version {constructionState.SchemaVersion} is unsupported; expected {ConstructionState.CurrentSchemaId} v{ConstructionState.CurrentSchemaVersion}.");++ SculptResult created;+ switch (constructionState.Base)+ {+ case EngineeringSourceConstruction engineering when engineering.SchemaVersion == 1:+ created = EngineeringBodyStateConstruction.Realize(engineering);+ break;+ case EngineeringSourceConstruction engineering:+ return Failure(null, null, null, [], "bodystate-base-version-unsupported",+ $"BaseConstruction '{engineering.BaseId}' payload version {engineering.SchemaVersion} is unsupported.");+ case HousingBaseConstruction housing when housing.SchemaVersion == 1:+ var recipe = housing.Housing;+ created = SculptedHousingFactory.CreateBase(housing.BaseId, recipe.Width, recipe.Depth, recipe.BaseHeight, recipe.Holes);+ break;+ case HousingBaseConstruction housing:+ return Failure(null, null, null, [], "bodystate-base-version-unsupported",+ $"BaseConstruction '{housing.BaseId}' payload version {housing.SchemaVersion} is unsupported.");+ default:+ return Failure(null, null, null, [], "bodystate-base-kind-unsupported",+ $"BaseConstruction kind '{constructionState.Base.BaseKind}' is not admitted by this runtime.");+ }++ if (!created.IsSuccess || created.OutputState is null)+ return new(false, null, null, null, [], [new("bodystate-base-replay-failed",+ "BaseConstruction could not be realized: " + string.Join(" | ", created.Diagnostics.Select(item => $"{item.Code}:{item.Message}"))) ]);++ var current = created.OutputState with { ConstructionAuthority = constructionState with { Operations = [] },+ AuthoredName = constructionState.Operations.Count == 0 && !string.IsNullOrWhiteSpace(outputName) ? outputName! : created.OutputState.AuthoredName };+ var steps = new List<ConstructionReplayStep>();+ for (var index = 0; index < constructionState.Operations.Count; index++)+ {+ var authored = constructionState.Operations[index];+ if (index > 0 && authored.PredecessorStateId != constructionState.Operations[index - 1].OutputStateId)+ return OperationFailure(current, authored, index, steps, [new("bodystate-operation-order-invalid",+ $"Operation '{authored.OperationId}' names predecessor {authored.PredecessorStateId.Value}, but the preceding authored operation outputs {constructionState.Operations[index - 1].OutputStateId.Value}.", authored.OperationId)]);+ if (authored.PayloadVersion != authored.Payload.SchemaVersion || authored.PayloadVersion != 1)+ return OperationFailure(current, authored, index, steps, [new("bodystate-operation-version-unsupported",+ $"Operation '{authored.OperationId}' ({authored.OperationKind}) payload version {authored.PayloadVersion} is unsupported.", authored.OperationId)]);+ if (!StringComparer.Ordinal.Equals(authored.OperationId, authored.Payload.StableId)+ || !StringComparer.Ordinal.Equals(authored.OperationKind, authored.Payload.OperationKind))+ return OperationFailure(current, authored, index, steps, [new("bodystate-operation-identity-invalid",+ $"Operation envelope '{authored.OperationId}'/{authored.OperationKind} does not match its typed payload '{authored.Payload.StableId}'/{authored.Payload.OperationKind}.", authored.OperationId)]);++ var nextName = index == constructionState.Operations.Count - 1 && !string.IsNullOrWhiteSpace(outputName)+ ? outputName! : authored.OutputAuthoredName;+ var realized = Apply(current, nextName, authored.Payload);+ if (!realized.IsSuccess || realized.OutputState is null)+ return OperationFailure(current, authored, index, steps, realized.Diagnostics);++ var output = realized.OutputState;+ var replayedOperations = output.ConstructionAuthority!.Operations.ToArray();+ replayedOperations[^1] = replayedOperations[^1] with { ReplayStatus = ConstructionReplayStatus.ReplayedAndValidated };+ current = output with { ConstructionAuthority = output.ConstructionAuthority with { Operations = replayedOperations } };+ steps.Add(new(index, authored.OperationId, authored.OperationKind, authored.PredecessorStateId,+ realized.Delta!.InputState, current.StateId, true, []));+ }++ return new(true, current, current, null, steps, []);+ }++ private static SculptResult Apply(BodyState input, string outputName, IConstructionOperation operation) => operation switch+ {+ OffsetRegionOperation offset => OffsetRegionSculptor.Apply(input, outputName, offset),+ ReplaceRegionOperation replace => ReplaceRegionSculptor.Apply(input, outputName, replace),+ SafeHoleOperation hole => SafeHoleSculptor.Apply(input, outputName, hole),+ BlendBoundaryOperation blend => Blend(BlendBoundarySculptor.Apply(input, outputName, blend)),+ AddSectionChainOperation add => AddSectionChainSculptor.Apply(input, outputName, add),+ RemoveSectionChainOperation remove => RemoveSectionChainSculptor.Apply(input, outputName, remove),+ _ => SculptResult.Failure([new("bodystate-operation-kind-unsupported",+ $"Typed construction operation '{operation.OperationKind}' is not admitted by this runtime.", operation.StableId)])+ };++ private static SculptResult Blend(BlendBoundaryResult result) => result.IsSuccess && result.OutputState is not null+ ? new(true, result.OutputState, result.Delta, result.OutputState.ValidationEvidence, result.Diagnostics)+ : SculptResult.Failure(result.Diagnostics);++ private static ConstructionReplayResult OperationFailure(BodyState current, ConstructionOperationState operation, int index,+ List<ConstructionReplayStep> steps, IReadOnlyList<SculptDiagnostic> cause)+ {+ var diagnostics = new List<SculptDiagnostic>+ {+ new("bodystate-operation-replay-failed",+ $"Replay failed atomically at operation {index} '{operation.OperationId}' ({operation.OperationKind}); predecessor {current.StateId.Value} remains authoritative.", operation.OperationId)+ };+ diagnostics.AddRange(cause);+ steps.Add(new(index, operation.OperationId, operation.OperationKind, operation.PredecessorStateId, current.StateId, null, false, cause));+ return new(false, null, current, operation, steps, diagnostics);+ }++ private static ConstructionReplayResult Failure(BodyState? output, BodyState? predecessor, ConstructionOperationState? operation,+ IReadOnlyList<ConstructionReplayStep> steps, string code, string message)+ => new(false, output, predecessor, operation, steps, [new(code, message)]);+}+diff --git a/Aetheris.Kernel.Firmament/Surfacing/EngineeringBodyStateConstruction.cs b/Aetheris.Kernel.Firmament/Surfacing/EngineeringBodyStateConstruction.csnew file mode 100644index 00000000..3d008578--- /dev/null+++ b/Aetheris.Kernel.Firmament/Surfacing/EngineeringBodyStateConstruction.cs@@ -0,0 +1,101 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++namespace Aetheris.Surfacing;++/// <summary>Adopts an engineering product without reconstructing it as a housing.+/// The existing compiler owns admission and geometry; the AST projection only+/// separates state history from the engineering program it references.</summary>+internal static class EngineeringBodyStateConstruction+{+ internal static bool IsStateDeclaration(StatementSyntax statement) => statement is DeclarationSyntax d+ && d.Type.Name.Text is "BodyState" or "SculptState" or "SurfacePatch" or "SectionChain";++ internal static SculptResult Realize(EngineeringSourceConstruction recipe)+ {+ var selected = FirmamentFrontendSchemas.Select(recipe.Source);+ if (!selected.IsSuccess) return SculptResult.Failure(selected.LocatedDiagnostics.Select(d => new SculptDiagnostic(d.Code, d.Message)));+ var syntax = FirmamentSyntaxParser.Parse(selected.Source, recipe.SourceFile);+ if (!syntax.IsSuccess) return SculptResult.Failure(syntax.Diagnostics.Select(d => new SculptDiagnostic(d.Code, d.Message)));+ var models = syntax.Document.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Model").ToArray();+ if (models.Length != 1 || models[0].Body is not {} body)+ return SculptResult.Failure([new("bodystate-source-invalid", "Engineering construction requires one Model with a body.", recipe.BaseId)]);+ var model = models[0];+ // Keep admitted engineering spelling and source offsets verbatim. Some+ // existing lowerers still consume authored literal/call spelling; this+ // projection is not a reason to reserialize their complete program.+ var characters = selected.Source.ToCharArray();+ foreach (var statement in body.Statements.Where(s => IsStateDeclaration(s)+ || s is FieldSyntax { Name.Text: "output" or "Output" }))+ for (var index = statement.Span.Start; index < statement.Span.Start + statement.Span.Length; index++)+ if (characters[index] is not ('\r' or '\n')) characters[index] = ' ';+ var source = new string(characters);+ var directory = recipe.SourceFile == "memory" ? null : Path.GetDirectoryName(Path.GetFullPath(recipe.SourceFile));+ var built = Aetheris.Kernel.Firmament.FirmamentBuildAndExport.CompileSource(source, directory);+ if (!built.IsSuccess)+ {+ var origins = new FirmamentSyntaxOrigins(syntax.Document, FirmamentSyntaxParser.Parse(source).Document);+ return SculptResult.Failure(built.Diagnostics.Select(d =>+ {+ var presented = FirmamentBuildAdmissionValidation.Present(d, recipe.SourceFile, source);+ var span = presented.SourceSpan is {} location ? origins.Find(location) : null;+ return new SculptDiagnostic(presented.Code, presented.Message, recipe.InputName)+ { SourceFile = recipe.SourceFile, SourceSpan = span is null ? null : new(span.Start, span.Length) };+ }));+ }+ var admitted = built.Value.RuntimeAdmissionDocument;+ var productNames = (admitted?.Composes is { Count: > 0 } compositions+ ? new[] { compositions[^1].Name }+ : admitted?.Solids.Select(s => s.Name) ?? []).ToHashSet(StringComparer.Ordinal);+ if (built.Value.RuntimeBodySourceName is {} nativeProduct) productNames = new(StringComparer.Ordinal) { nativeProduct };+ if (admitted?.ConceptIr?.MaterializedStruct.Name is {} materialized) productNames.Add(materialized);+ var productSyntax = FirmamentSyntaxParser.Parse(source).Document;+ var containingStruct = FirmamentV2Parser.MechanicalDeclarations(productSyntax.Statements).Any(d => d.Name?.Text == recipe.InputName+ && d.Type.Name.Text == "Struct" && !d.Modifiers.Any(m => m.Name.Text == "Concept")+ && FirmamentV2Parser.MechanicalDeclarations(d.Body?.Statements ?? []).Any(child => child.Name is {} n && productNames.Contains(n.Text)));+ if (!productNames.Contains(recipe.InputName) && !containingStruct)+ return SculptResult.Failure([new("bodystate-input-unresolved",+ $"BodyState '{recipe.BaseId}' input '{recipe.InputName}' does not name an admitted engineering body. Reference the Model's body or final Compose.", recipe.BaseId)]);+ var export = built.Value;+ BrepBody realized;+ if (export.RuntimeBody is {} runtime) realized = runtime;+ else+ {+ var imported = Step242Importer.ImportBody(export.StepText);+ if (!imported.IsSuccess) return SculptResult.Failure(imported.Diagnostics.Select(d => new SculptDiagnostic("bodystate-body-realization-failed", d.Message, recipe.BaseId)));+ realized = imported.Value;+ }+ var preflight = BrepExportPreflight.Validate(realized);+ if (!preflight.IsValid) return SculptResult.Failure(preflight.Diagnostics+ .Where(d => d.Severity == BrepExportPreflightSeverity.Error)+ .Select(d => new SculptDiagnostic("bodystate-body-invalid", d.Message, recipe.BaseId)));+ var id = BodyStateId.Derive($"EngineeringSource|{recipe.InputName}|{export.StepText}");+ var bodyId = export.RuntimeCorrespondence?.BodyStableId ?? recipe.InputName;+ var inventory = new Dictionary<string, SculptSemanticEntity>(StringComparer.Ordinal)+ {+ [bodyId] = new(bodyId, SculptEntityKind.Body, id.Value, "Admitted engineering body; no prototype regions inferred.")+ };+ var associations = new List<PersistentGeometryAssociation>();+ foreach (var group in export.RuntimeCorrespondence?.Descendants.GroupBy(d => d.SourceStableId) ?? [])+ {+ var faces = group.Where(d => d.Face is not null).Select(d => d.Face!.Value.Value).Distinct().Order().ToArray();+ inventory.TryAdd(group.Key, new(group.Key, SculptEntityKind.Region,+ string.Join(";", group.Select(d => d.StableId).Order(StringComparer.Ordinal)), "Explicit engineering materialization correspondence."));+ if (faces.Length > 0) associations.Add(new(group.Key, PersistentAssociationState.Preserved, faces, "Retained authoritative materializer correspondence."));+ }+ var evidence = new SculptValidationEvidence[]+ {+ new("EngineeringAdmission", true, LocalityEvidenceLevel.ExactSemantic, 0d, 0d,+ "Normal engineering compiler admitted the source; original STEP, PMI and exact body retained."),+ new("BrepExportPreflight", true, LocalityEvidenceLevel.CertifiedBounded, null, 0d,+ "Existing BRep export preflight passed. No general self-intersection proof is claimed.")+ };+ var authority = new ConstructionState(ConstructionState.CurrentSchemaId, ConstructionState.CurrentSchemaVersion, recipe, []);+ return new(true, new(id, null, bodyId, recipe.BaseId, realized, null, inventory, null, evidence,+ associations, ConstructionAuthority: authority, RealizedStepText: export.StepText)+ { RealizedStepProductName = export.DocumentName ?? model.Name?.Text }, null, evidence, []);+ }+}diff --git a/Aetheris.Kernel.Firmament/Surfacing/SculptingAuthoring.cs b/Aetheris.Kernel.Firmament/Surfacing/SculptingAuthoring.csindex b0ce0c6a..e9430509 100644--- a/Aetheris.Kernel.Firmament/Surfacing/SculptingAuthoring.cs+++ b/Aetheris.Kernel.Firmament/Surfacing/SculptingAuthoring.cs@@ -30,9 +30,18 @@ public static class SculptingAuthoringvar models = binding.Document.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Model").ToArray();if (models.Length != 1) return Fail("<unknown>", "sculpt-source-malformed", "Sculpting source requires exactly one Model.");var model = new Block(models[0], binding.Source, sourceFile, binding.Nominal, binding.OriginalSpan);+ var bodyStates = Blocks(model, "BodyState");+ var engineeringInputs = bodyStates.Any(b => b.Declaration.Body?.Statements.OfType<FieldSyntax>()+ .Any(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Input")) == true);foreach (var statement in binding.Document.Statements.Where(s => !ReferenceEquals(s, models[0])))- if (statement is not DeclarationSyntax data || !binding.OwnsData(data)) diagnostics.Add(new("sculpt-statement-unknown", "Unsupported statement outside the sculpting Model."));- foreach (var data in models[0].Body?.Statements.OfType<DeclarationSyntax>().Where(binding.OwnsData) ?? []) model.Consume(data);+ if (!engineeringInputs && (statement is not DeclarationSyntax data || !binding.OwnsCommonDeclaration(data))) diagnostics.Add(new("sculpt-statement-unknown", "Unsupported statement outside the sculpting Model."));+ foreach (var data in models[0].Body?.Statements.OfType<DeclarationSyntax>().Where(binding.OwnsCommonDeclaration) ?? []) model.Consume(data);+ if (engineeringInputs)+ foreach (var statement in models[0].Body?.Statements ?? [])+ if (!EngineeringBodyStateConstruction.IsStateDeclaration(statement)+ && statement is not FieldSyntax { Name.Text: "units" or "Units" or "output" or "Output" })+ model.Consume(statement); // The normal engineering compiler must admit these statements.+ diagnostics.AddRange(binding.BindCommonRequirements(binding.Document.Statements.Concat(models[0].Body?.Statements ?? [])).Select(Located));if (model.Word("Units") != "mm") diagnostics.Add(new("sculpt-units-invalid", "Sculpting authoring requires units: mm."));foreach (var block in Blocks(model, "SurfacePatch")){@@ -68,9 +77,21 @@ public static class SculptingAuthoringif (!sectionChains.TryAdd(block.Name, chain)) diagnostics.Add(new("section-chain-duplicate", $"SectionChain '{block.Name}' is declared more than once.", block.Name));}var baseClock = Stopwatch.StartNew();- foreach (var block in Blocks(model, "BodyState"))+ foreach (var block in bodyStates){var errorsBefore = diagnostics.Count;+ var engineeringInput = ScalarText(block, "Input");+ if (engineeringInput is not null)+ {+ var realized = EngineeringBodyStateConstruction.Realize(new(block.Name, binding.Source, sourceFile, engineeringInput));+ if (!realized.IsSuccess || realized.OutputState is null) diagnostics.AddRange(realized.Diagnostics.Select(d =>+ {+ var span = d.SourceSpan is {} location ? binding.OriginalSpan(new(location.Start, location.Length)) : null;+ return d with { SourceSpan = span is null ? null : new(span.Start, span.Length) };+ }));+ else if (!states.TryAdd(block.Name, realized.OutputState)) diagnostics.Add(new("sculpt-state-duplicate", $"BodyState '{block.Name}' is declared more than once.", block.Name));+ continue;+ }var size = Vector(block.Body, "Size", 3, diagnostics); var holes = ParseHoles(block.Body, diagnostics);if (size is null || diagnostics.Count != errorsBefore) continue;var created = SculptedHousingFactory.CreateBase(block.Name, size[0], size[1], size[2], holes);@@ -170,11 +191,11 @@ public static class SculptingAuthoringvar useCandidate = ScalarText(blendBlock.Body, "UseCandidate"); var maximumDegree = Integer(blendBlock.Body, "MaximumDegree") ?? 10;operationClock.Stop(); opConstruction += operationClock.Elapsed;if (between.Count != 2) diagnostics.Add(new("surf-blend-supports-invalid", $"BlendBoundary in '{block.Name}' requires exactly two Between supports."));- if (!Enum.TryParse<BlendContinuity>(preferredText, true, out var preferred)) diagnostics.Add(new("surf-blend-continuity-invalid", $"Preferred continuity '{preferredText}' must be G0, G1, or G2."));- if (!Enum.TryParse<BlendContinuity>(minimumText, true, out var minimum)) diagnostics.Add(new("surf-blend-continuity-invalid", $"Minimum continuity '{minimumText}' must be G0, G1, or G2."));+ if (!TryNamedEnum<BlendContinuity>(preferredText, true, out var preferred)) diagnostics.Add(new("surf-blend-continuity-invalid", $"Preferred continuity '{preferredText}' must be G0, G1, or G2."));+ if (!TryNamedEnum<BlendContinuity>(minimumText, true, out var minimum)) diagnostics.Add(new("surf-blend-continuity-invalid", $"Minimum continuity '{minimumText}' must be G0, G1, or G2."));if (!StringComparer.Ordinal.Equals(policyText, "StandardBlendJudgment")) diagnostics.Add(new("surf-blend-policy-unresolved", $"Blend policy '{policyText}' is not defined; use StandardBlendJudgment."));- if (between.Count != 2 || size is null || height is null || blendEnvelope is null || !Enum.TryParse<BlendContinuity>(preferredText, true, out preferred)- || !Enum.TryParse<BlendContinuity>(minimumText, true, out minimum) || !StringComparer.Ordinal.Equals(policyText, "StandardBlendJudgment")) continue;+ if (between.Count != 2 || size is null || height is null || blendEnvelope is null || !TryNamedEnum<BlendContinuity>(preferredText, true, out preferred)+ || !TryNamedEnum<BlendContinuity>(minimumText, true, out minimum) || !StringComparer.Ordinal.Equals(policyText, "StandardBlendJudgment")) continue;var blendOperation = new BlendBoundaryOperation(block.Name + ".BlendBoundary", between[0], between[1], regionName, preferred, minimum,size[0], size[1], height.Value, blendMayModify, new(blendEnvelope[0], blendEnvelope[1], blendEnvelope[2], blendEnvelope[3], blendEnvelope[4], blendEnvelope[5]),blendPreserve.Select(Preservation).ToArray(), blendRequirements, BlendJudgmentPolicy.StandardBlendJudgment, useCandidate, maximumDegree);@@ -201,8 +222,24 @@ public static class SculptingAuthoring}var outputName = ScalarText(model, "Output");BodyState? output = null;- if (outputName is null || !states.TryGetValue(outputName, out output)) diagnostics.Add(new("sculpt-output-unresolved", "Output must name one accepted BodyState or SculptState."));+ if (outputName is null || !states.TryGetValue(outputName, out output))+ {+ var failedDeclaration = models[0].Body?.Statements.OfType<DeclarationSyntax>()+ .Any(d => d.Type.Name.Text is "BodyState" or "SculptState" && d.Name?.Text == outputName) == true;+ if (outputName is null || !failedDeclaration || diagnostics.Count == 0)+ diagnostics.Add(new("sculpt-output-unresolved", "Output must name one accepted BodyState or SculptState."));+ }diagnostics.AddRange(model.CompleteTree().Select(Located));+ for (var i = 0; i < diagnostics.Count; i++)+ {+ if (diagnostics[i].SourceSpan is not null) continue;+ var enclosing = models[0].Body?.Statements.OfType<DeclarationSyntax>()+ .FirstOrDefault(d => d.Name?.Text == diagnostics[i].Entity) ?? models[0];+ var span = binding.OriginalSpan(enclosing.Span);+ diagnostics[i] = diagnostics[i] with { SourceFile = sourceFile,+ SourceSpan = span is null ? null : new(span.Start, span.Length)+ { LocationNote = "Location identifies the enclosing declaration; the domain operation supplied no finer original-source span." } };+ }total.Stop();return new(diagnostics.Count == 0 && output is not null, model.Name, output, states, diagnostics,new(baseClock.Elapsed.TotalMilliseconds, opConstruction.TotalMilliseconds, verification.TotalMilliseconds, brep.TotalMilliseconds, 0d));@@ -218,7 +255,6 @@ public static class SculptingAuthoringvar center = Vector(hole.Body, "Center", 2, diagnostics); var diameter = Length(hole.Body, "Diameter", diagnostics);if (center is not null && diameter is not null) result.Add(new(hole.Name, center[0], center[1], diameter.Value));}- if (result.Count == 0) diagnostics.Add(new("sculpt-hole-pattern-required", "The X0 housing witness requires at least one bounded mounting hole."));return result;}@@ -238,19 +274,27 @@ public static class SculptingAuthoring}if (stations.Count < 2) { diagnostics.Add(new("section-chain-section-count-invalid", $"SectionChain '{block.Name}' requires at least two Station blocks.", block.Name)); return null; }var startText = ScalarText(block.Body, "StartTermination") ?? "Open"; var endText = ScalarText(block.Body, "EndTermination") ?? "Open";- if (!Enum.TryParse<SectionTermination>(startText, true, out var start) || !Enum.TryParse<SectionTermination>(endText, true, out var end))+ if (!TryNamedEnum<SectionTermination>(startText, true, out var start) || !TryNamedEnum<SectionTermination>(endText, true, out var end)){ diagnostics.Add(new("section-chain-termination-invalid", $"SectionChain '{block.Name}' terminations must be Open or Cap.", block.Name)); return null; }var correspondence = stations.Zip(stations.Skip(1), (source, target) => new AdjacentSectionCorrespondence(source.SectionId, target.SectionId,spanIds.Select(span => new SectionSpanCorrespondence(span, span)).ToArray())).ToArray();// The compact X3b sculpt-operation grammar predates SURF-X4; absence remains G0 for replay compatibility.var continuityText = ScalarText(block.Body, "Continuity") ?? "G0";- if (!Enum.TryParse<SectionChainContinuity>(continuityText, true, out var continuity))+ if (!TryNamedEnum<SectionChainContinuity>(continuityText, true, out var continuity)){ diagnostics.Add(new("section-chain-continuity-invalid", $"SectionChain '{block.Name}' Continuity must be G0 or G1.", block.Name)); return null; }return new(block.Name, stations, correspondence,continuity == SectionChainContinuity.G1 ? SectionTransitionPolicy.SmoothPolynomial : SectionTransitionPolicy.Ruled,start, end, continuity);}+ private static bool TryNamedEnum<T>(string value, bool ignoreCase, out T result) where T : struct, Enum+ {+ result = default;+ return Enum.GetNames<T>().Any(name => string.Equals(name, value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))+ && Enum.TryParse(value, ignoreCase, out result);+ }+ private static bool TryNamedEnum<T>(string value, out T result) where T : struct, Enum => TryNamedEnum(value, false, out result);+private static IReadOnlyList<Block> Blocks(Block scope, string kind) => scope.Children(kind);private static Block? Single(Block scope, string kind, List<SculptDiagnostic> diagnostics){@@ -289,7 +333,7 @@ public static class SculptingAuthoring{var parsed = new List<SculptRequirement>();foreach (var value in values)- if (Enum.TryParse<SculptRequirement>(value, out var requirement)) parsed.Add(requirement); else diagnostics.Add(new("sculpt-requirement-unsupported", $"Requirement '{value}' is not supported."));+ if (TryNamedEnum<SculptRequirement>(value, out var requirement)) parsed.Add(requirement); else diagnostics.Add(new("sculpt-requirement-unsupported", $"Requirement '{value}' is not supported."));return parsed;}private static double[]? NumberVector(Block body, string field, int count, List<SculptDiagnostic> diagnostics)@@ -323,9 +367,9 @@ public static class SculptingAuthoringvar result = new List<PatchBoundaryCorrespondence>();foreach (var block in Blocks(body, "Boundary")){- if (!Enum.TryParse<PatchBoundarySide>(block.Name, true, out var side)) { diagnostics.Add(new("surf-boundary-side-invalid", $"Unknown patch boundary side '{block.Name}'.")); continue; }+ if (!TryNamedEnum<PatchBoundarySide>(block.Name, true, out var side)) { diagnostics.Add(new("surf-boundary-side-invalid", $"Unknown patch boundary side '{block.Name}'.")); continue; }var existing = ScalarText(block.Body, "Existing") ?? string.Empty; var continuityText = ScalarText(block.Body, "Continuity") ?? "G0";- if (!Enum.TryParse<PatchBoundaryContinuity>(continuityText, true, out var continuity) || continuity == PatchBoundaryContinuity.G2)+ if (!TryNamedEnum<PatchBoundaryContinuity>(continuityText, true, out var continuity) || continuity == PatchBoundaryContinuity.G2){diagnostics.Add(new("surf-boundary-continuity-invalid", $"Direct SurfacePatch boundary '{block.Name}' continuity must be G0 or G1; use BlendBoundary for qualified G2 construction and evidence."));continue;diff --git a/Aetheris.Modules.Tests/BodyStateDebtTests.cs b/Aetheris.Modules.Tests/BodyStateDebtTests.csnew file mode 100644index 00000000..0621bf28--- /dev/null+++ b/Aetheris.Modules.Tests/BodyStateDebtTests.cs@@ -0,0 +1,252 @@+using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Firmament;+using Aetheris.Surfacing;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Step242;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;+using Xunit;++namespace Aetheris.Modules.Tests;++public sealed class BodyStateDebtTests+{+ [Theory]+ [InlineData("Primitives/cone", "Body")]+ [InlineData("Primitives/sphere", "Body")]+ [InlineData("Primitives/torus", "Body")]+ [InlineData("Primitives/rounded-box", "Base")]+ [InlineData("Gears/spur-basic", "DriveGear")]+ [InlineData("Features/Sweep/circular-arc-sweep", "Wire")]+ [InlineData("Revolve/stepped-shaft", "Shaft")]+ [InlineData("Revolve/arbitrary-axis", "TiltedRing")]+ public void EngineeringAdoptionUsesTheExistingCompilerAcrossMaterialFamilies(string relative, string bodyName)+ {+ var path = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Fixture("box"))!, "../../Canonical", relative + ".firmament"));+ var source = File.ReadAllText(path);+ var reference = FirmamentBuildAndExport.CompileSource(source, Path.GetDirectoryName(path));+ Assert.True(reference.IsSuccess, string.Join(";", reference.Diagnostics.Select(d => d.Message)));+ // The wrapper is a Sculpting product. Keep the reference's explicit+ // Mechanical selector for the reference build, not for its new owner.+ var adoptionSource = FirmamentFrontendSchemas.Select(source).Source;+ var model = Assert.Single(FirmamentSyntaxParser.Parse(adoptionSource).Document.Statements.OfType<DeclarationSyntax>(), d => d.Type.Name.Text == "Model");+ var at = model.Body!.ContentSpan.Start + model.Body.ContentSpan.Length;+ var stateSource = "schema Sculpting\n" + adoptionSource.Insert(at, "\nBodyState Snapshot { input: " + bodyName + " }\noutput: Snapshot\n");+ var result = SculptingAuthoring.Compile(stateSource, path);+ Assert.True(result.IsSuccess, string.Join(";", result.Diagnostics.Select(d => d.Message)));+ Assert.Equal(reference.Value.StepText, SculptStepExporter.Export(result.OutputState!, result.ModelName).Step);+ var saved = ConstructionStateSerializer.Serialize(result.OutputState!.ConstructionAuthority!);+ var loaded = ConstructionStateSerializer.Deserialize(saved.Json!);+ Assert.True(loaded.IsSuccess, string.Join(";", loaded.Diagnostics.Select(d => d.Message)));+ var replay = ConstructionStateReplayer.Replay(loaded.ConstructionState!);+ Assert.True(replay.IsSuccess, string.Join(";", replay.Diagnostics.Select(d => d.Message)));+ Assert.Equal(reference.Value.StepText, SculptStepExporter.Export(replay.OutputState!, result.ModelName).Step);+ }++ [Theory]+ [InlineData("box")]+ [InlineData("cylinder")]+ [InlineData("counterbore-chamfer")]+ [InlineData("profile")]+ [InlineData("explicit-pmi")]+ public void EngineeringBodiesRetainExactProductAndReplay(string name)+ {+ var path = Fixture(name);+ var reference = FirmamentBuildAndExport.CompileSource(File.ReadAllText(Fixture(name + ".reference")));+ Assert.True(reference.IsSuccess, string.Join(";", reference.Diagnostics.Select(d => d.Message)));+ var result = SculptingAuthoring.CompileFile(path);+ Assert.True(result.IsSuccess, string.Join(";", result.Diagnostics.Select(d => d.Message)));+ var state = result.OutputState!;+ Assert.Null(state.Construction);+ Assert.DoesNotContain(SculptedHousingFactory.CrownRegion, state.SemanticInventory.Keys);+ Assert.Equal(reference.Value.StepText, SculptStepExporter.Export(state, result.ModelName).Step);+ var renamedExport = SculptStepExporter.Export(state, result.ModelName + "_renamed");+ Assert.False(renamedExport.IsSuccess);+ Assert.Null(renamedExport.Step);+ Assert.Contains(renamedExport.Diagnostics, d => d.Code == "bodystate-product-name-mismatch");+ var serialized = ConstructionStateSerializer.Serialize(state.ConstructionAuthority!);+ Assert.True(serialized.IsSuccess);+ var deserialized = ConstructionStateSerializer.Deserialize(serialized.Json!);+ Assert.True(deserialized.IsSuccess);+ var replay = ConstructionStateReplayer.Replay(deserialized.ConstructionState!, "Replayed");+ Assert.True(replay.IsSuccess, string.Join(";", replay.Diagnostics.Select(d => d.Message)));+ Assert.Equal("Replayed", replay.OutputState!.AuthoredName);+ Assert.Equal(state.StateId, replay.OutputState.StateId);+ Assert.Equal(state.BodyStableId, replay.OutputState.BodyStableId);+ Assert.Equal(reference.Value.StepText, SculptStepExporter.Export(replay.OutputState, result.ModelName).Step);+ Assert.Equal(BrepMassProperties.Evaluate(state.Body).AbsoluteVolume, BrepMassProperties.Evaluate(replay.OutputState.Body).AbsoluteVolume);+ }++ [Fact]+ public void PlainHousingCanBeEditedWithoutInventedHolesOrHolePmi()+ {+ var result = SculptingAuthoring.CompileFile(Fixture("plain-offset"));+ Assert.True(result.IsSuccess, string.Join(";", result.Diagnostics.Select(d => d.Message)));+ var state = result.OutputState!;+ Assert.Empty(state.Construction!.Holes);+ Assert.DoesNotContain(SculptedHousingFactory.MountingHolePattern, state.SemanticInventory.Keys);+ Assert.DoesNotContain(state.SemanticPmi!, p => p is Aetheris.Kernel.Core.Step242.Step242SemanticPmiHole);+ Assert.True(BrepMassProperties.Evaluate(state.Body).AbsoluteVolume > 6000);+ var replay = ConstructionStateReplayer.Replay(state.ConstructionAuthority!);+ Assert.True(replay.IsSuccess, string.Join(";", replay.Diagnostics.Select(d => d.Message)));+ Assert.Equal(state.StateId, replay.OutputState!.StateId);+ Assert.Equal(SculptStepExporter.Export(state, result.ModelName).Step, SculptStepExporter.Export(replay.OutputState, result.ModelName).Step);+ }++ [Fact]+ public void UnsupportedHousingEditCannotReplaceAnEngineeringCylinder()+ {+ var result = SculptingAuthoring.CompileFile(Fixture("cylinder"));+ Assert.True(result.IsSuccess, string.Join(";", result.Diagnostics.Select(d => d.Message)));+ var input = result.OutputState!;+ var operation = new OffsetRegionOperation("Raise", "HousingCrown", 3, 4, 4, ["HousingCrown"], new(-10,-10,0,10,10,30), [], []);+ var failed = OffsetRegionSculptor.Apply(input, "Bad", operation);+ Assert.False(failed.IsSuccess);+ Assert.Null(failed.OutputState);+ Assert.Contains(failed.Diagnostics, d => d.Code == "bodystate-operation-capability-unsupported");+ var authority = input.ConstructionAuthority!.Append(new("Raise", operation.OperationKind, 1, input.StateId,+ BodyStateId.Derive("bad"), "Bad", operation, [], [], operation.InfluenceEnvelope, [],+ new(input.StateId, BodyStateId.Derive("bad"), [], [], [], [], [], [], operation.InfluenceEnvelope, []), []));+ var replay = ConstructionStateReplayer.Replay(authority);+ Assert.False(replay.IsSuccess);+ Assert.Equal(input.StateId, replay.AuthoritativePredecessor!.StateId);+ Assert.Null(replay.OutputState);+ Assert.Equal(input.RealizedStepText, replay.AuthoritativePredecessor.RealizedStepText);+ }++ [Fact]+ public void RepeatedHolesRetainAttachedGeometryAndAllPriorFeatures()+ {+ var result = SculptingAuthoring.CompileFile(Fixture("second-hole-after-add"));+ Assert.True(result.IsSuccess, string.Join(";", result.Diagnostics.Select(d => d.Message)));+ var state = result.OutputState!;+ Assert.Equal(4, state.Construction!.Holes.Count);+ Assert.Contains("GripChain.AttachedSurface", state.SemanticInventory.Keys);+ Assert.Contains("ServicePort", state.SemanticInventory.Keys);+ Assert.Contains("SecondPort", state.SemanticInventory.Keys);+ Assert.Equal(3, state.ConstructionAuthority!.Operations.Count);+ var replay = ConstructionStateReplayer.Replay(state.ConstructionAuthority);+ Assert.True(replay.IsSuccess, string.Join(";", replay.Diagnostics.Select(d => d.Message)));+ Assert.Equal(state.StateId, replay.OutputState!.StateId);+ Assert.Equal(SculptStepExporter.Export(state, result.ModelName).Step, SculptStepExporter.Export(replay.OutputState, result.ModelName).Step);+ var previous = result.States["PortAdded"];+ var beforeMass = BrepMassProperties.Evaluate(previous.Body);+ var afterMass = BrepMassProperties.Evaluate(state.Body);+ // The generic trimmed-face mass evaluator is a tessellated sanity estimate.+ // Qualify exact geometry against the independently ordered construction instead.+ var reference = SculptingAuthoring.CompileFile(Fixture("second-hole-after-add.reference"));+ Assert.True(reference.IsSuccess, string.Join(";", reference.Diagnostics.Select(d => d.Message)));+ Assert.Equal(SculptStepExporter.Export(reference.OutputState!, result.ModelName).Step, SculptStepExporter.Export(state, result.ModelName).Step);+ Assert.Equal(4, state.Body.Geometry.Surfaces.Count(s => s.Value.Cylinder is not null));+ var holes = state.SemanticPmi!.OfType<Aetheris.Kernel.Core.Step242.Step242SemanticPmiHole>().OrderBy(p => p.Diameter).ToArray();+ Assert.Equal(new[] { 3d, 4d }, holes.Select(p => p.Diameter));+ Assert.All(holes, p => { Assert.Equal(2, p.Quantity); Assert.Equal(2, p.GeometricFaceIds.Count); });+ Assert.True(beforeMass.IsEnclosed && afterMass.IsEnclosed);+ Assert.True(afterMass.AbsoluteVolume > 80 * 40 * 20);+ }++ [Theory]+ [InlineData("unsupported-cylinder-edit", "bodystate-operation-capability-unsupported")]+ [InlineData("history-drop", "bodystate-history-capability-unsupported")]+ public void UnsupportedHistoryFailsBeforePublishingAnOutput(string name, string code)+ {+ var result = SculptingAuthoring.CompileFile(Fixture(name));+ Assert.False(result.IsSuccess);+ Assert.Null(result.OutputState);+ Assert.DoesNotContain("Bad", result.States.Keys);+ Assert.Contains(result.Diagnostics, d => d.Code == code && d.SourceSpan is not null);+ }++ [Theory]+ [InlineData("input: Stock", "input: Missing", "bodystate-input-unresolved")]+ [InlineData("BodyState Base { input: Stock }", "Struct Empty {} BodyState Base { input: Empty }", "bodystate-input-unresolved")]+ [InlineData("size: [30mm, 20mm, 10mm]", "size: [30mm, 20mm, 10mm] heigth: 2mm", "firmament-v2-canonical-field-unknown")]+ [InlineData("input: Stock", "input: Stock size: [1mm, 1mm, 1mm]", "firmament-v2-canonical-field-unknown")]+ public void InvalidIntentRejectsWithOriginalLocation(string before, string after, string code)+ {+ var path = Fixture("box");+ var result = SculptingAuthoring.Compile(File.ReadAllText(path).Replace(before, after), path);+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, d => d.Code.StartsWith(code, StringComparison.Ordinal) || d.Message.Contains(code, StringComparison.Ordinal));+ Assert.All(result.Diagnostics, d => { Assert.Equal(path, d.SourceFile); Assert.NotNull(d.SourceSpan); });+ }++ [Fact]+ public void DuplicateOrBlankHoleIdentitiesCannotCollapseSemanticInventory()+ {+ foreach (var holes in new HousingHole[][]+ {+ [new("same", -5, 0, 2), new("same", 5, 0, 2)],+ [new("", 0, 0, 2)]+ })+ {+ var result = SculptedHousingFactory.CreateBase("Base", 30, 20, 10, holes);+ Assert.False(result.IsSuccess);+ Assert.Null(result.OutputState);+ Assert.Contains(result.Diagnostics, d => d.Code is "sculpt-hole-duplicate" or "sculpt-hole-identity-required");+ }+ }++ [Fact]+ public void ReplacementControlNetIsPartOfStateIdentityAndDurableReplay()+ {+ var path = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Fixture("box"))!, "../../Canonical/Sculpting/surf-x1-freeform-housing.firmament"));+ var compiled = SculptingAuthoring.CompileFile(path);+ Assert.True(compiled.IsSuccess, string.Join(";", compiled.Diagnostics.Select(d => d.Message)));+ var original = compiled.States["FreeformCrown"];+ var payload = Assert.IsType<ReplaceRegionOperation>(Assert.Single(original.ConstructionAuthority!.Operations).Payload);+ var patch = Assert.IsType<BSplineSurfacePatch>(payload.ReplacementPatch);+ Assert.NotEqual(patch.GeometryFingerprint, new BSplineSurfacePatch(patch.PatchId, patch.Spline,+ new(.1, .9, .1, .9), patch.BoundaryLoop).GeometryFingerprint);+ Assert.NotEqual(patch.GeometryFingerprint, new BSplineSurfacePatch(patch.PatchId, patch.Spline,+ patch.ParameterDomain, patch.BoundaryLoop, reversedOrientation: true).GeometryFingerprint);+ var points = patch.Spline.ControlPoints.Select(row => row.ToArray()).ToArray();+ points[2][2] = points[2][2] + new Vector3D(0, 0, 1);+ var spline = new BSplineSurfaceWithKnots(patch.Spline.DegreeU, patch.Spline.DegreeV, points, patch.Spline.SurfaceForm,+ patch.Spline.UClosed, patch.Spline.VClosed, patch.Spline.SelfIntersect, patch.Spline.KnotMultiplicitiesU,+ patch.Spline.KnotMultiplicitiesV, patch.Spline.KnotValuesU, patch.Spline.KnotValuesV, patch.Spline.KnotSpec);+ var changedPatch = new BSplineSurfacePatch(patch.PatchId, spline, patch.ParameterDomain, patch.BoundaryLoop);+ var changed = ReplaceRegionSculptor.Apply(compiled.States["Base"], "Changed", payload with { ReplacementPatch = changedPatch });+ Assert.True(changed.IsSuccess, string.Join(";", changed.Diagnostics.Select(d => d.Message)));+ Assert.NotEqual(original.StateId, changed.OutputState!.StateId);+ Assert.NotEqual(original.SemanticInventory[patch.PatchId].GeometryFingerprint, changed.OutputState.SemanticInventory[patch.PatchId].GeometryFingerprint);+ Assert.NotEqual(SculptStepExporter.Export(original, "Shape").Step, SculptStepExporter.Export(changed.OutputState, "Shape").Step);+ var saved = ConstructionStateSerializer.Serialize(changed.OutputState.ConstructionAuthority!);+ Assert.True(saved.IsSuccess, string.Join(";", saved.Diagnostics.Select(d => d.Message)));+ var loaded = ConstructionStateSerializer.Deserialize(saved.Json!);+ Assert.True(loaded.IsSuccess, string.Join(";", loaded.Diagnostics.Select(d => d.Message)));+ var replay = ConstructionStateReplayer.Replay(loaded.ConstructionState!);+ Assert.True(replay.IsSuccess, string.Join(";", replay.Diagnostics.Select(d => d.Message)));+ Assert.Equal(changed.OutputState.StateId, replay.OutputState!.StateId);+ Assert.Equal(SculptStepExporter.Export(changed.OutputState, "Shape").Step, SculptStepExporter.Export(replay.OutputState, "Shape").Step);++ var imported = Step242Importer.ImportBody(SculptStepExporter.Export(original, "Shape").Step!);+ Assert.True(imported.IsSuccess);+ var adopted = ImportedFaceRegionReplacer.AdoptImportedBody(original, imported.Value, "Imported");+ Assert.Null(adopted.ConstructionAuthority);+ var refusal = OffsetRegionSculptor.Apply(adopted, "Bad", new("Bad", "HousingCrown", 1, 10, 10, [], new(-50,-40,20,50,40,30), [], []));+ Assert.False(refusal.IsSuccess);+ Assert.Contains(refusal.Diagnostics, d => d.Code == "bodystate-imported-reconstruction-unsupported");+ }++ [Fact]+ public void SectionFramesAndSplineKnotsParticipateInConstructionIdentity()+ {+ var chain = SectionChainTemplates.TwoProfileRuled();+ var first = chain.Sections[0];+ var rotated = first with { Frame = SectionFrame.Create(first.Frame.Origin, new(0, 1, 0), new(-1, 0, 0)) };+ Assert.NotEqual(SectionChainCanonical.Fingerprint(chain), SectionChainCanonical.Fingerprint(chain with { Sections = [rotated, .. chain.Sections.Skip(1)] }));+ var span = first.Profile.Spans[0];+ var curve = new SectionProfileCurve.PolynomialBSpline(1, [new(0,0), new(1,0), new(2,0)], [2,1,2], [0,.5,1]);+ var a = chain with { Sections = [first with { Profile = first.Profile with { Spans = [span with { Curve = curve }] } }, .. chain.Sections.Skip(1)] };+ var b = a with { Sections = [a.Sections[0] with { Profile = a.Sections[0].Profile with { Spans = [span with { Curve = curve with { KnotValues = [0,.25,1] } }] } }, .. a.Sections.Skip(1)] };+ Assert.NotEqual(SectionChainCanonical.Fingerprint(a), SectionChainCanonical.Fingerprint(b));+ }++ private static string Fixture(string name)+ {+ var root = new DirectoryInfo(AppContext.BaseDirectory);+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx"))) root = root.Parent;+ return Path.Combine(root!.FullName, "fixtures/Regression/BodyStateDebt", name + ".firmament");+ }+}diff --git a/Aetheris.Modules.Tests/SurfX0SculptingTests.cs b/Aetheris.Modules.Tests/SurfX0SculptingTests.csindex b023192a..34beafe9 100644--- a/Aetheris.Modules.Tests/SurfX0SculptingTests.cs+++ b/Aetheris.Modules.Tests/SurfX0SculptingTests.cs@@ -34,7 +34,7 @@ public sealed class SurfX0SculptingTestsAssert.True(result.IsSuccess, string.Join(';', result.Diagnostics.Select(x => x.Code)));var state = Assert.IsType<BodyState>(result.OutputState);Assert.NotNull(state.PredecessorStateId); Assert.Equal(result.States["Base"].StateId, state.PredecessorStateId);- Assert.NotSame(result.States["Base"].Body, state.Body); Assert.Equal(20d, result.States["Base"].Construction.FinalHeight); Assert.Equal(26d, state.Construction.FinalHeight);+ Assert.NotSame(result.States["Base"].Body, state.Body); Assert.Equal(20d, result.States["Base"].Construction!.FinalHeight); Assert.Equal(26d, state.Construction!.FinalHeight);Assert.Contains(SculptedHousingFactory.BottomMountingInterface, state.Delta!.Preserves);Assert.Contains(SculptedHousingFactory.CrownRegion, state.Delta.Replaces);Assert.Contains(SculptedHousingFactory.TransitionZone, state.Delta.Introduces);@@ -47,7 +47,7 @@ public sealed class SurfX0SculptingTestsAssert.True(first.IsSuccess); Assert.Equal(first.OutputState!.StateId, second.OutputState!.StateId);var baseState = first.States["Base"]; var six = first.States["CrownRaised"]; var ten = first.States["CrownHigh"];Assert.Equal(baseState.StateId, six.PredecessorStateId); Assert.Equal(baseState.StateId, ten.PredecessorStateId);- Assert.NotEqual(six.StateId, ten.StateId); Assert.Equal(20d, baseState.Construction.FinalHeight); Assert.Equal(26d, six.Construction.FinalHeight); Assert.Equal(30d, ten.Construction.FinalHeight);+ Assert.NotEqual(six.StateId, ten.StateId); Assert.Equal(20d, baseState.Construction!.FinalHeight); Assert.Equal(26d, six.Construction!.FinalHeight); Assert.Equal(30d, ten.Construction!.FinalHeight);}[Fact]@@ -68,7 +68,7 @@ public sealed class SurfX0SculptingTestspublic void FailedSculptIsAtomicAndTyped(string fixture, string diagnostic){var result = Compile(fixture); Assert.False(result.IsSuccess); Assert.Contains(result.Diagnostics, x => x.Code == diagnostic);- Assert.True(result.States.TryGetValue("Base", out var baseState)); Assert.Equal(20d, baseState.Construction.FinalHeight);+ Assert.True(result.States.TryGetValue("Base", out var baseState)); Assert.Equal(20d, baseState.Construction!.FinalHeight);Assert.DoesNotContain(result.States.Values, x => x.AuthoredName == "CrownRaised");}diff --git a/Aetheris.Modules.Tests/SurfX1PatchSurfacingTests.cs b/Aetheris.Modules.Tests/SurfX1PatchSurfacingTests.csindex 713e76ef..b4c56474 100644--- a/Aetheris.Modules.Tests/SurfX1PatchSurfacingTests.cs+++ b/Aetheris.Modules.Tests/SurfX1PatchSurfacingTests.cs@@ -41,7 +41,7 @@ public sealed class SurfX1PatchSurfacingTests[Fact]public void TrimAndExtendRemainBoundedByExistingNonRationalSupport(){- var patch = Assert.IsType<BSplineSurfacePatch>(CompileFlagship().OutputState!.Construction.ReplacementPatch);+ var patch = Assert.IsType<BSplineSurfacePatch>(CompileFlagship().OutputState!.Construction!.ReplacementPatch);var trimmed = SurfacePatchOperations.TrimRegion(patch, new(.1, .9, .2, .8));Assert.True(trimmed.IsSuccess); Assert.Equal(new SurfaceParameterDomain(.1, .9, .2, .8), trimmed.Patch!.ParameterDomain);var extended = SurfacePatchOperations.ExtendRegion((BSplineSurfacePatch)trimmed.Patch, new(0, 1, 0, 1));@@ -77,7 +77,7 @@ public sealed class SurfX1PatchSurfacingTests[Fact]public void ReplacedHistoricalSelectorProducesActionableDiagnostic(){- var first = CompileFlagship(); var input = first.OutputState!; var patch = input.Construction.ReplacementPatch!;+ var first = CompileFlagship(); var input = first.OutputState!; var patch = input.Construction!.ReplacementPatch!;var operation = new ReplaceRegionOperation("stale.ReplaceRegion", SculptedHousingFactory.CrownRegion, patch,[SculptedHousingFactory.CrownRegion], new(-30, -20, 20, 30, 20, 28), [], []);var result = ReplaceRegionSculptor.Apply(input, "Stale", operation);@@ -107,7 +107,7 @@ public sealed class SurfX1PatchSurfacingTestspublic void LowAndHighCrownsBranchIndependentlyFromSamePredecessor(){var compile = CompileFlagship(); var predecessor = compile.States["Base"]; var low = compile.States["FreeformCrown"];- var source = (BSplineSurfacePatch)low.Construction.ReplacementPatch!; var s = source.Spline;+ var source = (BSplineSurfacePatch)low.Construction!.ReplacementPatch!; var s = source.Spline;var controls = s.ControlPoints.Select(row => (IReadOnlyList<Aetheris.Kernel.Core.Math.Point3D>)row.Select(p => new Aetheris.Kernel.Core.Math.Point3D(p.X, p.Y, 20d + (p.Z - 20d) * 1.4d)).ToArray()).ToArray();var highSpline = new BSplineSurfaceWithKnots(s.DegreeU, s.DegreeV, controls, s.SurfaceForm, s.UClosed, s.VClosed, s.SelfIntersect, s.KnotMultiplicitiesU, s.KnotMultiplicitiesV, s.KnotValuesU, s.KnotValuesV, s.KnotSpec);var highPatch = new BSplineSurfacePatch("HighCrownPatch", highSpline, source.ParameterDomain, source.BoundaryLoop);@@ -118,8 +118,8 @@ public sealed class SurfX1PatchSurfacingTestsvar high = ReplaceRegionSculptor.Apply(predecessor, "HighCrown", operation);Assert.True(high.IsSuccess, string.Join(';', high.Diagnostics.Select(x => x.Message)));Assert.Equal(predecessor.StateId, low.PredecessorStateId); Assert.Equal(predecessor.StateId, high.OutputState!.PredecessorStateId);- Assert.NotEqual(low.StateId, high.OutputState.StateId); Assert.Equal(20d, predecessor.Construction.FinalHeight);- Assert.True(high.OutputState.Construction.FinalHeight > low.Construction.FinalHeight);+ Assert.NotEqual(low.StateId, high.OutputState.StateId); Assert.Equal(20d, predecessor.Construction!.FinalHeight);+ Assert.True(high.OutputState.Construction!.FinalHeight > low.Construction!.FinalHeight);}private static SculptingCompileResult CompileFlagship() => SculptingAuthoring.CompileFile(FlagshipPath());diff --git a/Aetheris.Modules.Tests/SurfX1aTrimIntersectionClosureTests.cs b/Aetheris.Modules.Tests/SurfX1aTrimIntersectionClosureTests.csindex 0652ac52..22c5461b 100644--- a/Aetheris.Modules.Tests/SurfX1aTrimIntersectionClosureTests.cs+++ b/Aetheris.Modules.Tests/SurfX1aTrimIntersectionClosureTests.cs@@ -42,7 +42,7 @@ public sealed class SurfX1aTrimIntersectionClosureTestsvar coincident = BoundedSurfaceIntersector.Intersect(new("z0a", z0, domain, "z0b", z0, domain));Assert.Equal(SurfaceIntersectionClassification.CoincidentRegion, coincident.Classification);- var patch = Assert.IsType<BSplineSurfacePatch>(CompileFlagship().OutputState!.Construction.ReplacementPatch);+ var patch = Assert.IsType<BSplineSurfacePatch>(CompileFlagship().OutputState!.Construction!.ReplacementPatch);var supportPlane = SurfaceGeometry.FromPlane(new PlaneSurface(new(0, -40, 20), Dir(0, -1, 0), Dir(1, 0, 0)));var first = BoundedSurfaceIntersector.Intersect(new("south", supportPlane, domain, patch.PatchId, patch.Support, patch.ParameterDomain, SeedOnA: new(0, 0)));var second = BoundedSurfaceIntersector.Intersect(new("south", supportPlane, domain, patch.PatchId, patch.Support, patch.ParameterDomain, SeedOnA: new(0, 0)));@@ -65,7 +65,7 @@ public sealed class SurfX1aTrimIntersectionClosureTestsAssert.True(analytic.IsSuccess); Assert.Equal(SurfaceExtensionMethod.AnalyticIdentity, analytic.Support!.Method);Assert.Equal(new Point3D(-.1, -.1, 0), analytic.Support.Evaluate(-.1, -.1));- var patch = Assert.IsType<BSplineSurfacePatch>(CompileFlagship().OutputState!.Construction.ReplacementPatch);+ var patch = Assert.IsType<BSplineSurfacePatch>(CompileFlagship().OutputState!.Construction!.ReplacementPatch);var extended = SurfaceSupportExtension.Extend(patch.Support, patch.ParameterDomain, new(-.1, 1.1, -.1, 1.1));Assert.True(extended.IsSuccess); Assert.Equal(SurfaceExtensionMethod.EndpointTangentContinuation, extended.Support!.Method);Assert.Contains("C1", extended.Support.ContinuityAtOriginalBoundary, StringComparison.Ordinal);@@ -117,7 +117,7 @@ public sealed class SurfX1aTrimIntersectionClosureTestsimported.Value.Geometry.GetSurface(binding.SurfaceGeometryId).Plane is { } plane && Math.Abs(plane.Origin.Z - 20d) < 1e-8d && plane.Normal.ToVector().Z > 0d);Assert.True(topBinding.SourceStepEntityId.HasValue);var adopted = ImportedFaceRegionReplacer.AdoptImportedBody(nativeBase, imported.Value, "ImportedBaseStep");- var patch = Assert.IsType<BSplineSurfacePatch>(compile.OutputState!.Construction.ReplacementPatch);+ var patch = Assert.IsType<BSplineSurfacePatch>(compile.OutputState!.Construction!.ReplacementPatch);var replaced = ImportedFaceRegionReplacer.Apply(adopted, topBinding.SourceStepEntityId!.Value, patch, "ImportedTrimmedCrown");Assert.True(replaced.IsSuccess, string.Join(" | ", replaced.Diagnostics.Select(item => item.Message)));Assert.Same(imported.Value.Topology, replaced.OutputState!.Body.Topology);diff --git a/Aetheris.PlasticShell/PlasticShellFirmament.cs b/Aetheris.PlasticShell/PlasticShellFirmament.csindex c23ba6a2..cccc677e 100644--- a/Aetheris.PlasticShell/PlasticShellFirmament.cs+++ b/Aetheris.PlasticShell/PlasticShellFirmament.cs@@ -23,8 +23,9 @@ public static class PlasticShellFirmamentif(models.Length!=1)return Fail("<unknown>","PlasticShell requires exactly one Model.");var model=new Block(models[0],binding.Source,sourcePath,binding.Nominal,binding.OriginalSpan);var modelName=model.Name;foreach(var statement in binding.Document.Statements.Where(s=>!ReferenceEquals(s,models[0])))- if(statement is not DeclarationSyntax data || !binding.OwnsData(data))diagnostics.Add(new(PlasticDiagnosticCodes.SourceInvalid,PlasticDiagnosticSeverity.Error,"Unsupported statement outside PlasticShell Model."));- foreach(var data in models[0].Body?.Statements.OfType<DeclarationSyntax>().Where(binding.OwnsData)??[])model.Consume(data);+ if(statement is not DeclarationSyntax data || !binding.OwnsCommonDeclaration(data))diagnostics.Add(new(PlasticDiagnosticCodes.SourceInvalid,PlasticDiagnosticSeverity.Error,"Unsupported statement outside PlasticShell Model."));+ foreach(var data in models[0].Body?.Statements.OfType<DeclarationSyntax>().Where(binding.OwnsCommonDeclaration)??[])model.Consume(data);+ diagnostics.AddRange(binding.BindCommonRequirements(binding.Document.Statements.Concat(models[0].Body?.Statements ?? [])).Select(Located));if(model.Word("Units")!="mm")diagnostics.Add(new(PlasticDiagnosticCodes.SourceInvalid,PlasticDiagnosticSeverity.Error,"PlasticShell requires units: mm."));var blocks=model.Children("PlasticShell").ToArray();if(blocks.Length!=1)diagnostics.Add(new(PlasticDiagnosticCodes.SourceInvalid,PlasticDiagnosticSeverity.Error,"Exactly one PlasticShell is required."));diff --git a/Aetheris.Surfacing/BlendBoundary.cs b/Aetheris.Surfacing/BlendBoundary.csindex 8ba01ca5..b5910eaf 100644--- a/Aetheris.Surfacing/BlendBoundary.cs+++ b/Aetheris.Surfacing/BlendBoundary.cs@@ -133,6 +133,9 @@ public static class BlendBoundarySculptorpublic static BlendBoundaryResult Apply(BodyState input, string outputName, BlendBoundaryOperation operation){ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(operation);+ if (input.Construction is null) return Failure(operation, [BodyStateCapabilities.HousingRequired(input, operation.OperationKind)]);+ if (BodyStateCapabilities.ImportedReconstruction(input, operation.OperationKind) is {} imported) return Failure(operation, [imported]);+ if (BodyStateCapabilities.UnretainedSectionChain(input, operation.OperationKind) is {} history) return Failure(operation, [history]);var diagnostics = ValidateRequest(input, operation).ToList();if (diagnostics.Count > 0) return Failure(operation, diagnostics);@@ -215,8 +218,9 @@ public static class BlendBoundarySculptorprivate static IEnumerable<SculptDiagnostic> ValidateRequest(BodyState input, BlendBoundaryOperation operation){+ if (input.Construction is null) { yield return BodyStateCapabilities.HousingRequired(input, operation.OperationKind); yield break; }if (!input.SemanticInventory.ContainsKey(operation.SupportA)) yield return new("surf-blend-support-unresolved", $"SupportA '{operation.SupportA}' is not present in the input BodyState.");- if (string.IsNullOrWhiteSpace(operation.SupportB)) yield return new("surf-blend-support-unresolved", "SupportB must identify the preserved analytic shoulder.");+ if (operation.SupportB != "PlanarTopShoulder") yield return new("surf-blend-support-unresolved", $"SupportB '{operation.SupportB}' is unsupported; this materializer requires PlanarTopShoulder.");if (!operation.MayModify.Contains(operation.Region, StringComparer.Ordinal) && !operation.MayModify.Contains(operation.SupportA, StringComparer.Ordinal))yield return new("sculpt-target-not-authorized", "BlendBoundary region/support is absent from MayModify.");if (operation.MinimumContinuity > operation.PreferredContinuity) yield return new("surf-blend-continuity-invalid", "Minimum continuity cannot exceed preferred continuity.");@@ -241,7 +245,7 @@ public static class BlendBoundarySculptorelse if (patch.Validate().Count > 0) rejection = "surf-blend-trim-invalid — materialized patch contract is invalid.";else{- var construction = input.Construction with { CrownWidth = operation.RegionWidth, CrownDepth = operation.RegionDepth, CrownOffset = operation.CrownHeight, ReplacementPatch = patch };+ var construction = (input.Construction ?? throw new InvalidOperationException("Housing capability must be admitted before candidate construction.")) with { CrownWidth = operation.RegionWidth, CrownDepth = operation.RegionDepth, CrownOffset = operation.CrownHeight, ReplacementPatch = patch };var built = SculptedHousingBrepBuilder.Build(construction);if (built.Body is null) rejection = "surf-blend-topology-invalid — " + string.Join(" | ", built.Diagnostics.Select(item => item.Message));elsediff --git a/Aetheris.Surfacing/BodyStateCapabilities.cs b/Aetheris.Surfacing/BodyStateCapabilities.csnew file mode 100644index 00000000..da07cd1f--- /dev/null+++ b/Aetheris.Surfacing/BodyStateCapabilities.cs@@ -0,0 +1,24 @@+namespace Aetheris.Surfacing;++internal static class BodyStateCapabilities+{+ internal static SculptDiagnostic? ImportedReconstruction(BodyState input, string operation) =>+ input.Body.Bindings.FaceBindings.Any(binding => binding.SourceStepEntityId.HasValue)+ ? new("bodystate-imported-reconstruction-unsupported",+ $"{operation} rebuilds a housing and cannot preserve the imported face provenance of '{input.AuthoredName}'. " ++ "Use the explicit imported-face graft API for its admitted operation; the predecessor remains unchanged.", input.AuthoredName)+ : null;+ internal static SculptDiagnostic? UnretainedSectionChain(BodyState input, string operation)+ {+ var retained = input.ConstructionAuthority?.Operations.FirstOrDefault(o => o.Payload is AddSectionChainOperation or RemoveSectionChainOperation);+ return retained is null ? null : new("bodystate-history-capability-unsupported",+ $"{operation} cannot retain prior {retained.OperationKind} '{retained.OperationId}' with the current materializer. " ++ "The operation was rejected before reconstruction; the predecessor remains authoritative.", input.AuthoredName);+ }++ internal static SculptDiagnostic HousingRequired(BodyState input, string operation) => new(+ "bodystate-operation-capability-unsupported",+ $"{operation} cannot edit engineering body '{input.AuthoredName}' with the current materializer. " ++ "This operation rebuilds the rectangular housing construction; arbitrary body regions are not supported. " ++ "Use an admitted engineering feature on the source body. The input state remains unchanged.", input.AuthoredName);+}diff --git a/Aetheris.Surfacing/ConstructionReplay.cs b/Aetheris.Surfacing/ConstructionReplay.csindex 44a70c2a..e4c82140 100644--- a/Aetheris.Surfacing/ConstructionReplay.cs+++ b/Aetheris.Surfacing/ConstructionReplay.cs@@ -1,6 +1,7 @@using System.Text.Json;using System.Text.Json.Serialization;using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Geometry.Surfaces;namespace Aetheris.Surfacing;@@ -14,126 +15,11 @@ internal static class ConstructionAuthorityEvolutionGeometricDelta delta,IReadOnlyList<SculptValidationEvidence> evidence){- var authority = input.ConstructionAuthority ?? ConstructionState.FromHousing(input.Construction, input.BodyStableId + ".legacy-base");+ var authority = input.ConstructionAuthority ?? ConstructionState.FromHousing(input.Construction ?? throw new InvalidOperationException("A non-housing state requires explicit construction authority."), input.BodyStableId + ".legacy-base");return authority.Append(ConstructionOperationState.Accepted(input, outputName, operation, outputStateId, delta, evidence));}}-public sealed record ConstructionReplayStep(- int Index,- string OperationId,- string OperationKind,- BodyStateId AuthoredPredecessor,- BodyStateId RealizedPredecessor,- BodyStateId? RealizedOutput,- bool Succeeded,- IReadOnlyList<SculptDiagnostic> Diagnostics);--public sealed record ConstructionReplayResult(- bool IsSuccess,- BodyState? OutputState,- BodyState? AuthoritativePredecessor,- ConstructionOperationState? FailedOperation,- IReadOnlyList<ConstructionReplayStep> Steps,- IReadOnlyList<SculptDiagnostic> Diagnostics);--/// <summary>Correctness-baseline full replay of one linear typed construction program.</summary>-public static class ConstructionStateReplayer-{- public static ConstructionReplayResult Replay(ConstructionState constructionState, string? outputName = null)- {- ArgumentNullException.ThrowIfNull(constructionState);- if (!StringComparer.Ordinal.Equals(constructionState.SchemaId, ConstructionState.CurrentSchemaId)- || constructionState.SchemaVersion != ConstructionState.CurrentSchemaVersion)- return Failure(null, null, null, [], "bodystate-construction-version-unsupported",- $"ConstructionState schema '{constructionState.SchemaId}' version {constructionState.SchemaVersion} is unsupported; expected {ConstructionState.CurrentSchemaId} v{ConstructionState.CurrentSchemaVersion}.");-- SculptResult created;- switch (constructionState.Base)- {- case HousingBaseConstruction housing when housing.SchemaVersion == 1:- var recipe = housing.Housing;- created = SculptedHousingFactory.CreateBase(housing.BaseId, recipe.Width, recipe.Depth, recipe.BaseHeight, recipe.Holes);- break;- case HousingBaseConstruction housing:- return Failure(null, null, null, [], "bodystate-base-version-unsupported",- $"BaseConstruction '{housing.BaseId}' payload version {housing.SchemaVersion} is unsupported.");- default:- return Failure(null, null, null, [], "bodystate-base-kind-unsupported",- $"BaseConstruction kind '{constructionState.Base.BaseKind}' is not admitted by this runtime.");- }-- if (!created.IsSuccess || created.OutputState is null)- return new(false, null, null, null, [], [new("bodystate-base-replay-failed",- "BaseConstruction could not be realized: " + string.Join(" | ", created.Diagnostics.Select(item => $"{item.Code}:{item.Message}"))) ]);-- var current = created.OutputState with { ConstructionAuthority = constructionState with { Operations = [] } };- var steps = new List<ConstructionReplayStep>();- for (var index = 0; index < constructionState.Operations.Count; index++)- {- var authored = constructionState.Operations[index];- if (index > 0 && authored.PredecessorStateId != constructionState.Operations[index - 1].OutputStateId)- return OperationFailure(current, authored, index, steps, [new("bodystate-operation-order-invalid",- $"Operation '{authored.OperationId}' names predecessor {authored.PredecessorStateId.Value}, but the preceding authored operation outputs {constructionState.Operations[index - 1].OutputStateId.Value}.", authored.OperationId)]);- if (authored.PayloadVersion != authored.Payload.SchemaVersion || authored.PayloadVersion != 1)- return OperationFailure(current, authored, index, steps, [new("bodystate-operation-version-unsupported",- $"Operation '{authored.OperationId}' ({authored.OperationKind}) payload version {authored.PayloadVersion} is unsupported.", authored.OperationId)]);- if (!StringComparer.Ordinal.Equals(authored.OperationId, authored.Payload.StableId)- || !StringComparer.Ordinal.Equals(authored.OperationKind, authored.Payload.OperationKind))- return OperationFailure(current, authored, index, steps, [new("bodystate-operation-identity-invalid",- $"Operation envelope '{authored.OperationId}'/{authored.OperationKind} does not match its typed payload '{authored.Payload.StableId}'/{authored.Payload.OperationKind}.", authored.OperationId)]);-- var nextName = index == constructionState.Operations.Count - 1 && !string.IsNullOrWhiteSpace(outputName)- ? outputName! : authored.OutputAuthoredName;- var realized = Apply(current, nextName, authored.Payload);- if (!realized.IsSuccess || realized.OutputState is null)- return OperationFailure(current, authored, index, steps, realized.Diagnostics);-- var output = realized.OutputState;- var replayedOperations = output.ConstructionAuthority!.Operations.ToArray();- replayedOperations[^1] = replayedOperations[^1] with { ReplayStatus = ConstructionReplayStatus.ReplayedAndValidated };- current = output with { ConstructionAuthority = output.ConstructionAuthority with { Operations = replayedOperations } };- steps.Add(new(index, authored.OperationId, authored.OperationKind, authored.PredecessorStateId,- realized.Delta!.InputState, current.StateId, true, []));- }-- return new(true, current, current, null, steps, []);- }-- private static SculptResult Apply(BodyState input, string outputName, IConstructionOperation operation) => operation switch- {- OffsetRegionOperation offset => OffsetRegionSculptor.Apply(input, outputName, offset),- ReplaceRegionOperation replace => ReplaceRegionSculptor.Apply(input, outputName, replace),- SafeHoleOperation hole => SafeHoleSculptor.Apply(input, outputName, hole),- BlendBoundaryOperation blend => Blend(BlendBoundarySculptor.Apply(input, outputName, blend)),- AddSectionChainOperation add => AddSectionChainSculptor.Apply(input, outputName, add),- RemoveSectionChainOperation remove => RemoveSectionChainSculptor.Apply(input, outputName, remove),- _ => SculptResult.Failure([new("bodystate-operation-kind-unsupported",- $"Typed construction operation '{operation.OperationKind}' is not admitted by this runtime.", operation.StableId)])- };-- private static SculptResult Blend(BlendBoundaryResult result) => result.IsSuccess && result.OutputState is not null- ? new(true, result.OutputState, result.Delta, result.OutputState.ValidationEvidence, result.Diagnostics)- : SculptResult.Failure(result.Diagnostics);-- private static ConstructionReplayResult OperationFailure(BodyState current, ConstructionOperationState operation, int index,- List<ConstructionReplayStep> steps, IReadOnlyList<SculptDiagnostic> cause)- {- var diagnostics = new List<SculptDiagnostic>- {- new("bodystate-operation-replay-failed",- $"Replay failed atomically at operation {index} '{operation.OperationId}' ({operation.OperationKind}); predecessor {current.StateId.Value} remains authoritative.", operation.OperationId)- };- diagnostics.AddRange(cause);- steps.Add(new(index, operation.OperationId, operation.OperationKind, operation.PredecessorStateId, current.StateId, null, false, cause));- return new(false, null, current, operation, steps, diagnostics);- }-- private static ConstructionReplayResult Failure(BodyState? output, BodyState? predecessor, ConstructionOperationState? operation,- IReadOnlyList<ConstructionReplayStep> steps, string code, string message)- => new(false, output, predecessor, operation, steps, [new(code, message)]);-}-public sealed record ConstructionStateSerializationResult(bool IsSuccess,ConstructionState? ConstructionState,@@ -153,6 +39,7 @@ public static class ConstructionStateSerializerDefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull};options.Converters.Add(new Direction3DConverter());+ options.Converters.Add(new SurfacePatchConverter());return options;}@@ -177,6 +64,45 @@ public static class ConstructionStateSerializerprivate static ConstructionStateSerializationResult Failure(string code, string message) => new(false, null, null, [new(code, message)]);+ private sealed class SurfacePatchConverter : JsonConverter<BoundedSurfacePatch>+ {+ public override BoundedSurfacePatch Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)+ {+ using var document = JsonDocument.ParseValue(ref reader);+ var root = document.RootElement;+ try+ {+ // Earlier writers emitted the effective support without a patch+ // discriminator. Recover that actual spline data, not a delegate.+ var splineJson = root.TryGetProperty("spline", out var explicitSpline) ? explicitSpline+ : root.GetProperty("support").GetProperty("bSplineSurfaceWithKnots");+ if (root.TryGetProperty("$patchKind", out var kind) && kind.GetString() != "BSpline")+ throw new JsonException("Unsupported persisted patch kind.");+ var spline = splineJson.Deserialize<BSplineSurfaceWithKnots>(options) ?? throw new JsonException("Missing spline support.");+ return new BSplineSurfacePatch(root.GetProperty("patchId").GetString() ?? throw new JsonException("Missing patch identity."),+ spline, root.GetProperty("parameterDomain").Deserialize<SurfaceParameterDomain>(options),+ root.GetProperty("boundaryLoop").Deserialize<SurfaceBoundaryLoop>(options) ?? throw new JsonException("Missing boundary correspondence."),+ root.GetProperty("reversedOrientation").GetBoolean(), root.GetProperty("surfaceClass").Deserialize<SurfacePatchClass>(options));+ }+ catch (Exception exception) when (exception is KeyNotFoundException or InvalidOperationException or ArgumentException)+ { throw new JsonException("Invalid persisted surface-patch construction: " + exception.Message, exception); }+ }++ public override void Write(Utf8JsonWriter writer, BoundedSurfacePatch value, JsonSerializerOptions options)+ {+ if (value is not BSplineSurfacePatch patch)+ throw new NotSupportedException("Persisted patch construction requires typed BSpline support; an opaque analytic evaluator is not replay authority.");+ writer.WriteStartObject();+ writer.WriteString("$patchKind", "BSpline"); writer.WriteString("patchId", patch.PatchId);+ writer.WritePropertyName("spline"); JsonSerializer.Serialize(writer, patch.Spline, options);+ writer.WritePropertyName("parameterDomain"); JsonSerializer.Serialize(writer, patch.ParameterDomain, options);+ writer.WritePropertyName("boundaryLoop"); JsonSerializer.Serialize(writer, patch.BoundaryLoop, options);+ writer.WriteBoolean("reversedOrientation", patch.ReversedOrientation);+ writer.WritePropertyName("surfaceClass"); JsonSerializer.Serialize(writer, patch.SurfaceClass, options);+ writer.WriteEndObject();+ }+ }+private sealed class Direction3DConverter : JsonConverter<Direction3D>{public override Direction3D Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)diff --git a/Aetheris.Surfacing/ImportedFaceRegionReplacer.cs b/Aetheris.Surfacing/ImportedFaceRegionReplacer.csindex 14af6342..de128b3b 100644--- a/Aetheris.Surfacing/ImportedFaceRegionReplacer.cs+++ b/Aetheris.Surfacing/ImportedFaceRegionReplacer.cs@@ -25,15 +25,19 @@ public static class ImportedFaceRegionReplacerpublic static BodyState AdoptImportedBody(BodyState semanticSource, BrepBody importedBody, string authoredName){ArgumentNullException.ThrowIfNull(semanticSource); ArgumentNullException.ThrowIfNull(importedBody);+ if (semanticSource.Construction is null) throw new ArgumentException("The imported housing adapter requires an explicit housing semantic source.", nameof(semanticSource));+ var geometry = Step242Exporter.ExportBody(importedBody);+ if (!geometry.IsSuccess) throw new ArgumentException("Imported body cannot be retained: " + string.Join("; ", geometry.Diagnostics.Select(d => d.Message)), nameof(importedBody));var associations = SculptedHousingFactory.PersistentAssociations(importedBody, semanticSource.Construction);return semanticSource with{- StateId = BodyStateId.Derive($"{semanticSource.StateId.Value}|ImportedStep|{importedBody.Topology.Faces.Count()}"),+ StateId = BodyStateId.Derive($"{semanticSource.StateId.Value}|ImportedStep|{geometry.Value}"),PredecessorStateId = semanticSource.StateId,AuthoredName = authoredName,Body = importedBody,+ ConstructionAuthority = null, // This adapter has no source/import recipe to replay.GeometryAssociations = associations,- SemanticPmi = SculptedHousingFactory.SemanticPmi(associations, semanticSource.Construction),+ SemanticPmi = SculptedHousingFactory.SemanticPmi(associations, semanticSource.Construction, importedBody),AssemblyInterfaces = SculptedHousingFactory.AssemblyInterfaces(associations)};}@@ -45,6 +49,7 @@ public static class ImportedFaceRegionReplacerstring outputName,double tolerance = 1e-5){+ if (importedState.Construction is null) return new(false, null, null, [BodyStateCapabilities.HousingRequired(importedState, "ImportedFaceReplacement")]);var historical = importedState.Delta?.Correspondence.FirstOrDefault(item => item.Change == GeometricChangeKind.Replaced&& item.InputEntity == $"ADVANCED_FACE:{sourceStepFaceEntityId}");if (historical is not null)@@ -89,9 +94,9 @@ public static class ImportedFaceRegionReplacervar inventory = importedState.SemanticInventory.ToDictionary(item => item.Key, item => item.Value, StringComparer.Ordinal);inventory.Remove(SculptedHousingFactory.CrownRegion);inventory[replacementPatch.PatchId] = new(replacementPatch.PatchId, SculptEntityKind.Surface,- $"{replacementPatch.ExportClass}:{replacementPatch.DegreeU}x{replacementPatch.DegreeV}:{replacementPatch.ControlCountU}x{replacementPatch.ControlCountV}",+ replacementPatch.GeometryFingerprint,"Imported ADVANCED_FACE semantic successor.");- var outputId = BodyStateId.Derive($"{importedState.StateId.Value}|ImportedReplaceRegion|{sourceStepFaceEntityId}|{replacementPatch.PatchId}");+ var outputId = BodyStateId.Derive($"{importedState.StateId.Value}|ImportedReplaceRegion|{sourceStepFaceEntityId}|{replacementPatch.PatchId}|{replacementPatch.GeometryFingerprint}|{replacementPatch.ReversedOrientation}");var delta = new GeometricDelta(importedState.StateId, outputId, [$"ADVANCED_FACE:{sourceStepFaceEntityId}"],[SculptedHousingFactory.BottomMountingInterface, SculptedHousingFactory.MountingHolePattern], [SculptedHousingFactory.CrownRegion], [], [replacementPatch.PatchId],[SculptedHousingFactory.CrownRegion], new(-construction.Width / 2d, -construction.Depth / 2d, construction.BaseHeight, construction.Width / 2d, construction.Depth / 2d, construction.FinalHeight),@@ -108,7 +113,7 @@ public static class ImportedFaceRegionReplacervar validations = SculptedHousingFactory.ValidateBody(body, tolerance).Append(new SculptValidationEvidence("ImportedFaceReplacement", true,LocalityEvidenceLevel.CertifiedBounded, 0d, tolerance, $"Retained topology and {evidence.PreservedNeighborSourceStepEntityIds.Count} neighboring imported face provenances; replaced support on current face {selected.FaceId.Value}.")).ToArray();var output = new BodyState(outputId, importedState.StateId, importedState.BodyStableId, outputName, body, construction, inventory, delta, validations,- associations, SculptedHousingFactory.SemanticPmi(associations, construction), SculptedHousingFactory.AssemblyInterfaces(associations));+ associations, SculptedHousingFactory.SemanticPmi(associations, construction, body), SculptedHousingFactory.AssemblyInterfaces(associations));return new(true, output, evidence, []);}diff --git a/Aetheris.Surfacing/SculptedHousingBrepBuilder.cs b/Aetheris.Surfacing/SculptedHousingBrepBuilder.csindex a03ad15a..8906f904 100644--- a/Aetheris.Surfacing/SculptedHousingBrepBuilder.cs+++ b/Aetheris.Surfacing/SculptedHousingBrepBuilder.cs@@ -237,6 +237,10 @@ internal static class SculptedHousingBrepBuilderif (!Positive(c.Width) || !Positive(c.Depth) || !Positive(c.BaseHeight)) d.Add(new("sculpt-housing-invalid", "Housing width, depth, and base height must be positive and finite."));if (!Positive(c.CrownWidth) || !Positive(c.CrownDepth) || c.CrownWidth > c.Width || c.CrownDepth > c.Depth) d.Add(new("sculpt-target-domain-invalid", "Crown region must be positive and contained by the housing footprint."));if (!double.IsFinite(c.CrownOffset) || c.FinalHeight <= 0d) d.Add(new("sculpt-self-intersection", "Offset crosses or collapses the bottom mounting plane."));+ if (c.Holes.Any(h => string.IsNullOrWhiteSpace(h.StableId)))+ d.Add(new("sculpt-hole-identity-required", "Every housing hole needs a nonempty semantic identity; name the Hole or supply HoleFeature id."));+ foreach (var duplicate in c.Holes.GroupBy(h => h.StableId, StringComparer.Ordinal).Where(g => g.Count() > 1))+ d.Add(new("sculpt-hole-duplicate", $"Hole identity '{duplicate.Key}' is declared more than once.", duplicate.Key));foreach (var h in c.Holes){var r = h.Diameter / 2d;diff --git a/Aetheris.Surfacing/SculptingExecution.cs b/Aetheris.Surfacing/SculptingExecution.csindex 706cb54d..0693abbf 100644--- a/Aetheris.Surfacing/SculptingExecution.cs+++ b/Aetheris.Surfacing/SculptingExecution.cs@@ -37,7 +37,7 @@ public static class SculptedHousingFactory[new("sculpt-base-invalid", "Initial body did not satisfy the body-state validity contract: " + string.Join("; ", evidence.Where(x => !x.Satisfied).Select(x => $"{x.Check}: {x.Detail}")))], evidence);var associations = PersistentAssociations(built.Body, construction);return new(true, new(stateId, null, "housing-body", stateName, built.Body, construction, inventory, null, evidence,- associations, SemanticPmi(associations, construction), AssemblyInterfaces(associations), ConstructionAuthority: ConstructionState.FromHousing(construction)), null, evidence, []);+ associations, SemanticPmi(associations, construction, built.Body), AssemblyInterfaces(associations), ConstructionAuthority: ConstructionState.FromHousing(construction)), null, evidence, []);}internal static IReadOnlyDictionary<string, SculptSemanticEntity> Inventory(HousingConstruction c)@@ -57,6 +57,7 @@ public static class SculptedHousingFactory[HousingSideEast] = new(HousingSideEast, SculptEntityKind.Region, $"plane:x={c.Width / 2d:R};y={-c.Depth / 2d:R}..{c.Depth / 2d:R};z=0..{c.BaseHeight:R}", "Semantic east housing support region."),[HousingSideWest] = new(HousingSideWest, SculptEntityKind.Region, $"plane:x={-c.Width / 2d:R};y={-c.Depth / 2d:R}..{c.Depth / 2d:R};z=0..{c.BaseHeight:R}", "Semantic west housing support region."),};+ if (c.Holes.Count == 0) inventory.Remove(MountingHolePattern);foreach (var hole in c.Holes) inventory[hole.StableId] = new(hole.StableId, SculptEntityKind.Region, HoleFingerprint(hole), "Stable mounting-hole feature.");return inventory;}@@ -84,11 +85,11 @@ public static class SculptedHousingFactoryvar bottom = bottomCandidates.Where(face => face.LoopIds.Count == maximumLoopCount).Select(face => face.Id.Value).ToArray();var cylinders = body.Topology.Faces.Where(face => body.TryGetFaceSurfaceGeometry(face.Id, out var support) && support?.Cylinder is not null).Select(face => face.Id.Value).Order().ToArray();- return- [- new(BottomMountingInterface, PersistentAssociationState.Preserved, bottom, "Explicit protected bottom-plane association."),- new(MountingHolePattern, PersistentAssociationState.Preserved, cylinders, "Explicit protected cylindrical-face association."),- ];+ var associations = new List<PersistentGeometryAssociation>+ { new(BottomMountingInterface, PersistentAssociationState.Preserved, bottom, "Explicit protected bottom-plane association.") };+ if (construction.Holes.Count > 0)+ associations.Add(new(MountingHolePattern, PersistentAssociationState.Preserved, cylinders, "Explicit protected cylindrical-face association."));+ return associations;}public static PersistentAssociationRemapResult RemapPersistentAssociations(BodyState input, BrepBody outputBody, GeometricDelta delta)@@ -120,17 +121,27 @@ public static class SculptedHousingFactoryreturn new(diagnostics.Count == 0, remapped, diagnostics);}- internal static IReadOnlyList<Step242SemanticPmi> SemanticPmi(IReadOnlyList<PersistentGeometryAssociation> associations, HousingConstruction construction)+ internal static IReadOnlyList<Step242SemanticPmi> SemanticPmi(IReadOnlyList<PersistentGeometryAssociation> associations, HousingConstruction construction, BrepBody body){var bottom = associations.Single(item => item.SemanticTarget == BottomMountingInterface).FaceIds;+ if (construction.Holes.Count == 0)+ return [new Step242SemanticPmiDatum("DatumA", "plane", "A", BottomMountingInterface) { GeometricFaceIds = bottom }];var holes = associations.Single(item => item.SemanticTarget == MountingHolePattern).FaceIds;- var diameter = construction.Holes[0].Diameter;- return- [- new Step242SemanticPmiDatum("DatumA", "plane", "A", BottomMountingInterface) { GeometricFaceIds = bottom },- new Step242SemanticPmiHole(MountingHolePattern, diameter, construction.BaseHeight, "through", .05d, -.05d, construction.Holes.Count) { GeometricFaceIds = holes },- new Step242SemanticPmiGeometricTolerance(MountingHolePattern, "HolePatternPosition", "position", .1d, ["A"], construction.Holes.Count) { GeometricFaceIds = holes },- ];+ var groups = construction.Holes.GroupBy(h => h.Diameter).OrderBy(g => g.Key).ToArray();+ var pmi = new List<Step242SemanticPmi>+ { new Step242SemanticPmiDatum("DatumA", "plane", "A", BottomMountingInterface) { GeometricFaceIds = bottom } };+ foreach (var group in groups)+ {+ var target = groups.Length == 1 ? MountingHolePattern : MountingHolePattern + ".Diameter" ++ group.Key.ToString("R", System.Globalization.CultureInfo.InvariantCulture).Replace('.', '_');+ // These faces already belong to the explicit constructed bore pattern.+ // Group by its exact analytic support radius, never nearest-face search.+ var faces = groups.Length == 1 ? holes : holes.Where(id => body.TryGetFaceSurfaceGeometry(new(id), out var support)+ && support?.Cylinder is {} cylinder && cylinder.Radius == group.Key / 2d).ToArray();+ pmi.Add(new Step242SemanticPmiHole(target, group.Key, construction.BaseHeight, "through", .05d, -.05d, group.Count()) { GeometricFaceIds = faces });+ }+ pmi.Add(new Step242SemanticPmiGeometricTolerance(MountingHolePattern, "HolePatternPosition", "position", .1d, ["A"], construction.Holes.Count) { GeometricFaceIds = holes });+ return pmi;}internal static IReadOnlyList<SculptAssemblyInterface> AssemblyInterfaces(IReadOnlyList<PersistentGeometryAssociation> associations)@@ -150,7 +161,12 @@ public static class OffsetRegionSculptorpublic static SculptResult Apply(BodyState input, string outputName, OffsetRegionOperation operation){ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(operation);+ if (input.Construction is null) return SculptResult.Failure([BodyStateCapabilities.HousingRequired(input, operation.OperationKind)]);+ if (BodyStateCapabilities.ImportedReconstruction(input, operation.OperationKind) is {} imported) return SculptResult.Failure([imported]);+ if (BodyStateCapabilities.UnretainedSectionChain(input, operation.OperationKind) is {} history) return SculptResult.Failure([history]);var diagnostics = new List<SculptDiagnostic>(); var evidence = new List<SculptValidationEvidence>();+ if (operation.TargetRegion != SculptedHousingFactory.CrownRegion || input.Construction.ReplacementPatch is not null)+ diagnostics.Add(new("sculpt-target-capability-unsupported", "OffsetRegion supports the current rectangular HousingCrown only; it cannot offset another semantic region or an accepted replacement patch.", operation.TargetRegion));if (!input.SemanticInventory.ContainsKey(operation.TargetRegion)) diagnostics.Add(new("sculpt-target-unresolved", $"Target region '{operation.TargetRegion}' does not exist in the input state.", operation.TargetRegion));if (!operation.MayModify.Contains(operation.TargetRegion, StringComparer.Ordinal)) diagnostics.Add(new("sculpt-target-not-authorized", "Target region is not present in MayModify.", operation.TargetRegion));if (operation.BoundaryContinuity != "G0") diagnostics.Add(new("sculpt-boundary-continuity-unsupported", "SURF-X0 supports G0 positional continuity only."));@@ -209,7 +225,7 @@ public static class OffsetRegionSculptorvar outputAssociations = associationRemap.Associations;var authority = ConstructionAuthorityEvolution.Append(input, outputName, operation, outputId, delta, evidence);var output = new BodyState(outputId, input.StateId, input.BodyStableId, outputName, built.Body, outputConstruction, inventory, delta, evidence,- outputAssociations, SculptedHousingFactory.SemanticPmi(outputAssociations, outputConstruction), SculptedHousingFactory.AssemblyInterfaces(outputAssociations), ConstructionAuthority: authority);+ outputAssociations, SculptedHousingFactory.SemanticPmi(outputAssociations, outputConstruction, built.Body), SculptedHousingFactory.AssemblyInterfaces(outputAssociations), ConstructionAuthority: authority);return new(true, output, delta, evidence, []);}}@@ -225,7 +241,12 @@ public static class ReplaceRegionSculptorprivate static SculptResult ApplyCore(BodyState input, string outputName, ReplaceRegionOperation operation, SpatialInfluenceEnvelope? certifiedBounds){ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(operation);+ if (input.Construction is null) return SculptResult.Failure([BodyStateCapabilities.HousingRequired(input, operation.OperationKind)]);+ if (BodyStateCapabilities.ImportedReconstruction(input, operation.OperationKind) is {} imported) return SculptResult.Failure([imported]);+ if (BodyStateCapabilities.UnretainedSectionChain(input, operation.OperationKind) is {} history) return SculptResult.Failure([history]);var diagnostics = operation.ReplacementPatch.Validate().ToList();+ if (operation.TargetRegion != SculptedHousingFactory.CrownRegion && operation.TargetRegion != input.Construction.ReplacementPatch?.PatchId)+ diagnostics.Add(new("sculpt-target-capability-unsupported", "ReplaceRegion supports HousingCrown or its current replacement patch only.", operation.TargetRegion));var evidence = new List<SculptValidationEvidence>();if (!input.SemanticInventory.ContainsKey(operation.TargetRegion)){@@ -326,7 +347,7 @@ public static class ReplaceRegionSculptorvar inventory = SculptedHousingFactory.Inventory(construction).ToDictionary(x => x.Key, x => x.Value, StringComparer.Ordinal);inventory.Remove(SculptedHousingFactory.CrownRegion);inventory[operation.ReplacementPatch.PatchId] = new(operation.ReplacementPatch.PatchId, SculptEntityKind.Surface,- $"{operation.ReplacementPatch.ExportClass}:{operation.ReplacementPatch.DegreeU}x{operation.ReplacementPatch.DegreeV}:{operation.ReplacementPatch.ControlCountU}x{operation.ReplacementPatch.ControlCountV}", "Accepted bounded replacement patch.");+ operation.ReplacementPatch.GeometryFingerprint, "Accepted bounded replacement patch.");foreach (var contract in operation.Preserves){var before = input.SemanticInventory[contract.EntityId]; var after = inventory[contract.EntityId];@@ -358,7 +379,7 @@ public static class ReplaceRegionSculptorvar outputAssociations = associationRemap.Associations;var authority = ConstructionAuthorityEvolution.Append(input, outputName, operation, outputId, delta, evidence);return new(true, new(outputId, input.StateId, input.BodyStableId, outputName, built.Body, construction, inventory, delta, evidence,- outputAssociations, SculptedHousingFactory.SemanticPmi(outputAssociations, construction), SculptedHousingFactory.AssemblyInterfaces(outputAssociations), ConstructionAuthority: authority), delta, evidence, []);+ outputAssociations, SculptedHousingFactory.SemanticPmi(outputAssociations, construction, built.Body), SculptedHousingFactory.AssemblyInterfaces(outputAssociations), ConstructionAuthority: authority), delta, evidence, []);}private static IReadOnlyList<Point3D> Sample(BoundedSurfacePatch patch, int count)@@ -434,7 +455,12 @@ public static class SafeHoleSculptor{public static SculptResult Apply(BodyState input, string outputName, SafeHoleOperation operation){+ ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(operation);+ if (input.Construction is null) return SculptResult.Failure([BodyStateCapabilities.HousingRequired(input, operation.OperationKind)]);+ if (BodyStateCapabilities.ImportedReconstruction(input, operation.OperationKind) is {} imported) return SculptResult.Failure([imported]);var diagnostics = new List<SculptDiagnostic>(); var evidence = new List<SculptValidationEvidence>();+ if (operation.TargetRegion is not (SculptedHousingFactory.CrownRegion or SculptedHousingFactory.OuterFootprintBoundary))+ diagnostics.Add(new("sculpt-target-capability-unsupported", "HoleFeature supports the housing's planar top/footprint frame only; another named region is not a drilling placement.", operation.TargetRegion));if (!input.SemanticInventory.ContainsKey(operation.TargetRegion))diagnostics.Add(new("sculpt-target-unresolved", $"Hole target '{operation.TargetRegion}' does not exist in the current BodyState.", operation.TargetRegion));if (input.SemanticInventory.ContainsKey(operation.Hole.StableId)) diagnostics.Add(new("sculpt-hole-duplicate", $"Hole '{operation.Hole.StableId}' already exists.", operation.Hole.StableId));@@ -445,7 +471,9 @@ public static class SafeHoleSculptorif (diagnostics.Count > 0) return SculptResult.Failure(diagnostics);var construction = input.Construction with { Holes = [.. input.Construction.Holes, operation.Hole] };- var retainedAdd = input.ConstructionAuthority?.Operations.LastOrDefault()?.Payload as AddSectionChainOperation;+ if (input.ConstructionAuthority?.Operations.Any(o => o.Payload is RemoveSectionChainOperation) == true)+ return SculptResult.Failure([BodyStateCapabilities.UnretainedSectionChain(input, operation.OperationKind)!]);+ var retainedAdd = input.ConstructionAuthority?.Operations.Select(o => o.Payload).OfType<AddSectionChainOperation>().LastOrDefault();BrepBody? realizedBody; IReadOnlyList<SculptDiagnostic> buildDiagnostics;if (retainedAdd is not null){@@ -462,7 +490,7 @@ public static class SafeHoleSculptorif (construction.ReplacementPatch is { } patch){inventory.Remove(SculptedHousingFactory.CrownRegion);- inventory[patch.PatchId] = new(patch.PatchId, SculptEntityKind.Surface, $"{patch.ExportClass}:{patch.DegreeU}x{patch.DegreeV}:{patch.ControlCountU}x{patch.ControlCountV}", "Accepted bounded replacement patch.");+ inventory[patch.PatchId] = new(patch.PatchId, SculptEntityKind.Surface, patch.GeometryFingerprint, "Accepted bounded replacement patch.");}if (retainedAdd is not null){@@ -485,7 +513,7 @@ public static class SafeHoleSculptorvar outputAssociations = SculptedHousingFactory.PersistentAssociations(realizedBody, construction);var authority = ConstructionAuthorityEvolution.Append(input, outputName, operation, outputId, delta, evidence);return new(true, new(outputId, input.StateId, input.BodyStableId, outputName, realizedBody, construction, inventory, delta, evidence,- outputAssociations, SculptedHousingFactory.SemanticPmi(outputAssociations, construction), SculptedHousingFactory.AssemblyInterfaces(outputAssociations), ConstructionAuthority: authority), delta, evidence, []);+ outputAssociations, SculptedHousingFactory.SemanticPmi(outputAssociations, construction, realizedBody), SculptedHousingFactory.AssemblyInterfaces(outputAssociations), ConstructionAuthority: authority), delta, evidence, []);}}@@ -555,6 +583,13 @@ public static class SculptStepExporter{public static SculptStepResult Export(BodyState state, string productName){+ if (state.Construction is null && state.RealizedStepText is {} admittedStep)+ {+ if (state.RealizedStepProductName is {} originalName && productName != originalName)+ return new(false, null, Inventory(admittedStep), [new("bodystate-product-name-mismatch",+ $"Engineering state retains authored product '{originalName}'; requested '{productName}'. Rename the source Model and rebuild to preserve its complete PMI product associations.", state.AuthoredName)]);+ return new(true, admittedStep, Inventory(admittedStep), []);+ }var semanticPmi = new List<Step242SemanticPmi>(state.SemanticPmi ?? []);foreach (var assemblyInterface in state.AssemblyInterfaces ?? [])semanticPmi.Add(new Step242SemanticPmiNote($"assembly-interface:{assemblyInterface.StableId}", assemblyInterface.SemanticTarget, assemblyInterface.Description)@@ -562,11 +597,12 @@ public static class SculptStepExportervar export = Step242Exporter.ExportBody(state.Body, semanticPmi, new Step242ExportOptions { BrepExportPreflightMode = BrepExportPreflightMode.Enforce, ProductName = productName });if (!export.IsSuccess) return new(false, null, Empty(), export.Diagnostics.Select(x => new SculptDiagnostic("surf-step-export-failed", x.Message)).ToArray());var text = export.Value;- var inventory = new StepSurfaceInventory(Count(text, "=PLANE("), Count(text, "=CYLINDRICAL_SURFACE("), Count(text, "=CONICAL_SURFACE("), Count(text, "=SPHERICAL_SURFACE("), Count(text, "=TOROIDAL_SURFACE("), Count(text, "=B_SPLINE_SURFACE_WITH_KNOTS("), 0, Count(text, "RATIONAL_B_SPLINE_SURFACE"));+ var inventory = Inventory(text);if (inventory.RationalNurbs != 0)return new(false, null, inventory, [new("surf-surface-export-normalization-failed", "STEP product boundary contains a rational NURBS surface; export was blocked.")]);return new(true, text, inventory, []);}+ private static StepSurfaceInventory Inventory(string text) => new(Count(text, "=PLANE("), Count(text, "=CYLINDRICAL_SURFACE("), Count(text, "=CONICAL_SURFACE("), Count(text, "=SPHERICAL_SURFACE("), Count(text, "=TOROIDAL_SURFACE("), Count(text, "=B_SPLINE_SURFACE_WITH_KNOTS("), 0, Count(text, "RATIONAL_B_SPLINE_SURFACE"));private static int Count(string text, string marker) => (text.Length - text.Replace(marker, string.Empty, StringComparison.Ordinal).Length) / marker.Length;private static StepSurfaceInventory Empty() => new(0, 0, 0, 0, 0, 0, 0, 0);}diff --git a/Aetheris.Surfacing/SculptingState.cs b/Aetheris.Surfacing/SculptingState.csindex 81c0ffde..90c92e11 100644--- a/Aetheris.Surfacing/SculptingState.cs+++ b/Aetheris.Surfacing/SculptingState.cs@@ -73,6 +73,7 @@ public sealed record HousingConstruction([JsonPolymorphic(TypeDiscriminatorPropertyName = "$baseKind")][JsonDerivedType(typeof(HousingBaseConstruction), "Housing")]+[JsonDerivedType(typeof(EngineeringSourceConstruction), "EngineeringSource")]public interface IBaseConstruction{string BaseId { get; }@@ -86,6 +87,14 @@ public sealed record HousingBaseConstruction(string BaseId, HousingConstructionpublic string BaseKind => "Housing";}+/// <summary>Replay authority is the authored engineering program and selected body,+/// not a fitted housing recipe or a snapshot of its final faces.</summary>+public sealed record EngineeringSourceConstruction(string BaseId, string Source, string SourceFile, string InputName,+ int SchemaVersion = 1) : IBaseConstruction+{+ public string BaseKind => "EngineeringSource";+}+[JsonPolymorphic(TypeDiscriminatorPropertyName = "$operationKind")][JsonDerivedType(typeof(OffsetRegionOperation), "OffsetRegion")][JsonDerivedType(typeof(ReplaceRegionOperation), "ReplaceRegion")]@@ -153,7 +162,7 @@ public sealed record BodyState(string BodyStableId,string AuthoredName,BrepBody Body,- HousingConstruction Construction,+ HousingConstruction? Construction,IReadOnlyDictionary<string, SculptSemanticEntity> SemanticInventory,GeometricDelta? Delta,IReadOnlyList<SculptValidationEvidence> ValidationEvidence,@@ -161,9 +170,11 @@ public sealed record BodyState(IReadOnlyList<Step242SemanticPmi>? SemanticPmi = null,IReadOnlyList<SculptAssemblyInterface>? AssemblyInterfaces = null,BlendJudgmentTrace? BlendJudgment = null,- ConstructionState? ConstructionAuthority = null)+ ConstructionState? ConstructionAuthority = null,+ string? RealizedStepText = null){- public IReadOnlyList<SurfacePatchMetadata> SurfacePatches => Construction.ReplacementPatch is { } patch+ public string? RealizedStepProductName { get; init; }+ public IReadOnlyList<SurfacePatchMetadata> SurfacePatches => Construction?.ReplacementPatch is { } patch? [SurfacePatchMetadata.From(patch, Body.Topology.Faces.FirstOrDefault(face =>Body.TryGetFaceSurfaceGeometry(face.Id, out var support) && Equals(support, patch.Support))?.LoopIds.Count ?? 1)] : [];}@@ -219,7 +230,7 @@ public sealed record ReplaceRegionOperation(string.Join(',', MayModify.Order(StringComparer.Ordinal)),$"{InfluenceEnvelope.MinX:R},{InfluenceEnvelope.MinY:R},{InfluenceEnvelope.MinZ:R},{InfluenceEnvelope.MaxX:R},{InfluenceEnvelope.MaxY:R},{InfluenceEnvelope.MaxZ:R}",string.Join(',', Preserves.OrderBy(x => x.EntityId, StringComparer.Ordinal).Select(x => $"{x.EntityId}:{x.Mode}")),- string.Join(',', Requirements.Order()), GeometricTolerance.ToString("R"), G1AngularToleranceDegrees.ToString("R"), G2CurvatureTolerance.ToString("R"));+ string.Join(',', Requirements.Order()), ReplacementPatch.GeometryFingerprint, ReplacementPatch.ReversedOrientation, GeometricTolerance.ToString("R"), G1AngularToleranceDegrees.ToString("R"), G2CurvatureTolerance.ToString("R"));}public sealed record SafeHoleOperation(diff --git a/Aetheris.Surfacing/SectionChainSculpting.cs b/Aetheris.Surfacing/SectionChainSculpting.csindex 59f2d358..1046820b 100644--- a/Aetheris.Surfacing/SectionChainSculpting.cs+++ b/Aetheris.Surfacing/SectionChainSculpting.cs@@ -9,6 +9,9 @@ public static class AddSectionChainSculptorpublic static SculptResult Apply(BodyState input, string outputName, AddSectionChainOperation operation){ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(operation);+ if (input.Construction is null) return SculptResult.Failure([BodyStateCapabilities.HousingRequired(input, operation.OperationKind)]);+ if (BodyStateCapabilities.ImportedReconstruction(input, operation.OperationKind) is {} imported) return SculptResult.Failure([imported]);+ if (BodyStateCapabilities.UnretainedSectionChain(input, operation.OperationKind) is {} history) return SculptResult.Failure([history]);var diagnostics = ValidateContract(input, operation).ToList();var evidence = new List<SculptValidationEvidence>();var bounds = Bounds(operation.Chain, input.Construction.Width / 2d);@@ -46,7 +49,7 @@ public static class AddSectionChainSculptorvar associations = SculptedHousingFactory.PersistentAssociations(built.Body, input.Construction);var authority = ConstructionAuthorityEvolution.Append(input, outputName, operation, outputId, delta, evidence);var output = new BodyState(outputId, input.StateId, input.BodyStableId, outputName, built.Body, input.Construction, inventory, delta, evidence,- associations, SculptedHousingFactory.SemanticPmi(associations, input.Construction), SculptedHousingFactory.AssemblyInterfaces(associations), ConstructionAuthority: authority);+ associations, SculptedHousingFactory.SemanticPmi(associations, input.Construction, built.Body), SculptedHousingFactory.AssemblyInterfaces(associations), ConstructionAuthority: authority);return new(true, output, delta, evidence, []);}@@ -92,6 +95,9 @@ public static class RemoveSectionChainSculptorpublic static SculptResult Apply(BodyState input, string outputName, RemoveSectionChainOperation operation){ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(operation);+ if (input.Construction is null) return SculptResult.Failure([BodyStateCapabilities.HousingRequired(input, operation.OperationKind)]);+ if (BodyStateCapabilities.ImportedReconstruction(input, operation.OperationKind) is {} imported) return SculptResult.Failure([imported]);+ if (BodyStateCapabilities.UnretainedSectionChain(input, operation.OperationKind) is {} history) return SculptResult.Failure([history]);var diagnostics = new List<SculptDiagnostic>(); var evidence = new List<SculptValidationEvidence>();if (operation.SupportRegions.Count != 2 || !operation.SupportRegions.SequenceEqual([SculptedHousingFactory.HousingSideWest, SculptedHousingFactory.HousingSideEast], StringComparer.Ordinal))diagnostics.Add(new("section-chain-remove-support-unsupported", "The admitted through-duct lane requires ordered supports [HousingSideWest, HousingSideEast]."));@@ -136,7 +142,7 @@ public static class RemoveSectionChainSculptorvar associations = SculptedHousingFactory.PersistentAssociations(built.Body, input.Construction);var authority = ConstructionAuthorityEvolution.Append(input, outputName, operation, outputId, delta, evidence);var output = new BodyState(outputId, input.StateId, input.BodyStableId, outputName, built.Body, input.Construction, inventory, delta, evidence,- associations, SculptedHousingFactory.SemanticPmi(associations, input.Construction), SculptedHousingFactory.AssemblyInterfaces(associations), ConstructionAuthority: authority);+ associations, SculptedHousingFactory.SemanticPmi(associations, input.Construction, built.Body), SculptedHousingFactory.AssemblyInterfaces(associations), ConstructionAuthority: authority);return new(true, output, delta, evidence, []);}diff --git a/Aetheris.Surfacing/SectionChains.cs b/Aetheris.Surfacing/SectionChains.csindex 7ae3b78d..cac36903 100644--- a/Aetheris.Surfacing/SectionChains.cs+++ b/Aetheris.Surfacing/SectionChains.cs@@ -74,19 +74,10 @@ public static class SectionChainCanonical{public static string Fingerprint(SectionChain chain){- var sections = chain.Sections.Select(section =>- {- var spans = section.Profile.Spans.Select(span => span.Curve switch- {- SectionProfileCurve.Line line => $"{span.SpanId}:L:{line.Start.X:R},{line.Start.Y:R}>{line.End.X:R},{line.End.Y:R}",- SectionProfileCurve.Arc arc => $"{span.SpanId}:A:{arc.Center.X:R},{arc.Center.Y:R},{arc.Radius:R},{arc.StartAngleRadians:R},{arc.SweepAngleRadians:R}",- SectionProfileCurve.PolynomialBSpline spline => $"{span.SpanId}:B:{spline.Degree}:{string.Join('/', spline.ControlPoints.Select(point => $"{point.X:R},{point.Y:R}"))}",- _ => span.SpanId- });- return $"{section.SectionId}@{section.Frame.Origin.X:R},{section.Frame.Origin.Y:R},{section.Frame.Origin.Z:R}:{string.Join(',', spans)}";- });- var fingerprint = string.Join('|', chain.StableId, chain.TransitionPolicy, chain.Continuity, chain.SmoothPolicy, chain.StartTermination, chain.EndTermination, string.Join(';', sections));- return chain.ProfileApproximationTolerance == 1e-5 ? fingerprint : fingerprint + "|ApproximationTolerance:" + chain.ProfileApproximationTolerance.ToString("R", System.Globalization.CultureInfo.InvariantCulture);+ // Hash the complete typed recipe: frames, spline knots, seam and+ // correspondence are engineering inputs, not just station origins.+ // JSON numeric formatting is invariant and the record/list order is fixed.+ return BodyStateId.Derive("SectionChain-v2|" + System.Text.Json.JsonSerializer.Serialize(chain)).Value;}}diff --git a/Aetheris.Surfacing/SurfacePatchIr.cs b/Aetheris.Surfacing/SurfacePatchIr.csindex ddcb7a88..1aacb92d 100644--- a/Aetheris.Surfacing/SurfacePatchIr.cs+++ b/Aetheris.Surfacing/SurfacePatchIr.cs@@ -1,6 +1,8 @@using Aetheris.Kernel.Core.Geometry;using Aetheris.Kernel.Core.Geometry.Surfaces;using Aetheris.Kernel.Core.Math;+using System.Text.Json;+using System.Text.Json.Serialization;namespace Aetheris.Surfacing;@@ -44,6 +46,8 @@ public abstract record BoundedSurfacePatch(SurfaceBoundaryLoop BoundaryLoop,bool ReversedOrientation){+ [JsonIgnore]+ public string GeometryFingerprint => BodyStateId.Derive("SurfacePatch-v1|" + JsonSerializer.Serialize<BoundedSurfacePatch>(this)).Value;public abstract SurfaceGeometry Support { get; }public abstract Point3D Evaluate(double u, double v);public abstract int? DegreeU { get; }diff --git a/docs/development/FIRMAMENT-BODY-STATE-DEBT-2026-10-18.md b/docs/development/FIRMAMENT-BODY-STATE-DEBT-2026-10-18.mdnew file mode 100644index 00000000..d0dbbb72--- /dev/null+++ b/docs/development/FIRMAMENT-BODY-STATE-DEBT-2026-10-18.md@@ -0,0 +1,218 @@+# Firmament body-state and semantic debt closeout++This pass follows the [remaining-domain AST migration](FIRMAMENT-REMAINING-DOMAIN-AST-2026-10-18.md).+The priority is BodyState correctness. The constraint is debt repayment, with no+new geometry operations, language control flow or parallel admission system.++## Repairs and actual ownership++| Finding | Repair / qualification |+| --- | --- |+| BodyState always called SculptedHousingFactory.CreateBase. A cylinder or existing feature body could not be retained as itself. | `input` references the Model's admitted engineering product. The AST separates state declarations from engineering construction, then the existing compiler admits/materializes that construction. Its exact body/STEP and available semantic correspondence are retained. No bounding-box fit or housing conversion occurs. A conflicting export-name override rejects rather than silently ignoring the requested name or losing PMI associations. |+| Native Gear/Sweep/Revolve/SectionChain producers did not consistently expose their authored body identity through the primitive bridge. | Retain RuntimeBodySourceName on the existing materializer result. BodyState consumes producer metadata, without parsing diagnostic feature IDs or maintaining a second construct list. Cone/sphere/torus/rounded-box/Gear/Sweep/Revolve adoption and replay are compared to their unchanged canonical source. |+| Domain Pattern expansion claimed Patterns belonging to mechanical Compose/Modify. | Expand only direct children of the actual domain owner. Mechanical patterns stay with their engineering owner; unsupported placements remain visible to AST scope closure. A patterned/explicit-PMI engineering product is retained byte-for-byte. |+| Authoring required a mounting hole even though the housing builder supports zero. Its PMI code indexed the first hole unconditionally. | Holes are optional. A hole-free housing has no hole pattern or hole PMI. A real crown edit and typed replay qualify this path. |+| A second HoleFeature after AddSectionChain could drop the chain: retention looked only at the immediately preceding operation. | Retain the typed additive construction from the full predecessor history. Two subsequent holes are compared against independently ordered construction with both bores present before attachment. |+| Other whole-housing reconstructions could erase a retained attachment/duct, and a valid semantic name did not prove an operation supported that region. | Check the actual construction/history/support capability before rebuilding. Unsupported combinations reject atomically, without publishing a successor. Offset/Replace targets and the Blend shoulder are checked explicitly. |+| Mixed-diameter housings emitted the first hole's diameter for the whole pattern. | Group hole PMI by authored diameter and the constructed bore faces' exact analytic radii. The legacy equal-diameter product stays unchanged. No nearest-face or guessed semantic rebinding is introduced. |+| Replacement-patch hashes omitted control points, while SectionChain hashes omitted frames and spline knots. Different shapes could share a state/geometry fingerprint. | Include the complete typed support and chain recipe. Regression checks change an interior control point, a frame and a knot vector while keeping names/counts fixed. |+| Abstract patch payloads could be written without a readable typed patch constructor. | The existing construction-state serializer now persists/reconstructs BSpline patch data explicitly, retaining domain, correspondence, orientation and surface class. Opaque evaluator delegates reject as replay authority. |+| The direct imported-face adapter inherited an unrelated native housing replay recipe and hashed only face count. | Clear that false authority, fingerprint the retained geometry, include patch support in graft identities, and reject whole-housing reconstruction that would discard imported face provenance. The bounded graft is not claimed as a durable imported-source program. |+| Blank/duplicate hole IDs could collapse distinct geometric bores into one semantic inventory entry. | Reject missing or duplicate hole identities before constructing a body. |+| CLI state presentation dereferenced HousingConstruction for every state. | Housing evidence is optional. Build/inspect can present engineering-source states without a null-reference failure. |+| Profile Template specialization renamed every matching word, including strings, fields and unrelated members, then scanned braces again to hoist guides. | Use the existing AST rewriter, lexical binding scopes, construction ownership and syntax writer. Preserve the established specialization prefixes and colliding Segment identities. Rewrite references to bound local guides; preserve unrelated external members, field labels and strings. |+| Template Record member validation searched source text, including string contents. | Inspect MemberSyntax and actual nested parameter/mapping shadow boundaries. A string mentioning `spec.ThisIsTextAndNotAField` no longer creates a phantom reference; a real missing member still rejects. |+| Structural/Sculpting/PlasticShell rejected common scalar requirements even though they already shared the value binder. | Admit common Concept declarations and Require checks through FirmamentDomainBinding and its existing Concept evaluator at product scopes. This does not invent scalar properties for domain geometry. |+| Expanded diagnostic anchors omitted field names/values. A failed state also generated an unnecessary unresolved-output error at the Model line. | Extend the existing origin index with field/name/value anchors. Preserve actual diagnostic codes/messages. Suppress an output cascade when the selected declaration has already failed, retaining the primary source-located cause. |+| Some owners silently ignored --parse-only and materialized geometry. | Owners without a static admission path reject the option with `firmament-validation-option-unsupported`, `status: not-validated`, and `validationLevel: NotValidated`. Reuse the existing Structural/Garment static analyzers; Mechanical/Assembly/Scene/SectionChain/WireForm/Sweep static paths remain with their owners. PlasticShell's normal report now also identifies its route and build level. |++The normal compiler retains its admitted document and native producer identity+on the existing in-process export result. The state adopter consumes that+binding evidence instead of running a separate semantic parse after compilation.+These fields do not change normal CLI/SDK JSON.++The engineering base is a versioned `EngineeringSourceConstruction`, alongside+the existing `HousingBaseConstruction`. It retains source, source file and the+selected product name. Replay recompiles that recipe through the same compiler;+the retained STEP is evidence, not the replay authority. External resources are+resolved relative to the retained source file, and are not silently frozen into+the state. Different dependency contents can produce a different state identity.++`ConstructionStateReplayer` now lives beside Firmament authoring in+`Aetheris.Kernel.Firmament`, retaining its namespace and source API. This avoids a+Surfacing-to-frontend dependency cycle. External precompiled .NET consumers must rebuild after the class move or+BodyState constructor change. Replayer consumers reference Kernel.Firmament;+BodyState-only geometry consumers still reference Surfacing. No binary forwarding+or universal binary compatibility is claimed. Construction-state serialization+and geometry algorithms remain in Surfacing.++## Compatibility decisions++Patch/SectionChain-derived state fingerprints intentionally change because the+old preimages could not distinguish different engineering inputs. Authored+semantic names and materialized geometry are preserved. Base housing IDs and+unaffected operation IDs retain their existing construction. Old source recipes+can be replayed to current realized identities; this is not a promise that a+previously colliding fingerprint remains a unique identity.++The previous DOMAIN register remains historical evidence. This table is its+current disposition under the no-new-features constraint; it does not erase the+original findings.++| Item | Current decision |+| --- | --- |+| DOMAIN-01: two SectionChain forms | Retain the compact Station form as compatibility, including its +X frame and G0 default. Both forms already lower to SectionChain IR; do not silently change geometry by imposing the standalone form's frames/defaults. A new unified authoring surface is outside this pass. |+| DOMAIN-02: housing-only BodyState | General engineering-product construction and source replay are repaired. Existing sculpt materializers remain explicit housing capabilities. Bounded replacement still needs the shared semantic-face/PMI adapter described below; broader offset/blend/composition also need kernel work. |+| DOMAIN-03: Drawing policy Concepts | Retain the bounded Drawing policy contract as a distinct documented domain form. Do not claim it is a general predicate evaluator or silently reinterpret its policies. |+| DOMAIN-04: Drawing Template adapter | Preserve its typed Product/Metadata compatibility adapter. General nested product Template semantics remain open; they require owner consolidation, not another source rewrite. |+| DOMAIN-05: structural Table roles | Preserve the existing named row contracts and public IDs. Direct Node/Path/Member authoring remains the ordinary alternative. A new typed role-collection syntax would be a feature and is not introduced. |+| DOMAIN-06: points/units/frames | Preserve explicit owner conventions and physical placement. No recentering, default-unit change or geometry migration. |+| DOMAIN-07: derived dimensions | Preserve existing finite physical literal converters and common dimensional algebra. General derived-dimensional computation is a separate feature. |+| DOMAIN-08: Review values | Preserve bounded proposal comparison and the separation from authoritative PMI. A new typed proposal model is not introduced. |+| DOMAIN-09: expansion provenance | Field/name/value source anchors are repaired. Complete include/expansion source maps remain incomplete; enclosing/generated locations must still disclose that limit. |+| DOMAIN-10: Template text transport | Remove the global Profile rename/hoist scans and Record member regex admission. Existing lowerer string transport remains; this is not a claim of fully AST-native expansion. |+| DOMAIN-11: editor coverage | Keep compiler authority and the existing explicit compile-context notice for expensive domains. No geometry construction on each keystroke and no parallel editor validator. Complete domain completion/formatting metadata remains host integration work. |+| DOMAIN-12: validation levels | Ignored static-only options now reject explicitly; actual owner validation levels remain distinct. No parsed-is-valid claim. |+| DOMAIN-13: requirements | Common compile-time data predicates/contracts now bind in Structural/Sculpting/PlasticShell product scopes. Automatic semantic-value projection of domain entities remains unsupported and must reject, rather than fabricate properties. |++Housing OffsetRegion still expresses the recipe's crown height above its base+plane. It is not a generic displacement operator over an arbitrary successor+surface. This boundary is explicit in the public operation table. The old+housing adapter's datum/tolerance annotations are preserved for compatibility;+ordinary engineering inputs retain their own explicit PMI.++## Evidence and qualification++Source witnesses and transformation-only fragments live under+`fixtures/Regression/BodyStateDebt/`. The fragments are syntax-transform test+inputs, not speculative products counted as successful builds. Existing+Canonical and Claude X4 sources/goldens are not rewritten to manufacture passes.++Run evidence is local and ignored under `artifacts/local/body-state-debt/`.+The initial historical domain gate was 37/37 before implementation.+The broader adoption tests wrap existing canonical products; they do not edit+those fixtures. An early generated wrapper retained `schema Mechanical` while+adding a Sculpting output: that mismatch is correctly rejected, not classified+as a regression. The wrapper now explicitly selects Sculpting, while its+reference still uses the original Mechanical selector. Separate failures for+real native producer names were actual metadata gaps and were repaired in their+owning materializers. The+additional Profile Template baseline is `template-before.step`. The final+qualification results are recorded below.++Projection preserves the original engineering statement text and offsets,+omitting only AST-owned state/output spans. A rich PMI witness exposed that+reserializing the whole body changed literal/call spelling consumed by an older+lowerer. That path was repaired locally; it does not introduce a global rewrite+or pretend the older lowerer is AST-native. The original failing iteration is+retained in `pattern-qualified.log`.++The generic mass evaluator explicitly labels nonanalytic trimmed-face results+as tessellated sanity estimates. An early repeated-hole test incorrectly used+one as an exact small-hole volume oracle. Its failed measurement is retained in+`modules-focused.log`; the repaired test uses exact STEP equality to an+independently ordered source, plus bore topology, semantic inventory and replay.+No kernel volume code or expected geometry was changed to accommodate it.++## Final qualification++Checkout HEAD is `7051f060c4dccfe64ef7974f645285c57abd8c3d` with this pass's+reviewable working-tree changes. Qualification used .NET SDK 10.0.401 on Windows.++| Gate | Result | Local evidence |+| --- | --- | --- |+| Release solution build | 0 errors; 30 existing warnings retained | `release-build.log` |+| Focused state/surfacing/normalization, CLI and Template checks | 92 + 17 + 10 = 119 passed | `modules-qualified.log`, `cli-qualified.log`, `template-qualified.log` |+| Fast kernel lane | 1,076 passed | `fast.log` |+| Full configured solution suite, including SlowCorpus | 5,508 passed, 0 failed, 0 skipped; 20 nonempty assemblies | `full.log`, `test-summary.json` |+| Canonical owner/consumer gate | 296 owner operations + 69 consumed modules + 4 expected external-body boundaries = 369 sources | `canonical/qualification.json`, `canonical.log` |+| Historical frontend gate | 37/37 matched: 35 exact STEP hashes and 2 expected rejections | `after/comparison.json` |+| Recent Structural/Sculpting/BodyState/PlasticShell baseline | 30/30 source texts unchanged; baseline artifact SHA verified against the previous qualified parity record; 28 exact STEP files | `domain-current.json`, `domain-current.log` |+| Two changed STEP files | Intentional mixed-diameter PMI correction; reimport and annotation-free re-export have identical geometry hashes and topology | `geometry-comparison.json` |+| Profile Template control arithmetic | Before/after exact STEP SHA-256 `6dd25297e4d52687998c4546076ea3ee886295fa7cdce152088876a08e5eaad4` | `template-before.step`, `template-after.step` |+| Claude X4 | 32/32 passed, cases/goldens untouched | `x4.log` |+| Sheet profile corpus | 26/26; formed STEP/flat parity true | `sheet-syntax.log` |+| Sheet semantic corpus | 29/29 | `sheet-semantics.log` |+| Final public documentation and assembly documentation contracts | 14/14 passed | `docs-qualified.log` |+| Runtime/storage inventory | No dotnet/testhost/VBCSCompiler/aetheris host remained; this evidence tree 144.3 MiB; C: free 200.3 GiB at sample | Final inventory |++The two PMI changes are `BodyState/surf-x3b-multi-operation-replay` and+`BodyState/surf-x3b-safe-feature-after-add`. The former retains 22 faces / 48 edges /+28 vertices and normalized geometry SHA-256+`bc8fe7b67babdad6d88e0720ce72acc3915d2caf21aa8fc9a8a5614dbe026228`.+The latter retains 17 faces / 37 edges / 22 vertices and normalized geometry hash+`61795e22417d43db384fd54270fe97f711932fc6467871aeac38796a8ee960b9`.+The raw STEP metadata previously assigned diameter 4 to every bore; the corrected+PMI distinguishes the authored diameter groups and quantities, with exact face+associations. Geometry normalization removes annotations only for comparison;+shipping STEP retains the corrected PMI.++The 30-source comparison reuses the previous domain migration's retained+before/after snapshots, not a newly recorded golden. It verifies each baseline+STEP's recorded SHA and compares its saved source text with the unchanged+current source before rebuilding. The paired source-reference and independent+operation-order tests supply portable regression coverage as well.++The solution visits FrictionLab, which currently discovers no tests; it is not+counted as a passing test assembly. These are local compiler/CLI/STEP results,+not remote CI or interactive Helios certification. Frozen Zig was not run:+neither its compiler nor its infrastructure changed.++## Code-quality review and reproduction++Review covered direct statement ownership, closed field consumption, V1 isolation,+name resolution, duplicate semantic IDs, state/history identity, typed replay,+source anchors, warning/error boundaries, product identity, and runtime lifetime.+No new whole-document regex dispatch, diagnostic fatality allowlist, independent+field catalogue, source macro framework, global parser state, service or startup+hook was added. The projection omits only known AST state/output spans; guide+hygiene reuses the existing AST rewriter/binding scopes. Geometry builders are+reused; no kernel operation was added. `git diff --check` passes. Canonical and+Claude X4 fixtures/goldens have no working-tree changes.++Run serially from the repository:++```powershell+dotnet build Aetheris.slnx -c Release -m:1 -nr:false -p:UseSharedCompilation=false+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build --filter "Category!=SlowCorpus"+dotnet test Aetheris.slnx -c Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1+./scripts/Test-CanonicalFixtures.ps1 -NoBuild+./scripts/qualify-firmament-domain-frontend.ps1+python fixtures/Regression/FrontendX4/run.py+python fixtures/Regression/SheetMetalSyntax/run.py+python fixtures/Regression/SheetMetalSemantics/run.py+```++## Remaining blocker and verdict++The next body-state blocker is concrete: `OffsetRegionSculptor`,+`ReplaceRegionSculptor`, `BlendBoundarySculptor`, and+`SectionChainHousingBrepBuilder.BuildAddEast/BuildRemoveThroughX` construct a+whole housing from HousingConstruction. They do not take an arbitrary input+BRep and emit a bounded topology graft with successor correspondence. Passing+a generic body through those builders would replace unrelated engineering+geometry. Capability checks now prevent that path.++A bounded support-surface graft already exists in ImportedFaceRegionReplacer;+it would be inaccurate to say every replacement lacks a kernel algorithm. That+adapter still computes a HousingConstruction successor and housing PMI/interfaces,+while the source-level ReplaceRegion owner resolves housing regions. An+engineering-source state currently retains complete original STEP/PMI and the+available correspondence, but has no common bound semantic-face/PMI projection+for editing and re-exporting an arbitrary successor. Removing only the guard+would discard or mislabel that authority.++The smallest remaining X2 prerequisite is to decouple the existing bounded graft+from housing bookkeeping and supply it with authoritative face selection, PMI+association succession and typed replay through the shared domain-value seam.+This is semantic adapter debt, not new syntax or proof that the existing kernel+is incapable. More general offsets, blends and SectionChain topology would also+need broader kernel materializers; those are outside the no-new-features round.+No fitted housing, new parser route or success flag is used to conceal either+boundary.++**Meaningful progression for the overall semantic closeout.** Construction,+history retention, unsafe text recognition, requirement admission and validation+option debts are repaired and separately qualified above. Full X2 semantic+consolidation and arbitrary-body editing are not declared complete. No further+user syntax decision was required for these repairs.diff --git a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.mdindex a053c326..22761339 100644--- a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md+++ b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md@@ -431,3 +431,22 @@ CORPUS-05 independent-reader qualification above. Unknown intent closes at theactual AST owner; no shadow-only admission path was added. DOMAIN-01 throughDOMAIN-13 preserve the remaining semantic, expansion, units, provenance andmetadata decisions. This does not mark X2 or separate geometry work complete.+++## Body-state and semantic debt follow-up (2026-10-18)++The [body-state debt report](FIRMAMENT-BODY-STATE-DEBT-2026-10-18.md) records+current dispositions for all thirteen DOMAIN items without erasing their+original findings. Engineering-product construction/replay now preserves the+normal compiler's exact output; hole-free housings work; repeated holes retain+an attachment; unsupported reconstruction histories reject atomically. Mixed+hole-diameter PMI is corrected. Profile guide hygiene and Record member checks+use AST ownership instead of whole-word source matching. Shared compile-time+Concept/Require checks are admitted at Structural/Sculpting/PlasticShell product+scopes, and owners no longer silently ignore static-only validation requests.++This is not general BRep operation grafting, derived-dimensional algebra,+a new structural collection language or complete expansion source maps. Those+remain explicit capability/consolidation boundaries under the no-new-features+constraint. See the report for qualification, compatibility changes and the+concrete remaining housing-materializer coupling.diff --git a/docs/public/firmament/sculpting.md b/docs/public/firmament/sculpting.mdindex e0602a3e..2249f6fc 100644--- a/docs/public/firmament/sculpting.md+++ b/docs/public/firmament/sculpting.md@@ -4,9 +4,10 @@ Authoring uses the shared AST and compile-time value binder, with camelCasefields and historical PascalCase aliases. A single Model owns its states,SurfacePatch and compact SectionChain declarations and selects one `output`.Unknown statements/fields, duplicate singleton operations and unsupported header-placements reject. `schema Sculpting` is optional. The current `BodyState`-constructor remains the bounded housing witness with explicit holes; it is not-a general arbitrary-body constructor. Its compact Station-based SectionChain+placements reject. `schema Sculpting` is optional. `BodyState { input: body }`+retains an admitted engineering product through its normal compiler. The legacy+`size`/`Hole` constructor describes the rectangular housing, with optional holes.+Its compact Station-based SectionChainform remains distinct from the framed Profile-based SectionChain frontend.SURF-X0 supports bounded mathematical sculpting and locality-preserving region modification. SURF-X1 adds direct rectangular patch replacement. SURF-X1a closes the trim path for the admitted housing: qualified surface intersections derive the outer boundary, face-local pcurves qualify every trim, circular inner loops preserve openings, and an imported `ADVANCED_FACE` can receive a bounded support-surface graft. SURF-X2 adds a qualified two-support crown-to-planar-shoulder `BlendBoundary` that generates and deterministically judges exact non-rational polynomial candidates. This is not full general surfacing.@@ -24,9 +25,51 @@ Base -> CrownHighBoth variants can share `Base`; neither mutates it or the other. State IDs are deterministic hashes of the predecessor and canonical operation contract. Ordinary authoring always references the current predecessor, not topology from an arbitrary historical state.-`BodyState` is reconstructed from a versioned typed `ConstructionState`. Its authority is a `BaseConstruction` plus an ordered list of semantic operations such as `OffsetRegion`, `ReplaceRegion`, `BlendBoundary`, `HoleFeature`, `AddSectionChain`, and `RemoveSectionChain`. Each retained operation records stable identity, payload version, authored inputs, predecessor/output relationship, reads, `MayModify`, authorized envelope, preservation contracts, `GeometricDelta`, and validation evidence. The BRep and effective housing recipe are realized evidence, not design-history authority.--Rebuild means realizing the base and replaying operations in order. Each operation validates against its newly realized predecessor. If operation N fails, no State N is returned and State N-1 remains authoritative with `bodystate-operation-replay-failed` evidence. Serialization uses the explicit `aetheris.surfacing.construction-state` schema; opaque delegates and generic Boolean history are not admitted.+`BodyState` is reconstructed from a versioned typed `ConstructionState`. Its authority is a `BaseConstruction` plus an ordered list of semantic operations such as `OffsetRegion`, `ReplaceRegion`, `BlendBoundary`, `HoleFeature`, `AddSectionChain`, and `RemoveSectionChain`. A base is either the established `Housing` recipe or an `EngineeringSource` recipe retaining the engineering source, source file and selected body. Each retained operation records stable identity, payload version, authored inputs, predecessor/output relationship, reads, `MayModify`, authorized envelope, preservation contracts, `GeometricDelta`, and validation evidence. The BRep, retained STEP and effective housing recipe are realized evidence, not design-history authority.++Rebuild means realizing the base and replaying operations in order. Each operation validates against its newly realized predecessor. If operation N fails, no State N is returned and State N-1 remains authoritative with `bodystate-operation-replay-failed` evidence. Serialization uses the explicit `aetheris.surfacing.construction-state` schema; typed BSpline patch data round-trips along with housing, source and SectionChain recipes. Opaque delegates and generic Boolean history are not admitted. Patch fingerprints include the effective support/control net; SectionChain fingerprints include frames, knots, seam and correspondence, so equal names and control counts do not imply equal states.++### Construction and operation boundaries++The [engineering-body example](syntax.md#bodystate-retain-an-engineering-body)+preserves the original STEP, including authored PMI. It assigns no synthetic+housing crown, hole pattern or mounting interface to an arbitrary body.+The retained engineering STEP keeps its authored Model/product name. The export+API rejects a conflicting product-name override; rename the source Model and+rebuild when a different product identity is intended.+Replay runs the same engineering compiler and resolves resources relative to+the retained source file. Replaying after an external dependency changes can+produce a different state identity; the source recipe is not a frozen copy of+every referenced file.++The `size` constructor admits a hole-free housing. Such a state has no+`MountingHolePattern` entity or hole PMI. The established housing adapter retains+its historical datum/tolerance annotations for compatibility. Mixed hole+diameters now emit separate diameter quantities and face sets, rather than+incorrectly assigning the first diameter to every hole. Prefer explicit PMI in+ordinary engineering source for production annotation policy.++| Operation | Current admitted construction |+| --- | --- |+| OffsetRegion | Rectangular HousingCrown; not a replacement patch or arbitrary named face. Offset remains the housing recipe's crown height above its base plane. |+| ReplaceRegion / BlendBoundary | Qualified housing crown/patch replacement and documented planar-shoulder supports. |+| HoleFeature | Housing top/footprint frame; retains an existing east-attached SectionChain across repeated holes. |+| AddSectionChain / RemoveSectionChain | One qualified housing attachment or through-duct construction. |++These materializers do not yet graft arbitrary operations onto arbitrary BReps.+They reject engineering-source bodies with+`bodystate-operation-capability-unsupported`. A reconstruction that cannot+retain an earlier SectionChain rejects with+`bodystate-history-capability-unsupported`; the predecessor remains authoritative.+No operation may silently remove an earlier attachment or duct.++The direct C# imported-face adapter retains imported topology/provenance and+supports its bounded support-surface graft. It does not carry a replayable+source recipe and exposes no `ConstructionAuthority`; whole-housing edits on+that state reject before discarding imported provenance. Its retained-body and+graft identities include actual geometry. This is distinct from a BodyState+created from an admitted engineering-source import, whose source recipe can be+replayed by the engineering compiler.## X0 authoringdiff --git a/docs/public/firmament/structural.md b/docs/public/firmament/structural.mdindex 5f2d37be..791f4273 100644--- a/docs/public/firmament/structural.md+++ b/docs/public/firmament/structural.md@@ -57,7 +57,7 @@ Member Horizontal {### Columnar graph tables-For frames with many edges, use the existing first-class `Record` + `Static Table` mechanism instead of repeating blocks. Structural table rows normalize to exactly the same Member AIR:+For frames with many edges, use the existing first-class `Record` + `Static Table` mechanism instead of repeating blocks. Structural table rows normalize to exactly the same Member AIR. The established Record names `StructuralMemberRow`, `StructuralJointRow` and `StructuralWeldRow` select these compatibility adapters; arbitrary Record names do not acquire structural roles by having similar fields:```firmamentRecord StructuralMemberRow { Name: String Path: String Section: String Material: String Orientation: String }@@ -70,7 +70,7 @@ Static Table Members: StructuralMemberRow Key: Name {}```-`StructuralJointRow` columns are `Name`, `Type`, `FirstMember`, `FirstEnd`, `SecondMember`, `SecondEnd`, and `Primary`. End values are `Start` or `End`; `Type` is `Butt` or `Miter`. `Primary` names the through member for a butt joint. The column is still required for a miter row because Static Tables have one fixed schema, but its value is ignored. `StructuralWeldRow` columns are `Name`, `Joint`, `Type`, and `Size`; X2 weld type is `Fillet`.+`StructuralJointRow` columns are `Name`, `Type`, `FirstMember`, `FirstEnd`, `SecondMember`, `SecondEnd`, and `Primary`. End values are `Start` or `End`; `Type` is `Butt` or `Miter`. `Primary` names the through member for a butt joint. The column is still required for a miter row because Static Tables have one fixed schema. It is retained in the joint metadata; miter geometry is symmetric in the two member ends and does not use Primary as a geometric driver. `StructuralWeldRow` columns are `Name`, `Joint`, `Type`, and `Size`; X2 weld type is `Fillet`.```firmamentRecord StructuralJointRow { Name: String Type: String FirstMember: String FirstEnd: String SecondMember: String SecondEnd: String Primary: String }diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex 150d4ba0..be128f25 100644--- a/docs/public/firmament/syntax.md+++ b/docs/public/firmament/syntax.md@@ -44,7 +44,10 @@ aetheris build plate.firmament --output artifacts/local/plate.step```Normal mechanical validation performs engineering compilation in memory.-`--parse-only` reports `ParsedNotBuilt`; it does not prove the part can be built.+Where a static admission path exists, `--parse-only` reports `ParsedNotBuilt`;+it does not prove the part can be built. Domains without that path reject the+option as `NotValidated`, with an explanation. They do not silently execute a+full build for a static-only request.`--explain` adds developer information about admission and the chosen frontend.See [diagnostics](../reference/diagnostics.md) for interpreting failures.@@ -926,8 +929,43 @@ Do not invent `schema Assembly` or wrap arbitrary domain declarations in a Model| Sheet manufacturing, regions and bends | [Sheet metal](sheet-metal.md). || Structural / piping domains | [Structural](structural.md), [piping](piping.md). || Engineering annotations | [PMI](pmi.md). |+| Immutable body construction and bounded surface edits | [Body states and sculpting](sculpting.md). || File-backed modules and source-only projects | [Project snapshots](project-snapshots.md), [Concept derivation](concept-derivation.md). |+### BodyState: retain an engineering body++`BodyState` can reference the Model's admitted engineering body. It does not+convert that geometry into the old rectangular housing prototype.++**Complete file:**++```firmament+Model Sleeve {+ units: mm+ Cylinder stock { radius: 6mm height: 17mm }+ BodyState base { input: stock }+ output: base+}+```++The ordinary engineering compiler admits `stock`, including its modifications+and explicit PMI. The state retains that exact product, semantic correspondence+where available, and its source recipe for replay. `input` must name an admitted+body or final Compose; it cannot select an unrelated Record, Profile guide or+an intermediate stage of the same construction. Use separate Parts for separate+products, as in ordinary mechanical authoring. Primitive, profile/Compose,+Gear, Sweep and Revolve products retain their existing engineering lowerers.+When adding a state output to a file with an explicit `schema Mechanical`,+select `schema Sculpting` for the state-owning document; an explicit conflicting+selector is still an error.++The older `BodyState base { size: [...] Hole ... }` form remains a housing+construction. Holes are optional. Its named crown and mounting regions belong+to that construction; they are not inferred on arbitrary engineering bodies.+The existing surface-edit materializers still have explicit topology/support+requirements. An unsupported edit or history combination rejects before it can+replace earlier geometry. See the [operation boundaries](sculpting.md).+### Inventory: organize module dependenciesUse a short `include "parts/bolt";` when shared declarations are convenient. For@@ -1116,6 +1154,13 @@ statement/field scopes. Unknown fields, duplicate aliases, unknown statementsand unsupported header placements reject; shared parsing does not make everyoperation legal in every domain.+Structural, Sculpting and PlasticShell accept common predicate/structural+`Concept` declarations and `Require` checks over shared compile-time data at+their product scopes. A requirement must resolve through that binder; domain+geometry is not implicitly converted into arbitrary scalar properties.+Profile Template specialization now renames bound local guides through the AST;+field labels, string contents and unrelated external members retain their spelling.+Use `pmi` and `bom` for acronym fields. Historical `PMI`/`BOM` and the oldfirst-letter-only `pMI`/`bOM` aliases remain admitted by the common field reader.Record member names remain authored, case-sensitive data; do not blindly changediff --git a/docs/public/reference/cli.md b/docs/public/reference/cli.mdindex f9172c15..264ab499 100644--- a/docs/public/reference/cli.md+++ b/docs/public/reference/cli.md@@ -21,7 +21,7 @@ Primary public commands:| `wireframe <model.step> [--out preview.svg] [--view iso\|front\|top\|right] [--density N] [--json]` | Render deterministic exact-edge and trim-clipped surface-isoline SVG evidence || `asm ...` | Inspect/execute/import/export assemblies |-Generic mechanical `validate` now runs the existing engineering compilation in memory, including selection binding, capability checks and geometry/STEP preflight. It writes no output file. Its report includes `validationLevel` (`Built`, `BuildRejected`, or `ParsedNotBuilt`) and developer-only `parserRoute` metadata. `--explain` prints the route, admission level and available instance counts. `--parse-only` explicitly requests static analysis and reports `parsed-not-built` on success. External `--forge-pack` validation is also labelled `parsed-not-built`: those descriptor providers are not installed into normal build. Domain-specific validators retain their separate scope; inspect their reports. This is not a promise that unchanged source can never encounter a later environment or kernel failure.+Generic mechanical `validate` now runs the existing engineering compilation in memory, including selection binding, capability checks and geometry/STEP preflight. It writes no output file. Its report includes `validationLevel` (`Built`, `BuildRejected`, or `ParsedNotBuilt`) and developer-only `parserRoute` metadata. `--explain` prints the route, admission level and available instance counts. `--parse-only` explicitly requests static analysis and reports `parsed-not-built` on success. Drawing, Analysis, PlasticShell, Sculpting, Plateau and Piping currently lack that separate static admission path: they reject this option with `firmament-validation-option-unsupported` and `NotValidated`, rather than silently materializing geometry. Structural and Garment reuse their existing static analyzers. External `--forge-pack` validation is also labelled `parsed-not-built`: those descriptor providers are not installed into normal build. Domain-specific validators retain their separate scope; inspect their reports. This is not a promise that unchanged source can never encounter a later environment or kernel failure.Mechanical Model and material-bearing Struct documents now use the unified lexer/AST admission path (`UnifiedMechanical`). The ignored Compose Fillet, erased Rect2 field and unused Slot2 route-perturbation cases are repaired. Profile/Compose build execution consumes admitted engineering inputs. Other dedicated domains retain their existing owners; see the [production migration qualification](../../release/FIRMAMENT-MECHANICAL-FRONTEND-MIGRATION.md) for its scope and evidence.diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.mdindex eb79c9f8..50849941 100644--- a/docs/public/reference/supported-features.md+++ b/docs/public/reference/supported-features.md@@ -9,7 +9,7 @@| Gear Standard Library | Supported / bounded by family | Supported external/internal standard involute spur gears; bounded straight bevel/miter and ratchet/pawl; typed `Interface<Gear>` compatibility and ideal ratios; deterministic manifold AP242. No contact, dynamics, ratings, helical/worm, spiral-bevel, or qualified hub/keyway geometry. See the [gear guide](../firmament/gears.md). || Assembly Interface bundles and Subassemblies | Supported / bounded | Compiler-owned `Fixed`, `Axial`, and `Revolute` expansion; explicit `Custom` atomic bundles; compile-time relative `Include`; reusable nested definitions; private-by-default internals; exposed semantic ports that preserve type, including Gear; stable hierarchical paths and dependency hashes. Include aliases are deferred. See [assemblies](../firmament/assemblies.md). || Scene spatial composition | Supported / bounded | Metre/mm coordinates; rectangular Room boundaries; Door/Window apertures; independent AssemblyFile and typed Part occurrences; keyed patterns; retained definition reuse; cameras and appearances; USD/GLB. No Scene mechanical relationships, nested Scenes, whole-scene STEP or BIM. See [scenes](../firmament/scenes.md). |-| Bounded mathematical sculpting | Bounded (SURF-X3b subset) | Immutable single-predecessor `BodyState` reconstructed from versioned `BaseConstruction` plus typed replay operations; persistent `OffsetRegion`, `ReplaceRegion`, judged `BlendBoundary`, `HoleFeature`, east-attached `AddSectionChain`, and west/east through-duct `RemoveSectionChain`; atomic replay, semantic support invalidation, locality/preservation evidence, pcurves, AP242 associations, and rational-free STEP. General blend networks and arbitrary SectionChain supports remain unsupported. See the [sculpting guide](../firmament/sculpting.md). |+| Bounded mathematical sculpting | Bounded (SURF-X3b subset) | Immutable single-predecessor `BodyState` reconstructed from an admitted engineering-source or housing `BaseConstruction` plus typed replay operations; engineering bodies retain their exact product while the existing edit materializers require the documented housing supports; persistent `OffsetRegion`, `ReplaceRegion`, judged `BlendBoundary`, `HoleFeature`, east-attached `AddSectionChain`, and west/east through-duct `RemoveSectionChain`; atomic replay, semantic support invalidation, locality/preservation evidence, pcurves, AP242 associations, and rational-free STEP. General blend networks and arbitrary SectionChain supports remain unsupported. See the [sculpting guide](../firmament/sculpting.md). || Molded plastic shell | Bounded (MOLD-X0a) | First-class `PlasticShell` IR; exact drafted coaxial-frustum shell; analytic annular standoffs with retained core holes; constant-shell-thickness planar B-rep rib walls with flat tops; one closed product boundary; face-associated AP242 notes; and explicit zero-release-draft warning for constant-section vertical features. The retired polar height field is available only through the non-manufacturing experimental art command. Freeform exterior offsets and general junctions remain unsupported. See the [PlasticShell guide](../firmament/plastic-shell.md). || Virtual Sculpture | Bounded (ART-X0) | The explicit `Mode: Virtual` Sol 1 flagship: deterministic golden-angle/Fibonacci 3D lattice, analytic toroidal frame and eye, exact closed-body AP242 assembly, evidence/preview output, and zero rational product surfaces. This is not manufacturing geometry and does not extend Firmament engineering domains. See [Virtual Sculpture](../virtual-sculpture.md). || Firmament V2 analytic primitives | Bounded | Direct named Sphere, Cone (including zero-radius pointed end), and Torus routes round-trip through AP242; legacy `solid` declarations remain compatibility inputs, not canonical authoring |diff --git a/fixtures/Regression/BodyStateDebt/README.md b/fixtures/Regression/BodyStateDebt/README.mdnew file mode 100644index 00000000..0de946ab--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/README.md@@ -0,0 +1,25 @@+# Body-state and semantic-debt witnesses++These sources are exercised by BodyStateDebtTests, BodyStateDebtCliTests and+ProfileTemplateProjectionTests. They are not all standalone valid products.++| Specimen | Expected result / evidence |+| --- | --- |+| box, cylinder, profile, counterbore-chamfer | Accepted engineering-source BodyState; exact STEP equality to the corresponding `.reference` product and serialized source replay. |+| explicit-pmi | Accepted Record/Pattern/Compose/counterbore/chamfer product with explicit PMI; original STEP and semantic product survive construction/replay unchanged. |+| plain-offset | Accepted hole-free housing and crown edit; no fabricated hole entity or hole PMI; replay agrees. |+| second-hole-after-add | Accepted attachment followed by two holes; compare exact STEP to the reference with all bores constructed before attachment. Both earlier geometry and feature identities must survive. |+| unsupported-cylinder-edit | Rejected operation capability; the source cylinder must never become a housing. |+| history-drop | Rejected history capability; a later housing rebuild must never discard the earlier attachment. |+| unknown-field | Rejected unknown `heigth` field at its authored field location, without an unrelated Model/output cascade. |+| record-member-string | Accepted typed Template product. A string containing `spec.ThisIsTextAndNotAField` is text, not a missing Record member. A test mutation to a real missing member must reject. |+| requirements.fragment | Prefix for existing Structural/Sculpting/PlasticShell products; the true predicate preserves exact STEP, and its false mutation rejects validate/build. |+| profile-hygiene.fragment | Syntax-transformation-only specimen. Checks local-guide/member/segment identity and preservation of strings/field labels/external members. Not counted as a materializing product. |++The tests also wrap unchanged canonical cone, sphere, torus, rounded-box, Gear,+Sweep and Revolve products using the correct state-owner selector. Typed-value+checks distinguish frame/knot changes and actual replacement control-net changes;+replacement construction is serialized, restored and replayed to the same STEP.++The full regression suite and canonical qualification remain separate gates.+Run output belongs under ignored `artifacts/local/`, never beside these files.diff --git a/fixtures/Regression/BodyStateDebt/box.firmament b/fixtures/Regression/BodyStateDebt/box.firmamentnew file mode 100644index 00000000..20443318--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/box.firmament@@ -0,0 +1,6 @@+Model State_box {+ units: mm+ Box Stock { size: [30mm, 20mm, 10mm] }+ BodyState Base { input: Stock }+ output: Base+}diff --git a/fixtures/Regression/BodyStateDebt/box.reference.firmament b/fixtures/Regression/BodyStateDebt/box.reference.firmamentnew file mode 100644index 00000000..a825fad0--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/box.reference.firmament@@ -0,0 +1,4 @@+Model State_box {+ units: mm+ Box Stock { size: [30mm, 20mm, 10mm] }+}diff --git a/fixtures/Regression/BodyStateDebt/counterbore-chamfer.firmament b/fixtures/Regression/BodyStateDebt/counterbore-chamfer.firmamentnew file mode 100644index 00000000..a84021ca--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/counterbore-chamfer.firmament@@ -0,0 +1,10 @@+Model State_counterbore_chamfer {+ units: mm+ Box Stock { size: [10mm, 15mm, 20mm] }+ Modify Stock {+ Hole<Counterbore> Mount { on: +Z center: Point2(0mm, 0mm) diameter: 4mm counterboreDiameter: 7mm counterboreDepth: 3mm end: ThroughAll }+ EdgeFinish TopBreak { face: +Z target: Boundary kind: Chamfer distance: 1mm }+ }+ BodyState Base { input: Stock }+ output: Base+}diff --git a/fixtures/Regression/BodyStateDebt/counterbore-chamfer.reference.firmament b/fixtures/Regression/BodyStateDebt/counterbore-chamfer.reference.firmamentnew file mode 100644index 00000000..e9a295b7--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/counterbore-chamfer.reference.firmament@@ -0,0 +1,8 @@+Model State_counterbore_chamfer {+ units: mm+ Box Stock { size: [10mm, 15mm, 20mm] }+ Modify Stock {+ Hole<Counterbore> Mount { on: +Z center: Point2(0mm, 0mm) diameter: 4mm counterboreDiameter: 7mm counterboreDepth: 3mm end: ThroughAll }+ EdgeFinish TopBreak { face: +Z target: Boundary kind: Chamfer distance: 1mm }+ }+}diff --git a/fixtures/Regression/BodyStateDebt/cylinder.firmament b/fixtures/Regression/BodyStateDebt/cylinder.firmamentnew file mode 100644index 00000000..0d5efb97--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/cylinder.firmament@@ -0,0 +1,6 @@+Model State_cylinder {+ units: mm+ Cylinder Stock { radius: 6mm height: 17mm }+ BodyState Base { input: Stock }+ output: Base+}diff --git a/fixtures/Regression/BodyStateDebt/cylinder.reference.firmament b/fixtures/Regression/BodyStateDebt/cylinder.reference.firmamentnew file mode 100644index 00000000..4f6217a8--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/cylinder.reference.firmament@@ -0,0 +1,4 @@+Model State_cylinder {+ units: mm+ Cylinder Stock { radius: 6mm height: 17mm }+}diff --git a/fixtures/Regression/BodyStateDebt/explicit-pmi.firmament b/fixtures/Regression/BodyStateDebt/explicit-pmi.firmamentnew file mode 100644index 00000000..f3dc39c0--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/explicit-pmi.firmament@@ -0,0 +1,68 @@+Model ProfileComposeLBracketCounterborePmi {+ units: mm++ Record MountSpec { Center: Point2 Diameter: Length }+ Static Mounts: MountSpec[] = [+ MountSpec { Center: Point2(20mm, -10mm) Diameter: 6mm }+ MountSpec { Center: Point2(-30mm, 20mm) Diameter: 6mm }+ ]+ Template<spec: MountSpec> ShaftHole {+ Hole<Shaft> Mount {+ on: +Z+ center: spec.Center+ diameter: spec.Diameter+ end: ThroughAll+ }+ }++ Concept Struct Layout on XY {+ Rect2 Horizontal { center: [0mm, -10mm]; size: [80mm, 20mm] }+ Rect2 Vertical { center: [-30mm, 10mm]; size: [20mm, 60mm] }+ Point2 Notch { position: [-20mm, 0mm] }+ }++ Profile Bracket using Layout { Loop Outer {+ Horizontal.Bottom as South+ |> Horizontal.Right as East+ |> Horizontal.Top to Notch as Inner+ |> Vertical.Right to Vertical.TopRight as Upright+ |> Vertical.Top as North+ |> Vertical.Left to Horizontal.BottomLeft as West+ |> Close+ } }++ Struct BracketBody {+ Compose BracketBody {+ Base Stock { profile: Bracket; from: 0mm; to: 12mm; role: Stock }+ Pattern MountPattern over Mounts { ShaftHole<Current> }+ Hole<Counterbore> CounterboredMount {+ on: +Z+ center: Point2(-30mm, -10mm)+ diameter: 8mm+ counterboreDiameter: 14mm+ counterboreDepth: 4mm+ end: ThroughAll+ }+ }+ }++ Modify BracketBody {+ EdgeFinish TopPerimeter {+ Target: Bracket.Outer+ On: Top+ Kind: Chamfer+ Distance: 1mm+ }+ }++ Pmi {+ Datum A { Target: face(+Z) }+ HoleDiameter CounterboredMountDiameter {+ Target: CounterboredMount+ Value: 8mm+ Tolerance: PlusMinus(0.05mm, 0.02mm)+ }+ }+ BodyState State { input: BracketBody }+ output: State+}diff --git a/fixtures/Regression/BodyStateDebt/explicit-pmi.reference.firmament b/fixtures/Regression/BodyStateDebt/explicit-pmi.reference.firmamentnew file mode 100644index 00000000..cc768fe5--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/explicit-pmi.reference.firmament@@ -0,0 +1,66 @@+Model ProfileComposeLBracketCounterborePmi {+ units: mm++ Record MountSpec { Center: Point2 Diameter: Length }+ Static Mounts: MountSpec[] = [+ MountSpec { Center: Point2(20mm, -10mm) Diameter: 6mm }+ MountSpec { Center: Point2(-30mm, 20mm) Diameter: 6mm }+ ]+ Template<spec: MountSpec> ShaftHole {+ Hole<Shaft> Mount {+ on: +Z+ center: spec.Center+ diameter: spec.Diameter+ end: ThroughAll+ }+ }++ Concept Struct Layout on XY {+ Rect2 Horizontal { center: [0mm, -10mm]; size: [80mm, 20mm] }+ Rect2 Vertical { center: [-30mm, 10mm]; size: [20mm, 60mm] }+ Point2 Notch { position: [-20mm, 0mm] }+ }++ Profile Bracket using Layout { Loop Outer {+ Horizontal.Bottom as South+ |> Horizontal.Right as East+ |> Horizontal.Top to Notch as Inner+ |> Vertical.Right to Vertical.TopRight as Upright+ |> Vertical.Top as North+ |> Vertical.Left to Horizontal.BottomLeft as West+ |> Close+ } }++ Struct BracketBody {+ Compose BracketBody {+ Base Stock { profile: Bracket; from: 0mm; to: 12mm; role: Stock }+ Pattern MountPattern over Mounts { ShaftHole<Current> }+ Hole<Counterbore> CounterboredMount {+ on: +Z+ center: Point2(-30mm, -10mm)+ diameter: 8mm+ counterboreDiameter: 14mm+ counterboreDepth: 4mm+ end: ThroughAll+ }+ }+ }++ Modify BracketBody {+ EdgeFinish TopPerimeter {+ Target: Bracket.Outer+ On: Top+ Kind: Chamfer+ Distance: 1mm+ }+ }++ Pmi {+ Datum A { Target: face(+Z) }+ HoleDiameter CounterboredMountDiameter {+ Target: CounterboredMount+ Value: 8mm+ Tolerance: PlusMinus(0.05mm, 0.02mm)+ }+ }+}diff --git a/fixtures/Regression/BodyStateDebt/history-drop.firmament b/fixtures/Regression/BodyStateDebt/history-drop.firmamentnew file mode 100644index 00000000..092028e2--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/history-drop.firmament@@ -0,0 +1,47 @@+Model SurfX3bSafeFeatureAfterAdd {+ units: mm+ SectionChain GripChain {+ StartTermination: Open+ EndTermination: Cap+ Station Attach { Origin: [0mm, 0mm, 10mm]+ Size: [40mm, 20mm] }+ Station Neck { Origin: [15mm, 0mm, 10mm]+ Size: [30mm, 17mm] }+ Station Tail { Origin: [40mm, 0mm, 10mm]+ Size: [12mm, 8mm] }+ }+ BodyState Base {+ Size: [80mm, 40mm, 20mm]+ Hole MountA { center: [-25mm, -12mm]+ diameter: 4mm }+ Hole MountB { center: [25mm, 12mm]+ diameter: 4mm }+ }+ SculptState GripAdded {+ Input: Base+ AddSectionChain Grip { Chain: GripChain+ Support: HousingSideEast+ Terminal: Attach+ InfluenceEnvelope: [40mm, -20mm, 0mm, 80mm, 20mm, 20mm] }+ MayModify: [HousingSideEast]+ Preserve: [BottomMountingInterface, MountingHolePattern]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ SculptState PortAdded {+ Input: GripAdded+ HoleFeature Port { Target: HousingCrown+ Id: ServicePort+ Center: [0mm, 10mm]+ Diameter: 3mm+ InfluenceEnvelope: [-1.5mm, 8.5mm, 0mm, 1.5mm, 11.5mm, 20mm] }+ Preserve: [OuterFootprintBoundary, GripChain.AttachedSurface]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ SculptState Bad {+ input: PortAdded+ OffsetRegion { target: HousingCrown offset: 4mm region: [30mm, 20mm]+ influenceEnvelope: [-40mm, -20mm, 20mm, 40mm, 20mm, 24mm] boundary: G0 }+ mayModify: [HousingCrown, CrownTransitionZone]+ }+ output: Bad+}diff --git a/fixtures/Regression/BodyStateDebt/plain-offset.firmament b/fixtures/Regression/BodyStateDebt/plain-offset.firmamentnew file mode 100644index 00000000..c92170f4--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/plain-offset.firmament@@ -0,0 +1,13 @@+Model PlainOffset {+ units: mm+ BodyState Base { size: [30mm, 20mm, 10mm] }+ SculptState Raised {+ input: Base+ OffsetRegion { target: HousingCrown offset: 4mm region: [14mm, 12mm]+ influenceEnvelope: [-15mm, -10mm, 10mm, 15mm, 10mm, 14mm] boundary: G0 }+ mayModify: [HousingCrown, CrownTransitionZone]+ preserve: [BottomMountingInterface, OuterFootprintBoundary]+ require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ output: Raised+}diff --git a/fixtures/Regression/BodyStateDebt/profile-hygiene.fragment.firmament b/fixtures/Regression/BodyStateDebt/profile-hygiene.fragment.firmamentnew file mode 100644index 00000000..9130fc0e--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/profile-hygiene.fragment.firmament@@ -0,0 +1,10 @@+// Syntax transformation specimen, not a materializing product.+Point2 A { position: [0mm, 0mm] }+Concept Struct Local {+ Point2 A { position: [1mm, 0mm] }+}+Loop Outer {+ Segment A { trace: A from: Local.A to: External.A }+}+Static Label: String = "A Local.A External.A"+Static Labels = { A: "A" }diff --git a/fixtures/Regression/BodyStateDebt/profile.firmament b/fixtures/Regression/BodyStateDebt/profile.firmamentnew file mode 100644index 00000000..6cb3361a--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/profile.firmament@@ -0,0 +1,10 @@+Model State_profile {+ units: mm+ Concept Struct Layout on XY { Rect2 Base { center: [0mm, 0mm] size: [40mm, 20mm] role: ProfileGuide } }+ Profile Outline using Layout {+ Loop Outer { Base.Bottom as South |> Base.Right as East |> Base.Top as North |> Base.Left as West |> Close }+ }+ Struct Plate { Extrude Outline { profile: Outline; from: 0mm; to: 5mm } }+ BodyState Base { input: Plate }+ output: Base+}diff --git a/fixtures/Regression/BodyStateDebt/profile.reference.firmament b/fixtures/Regression/BodyStateDebt/profile.reference.firmamentnew file mode 100644index 00000000..23f1df2b--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/profile.reference.firmament@@ -0,0 +1,8 @@+Model State_profile {+ units: mm+ Concept Struct Layout on XY { Rect2 Base { center: [0mm, 0mm] size: [40mm, 20mm] role: ProfileGuide } }+ Profile Outline using Layout {+ Loop Outer { Base.Bottom as South |> Base.Right as East |> Base.Top as North |> Base.Left as West |> Close }+ }+ Struct Plate { Extrude Outline { profile: Outline; from: 0mm; to: 5mm } }+}diff --git a/fixtures/Regression/BodyStateDebt/record-member-string.firmament b/fixtures/Regression/BodyStateDebt/record-member-string.firmamentnew file mode 100644index 00000000..22168d9e--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/record-member-string.firmament@@ -0,0 +1,8 @@+Record SizeSpec { width: Length }+Static size: SizeSpec = SizeSpec { width: 40mm }+Template<spec: SizeSpec> Model Product {+ units: mm+ Static documentation: String = "spec.ThisIsTextAndNotAField"+ Box Stock { size: [spec.width, 20mm, 5mm] }+}+Model Example = Product<spec: size>diff --git a/fixtures/Regression/BodyStateDebt/requirements.fragment.firmament b/fixtures/Regression/BodyStateDebt/requirements.fragment.firmamentnew file mode 100644index 00000000..90fd3f7a--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/requirements.fragment.firmament@@ -0,0 +1,2 @@+Concept Positive(value: Length) => value > 0mm+Require admitted => Positive(1mm)diff --git a/fixtures/Regression/BodyStateDebt/second-hole-after-add.firmament b/fixtures/Regression/BodyStateDebt/second-hole-after-add.firmamentnew file mode 100644index 00000000..f314f30a--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/second-hole-after-add.firmament@@ -0,0 +1,48 @@+Model SurfX3bSafeFeatureAfterAdd {+ units: mm+ SectionChain GripChain {+ StartTermination: Open+ EndTermination: Cap+ Station Attach { Origin: [0mm, 0mm, 10mm]+ Size: [40mm, 20mm] }+ Station Neck { Origin: [15mm, 0mm, 10mm]+ Size: [30mm, 17mm] }+ Station Tail { Origin: [40mm, 0mm, 10mm]+ Size: [12mm, 8mm] }+ }+ BodyState Base {+ Size: [80mm, 40mm, 20mm]+ Hole MountA { center: [-25mm, -12mm]+ diameter: 4mm }+ Hole MountB { center: [25mm, 12mm]+ diameter: 4mm }+ }+ SculptState GripAdded {+ Input: Base+ AddSectionChain Grip { Chain: GripChain+ Support: HousingSideEast+ Terminal: Attach+ InfluenceEnvelope: [40mm, -20mm, 0mm, 80mm, 20mm, 20mm] }+ MayModify: [HousingSideEast]+ Preserve: [BottomMountingInterface, MountingHolePattern]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ SculptState PortAdded {+ Input: GripAdded+ HoleFeature Port { Target: HousingCrown+ Id: ServicePort+ Center: [0mm, 10mm]+ Diameter: 3mm+ InfluenceEnvelope: [-1.5mm, 8.5mm, 0mm, 1.5mm, 11.5mm, 20mm] }+ Preserve: [OuterFootprintBoundary, GripChain.AttachedSurface]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ SculptState SecondPortAdded {+ input: PortAdded+ HoleFeature Second { target: HousingCrown id: SecondPort center: [0mm, -10mm] diameter: 3mm+ influenceEnvelope: [-1.5mm, -11.5mm, 0mm, 1.5mm, -8.5mm, 20mm] }+ preserve: [OuterFootprintBoundary, GripChain.AttachedSurface, ServicePort, MountA, MountB]+ require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ output: SecondPortAdded+}diff --git a/fixtures/Regression/BodyStateDebt/second-hole-after-add.reference.firmament b/fixtures/Regression/BodyStateDebt/second-hole-after-add.reference.firmamentnew file mode 100644index 00000000..d11c5f45--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/second-hole-after-add.reference.firmament@@ -0,0 +1,33 @@+Model SurfX3bSafeFeatureAfterAdd {+ units: mm+ SectionChain GripChain {+ StartTermination: Open+ EndTermination: Cap+ Station Attach { Origin: [0mm, 0mm, 10mm]+ Size: [40mm, 20mm] }+ Station Neck { Origin: [15mm, 0mm, 10mm]+ Size: [30mm, 17mm] }+ Station Tail { Origin: [40mm, 0mm, 10mm]+ Size: [12mm, 8mm] }+ }+ BodyState Base {+ Size: [80mm, 40mm, 20mm]+ Hole MountA { center: [-25mm, -12mm]+ diameter: 4mm }+ Hole MountB { center: [25mm, 12mm]+ diameter: 4mm }+ Hole ServicePort { center: [0mm, 10mm] diameter: 3mm }+ Hole SecondPort { center: [0mm, -10mm] diameter: 3mm }+ }+ SculptState GripAdded {+ Input: Base+ AddSectionChain Grip { Chain: GripChain+ Support: HousingSideEast+ Terminal: Attach+ InfluenceEnvelope: [40mm, -20mm, 0mm, 80mm, 20mm, 20mm] }+ MayModify: [HousingSideEast]+ Preserve: [BottomMountingInterface, MountingHolePattern]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ output: GripAdded+}diff --git a/fixtures/Regression/BodyStateDebt/unknown-field.firmament b/fixtures/Regression/BodyStateDebt/unknown-field.firmamentnew file mode 100644index 00000000..3e57ae23--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/unknown-field.firmament@@ -0,0 +1,6 @@+Model State_box {+ units: mm+ Box Stock { size: [30mm, 20mm, 10mm] heigth: 2mm }+ BodyState Base { input: Stock }+ output: Base+}diff --git a/fixtures/Regression/BodyStateDebt/unsupported-cylinder-edit.firmament b/fixtures/Regression/BodyStateDebt/unsupported-cylinder-edit.firmamentnew file mode 100644index 00000000..fd4892fb--- /dev/null+++ b/fixtures/Regression/BodyStateDebt/unsupported-cylinder-edit.firmament@@ -0,0 +1,12 @@+Model State_cylinder {+ units: mm+ Cylinder Stock { radius: 6mm height: 17mm }+ BodyState Base { input: Stock }+ SculptState Bad {+ input: Base+ OffsetRegion { target: HousingCrown offset: 3mm region: [4mm, 4mm]+ influenceEnvelope: [-10mm, -10mm, 0mm, 10mm, 10mm, 30mm] boundary: G0 }+ mayModify: [HousingCrown]+ }+ output: Bad+}