Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Persist typed construction intent and replay validation
Yuechen Lid5c8acc9dc7a
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 785cf316..ce086a83 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -667,6 +667,7 @@ public static class CliRunnerinputState = compile.OutputState.PredecessorStateId,outputState = compile.OutputState.StateId,compile.OutputState.Delta,+ constructionState = compile.OutputState.ConstructionAuthority,validationEvidence = compile.OutputState.ValidationEvidence,surfacePatches = compile.OutputState.SurfacePatches,blendJudgment = compile.OutputState.BlendJudgment,@@ -723,7 +724,20 @@ public static class CliRunnerprivate static object DescribeSculptState(BodyState state) => new{state.AuthoredName, state.StateId, state.PredecessorStateId, state.BodyStableId,- construction = new { state.Construction.Width, state.Construction.Depth, state.Construction.BaseHeight, state.Construction.CrownWidth, state.Construction.CrownDepth, state.Construction.CrownOffset, state.Construction.FinalHeight },+ constructionState = state.ConstructionAuthority is null ? null : new+ {+ schema = new { state.ConstructionAuthority.SchemaId, state.ConstructionAuthority.SchemaVersion },+ @base = new { state.ConstructionAuthority.Base.BaseId, state.ConstructionAuthority.Base.BaseKind, state.ConstructionAuthority.Base.SchemaVersion },+ operations = state.ConstructionAuthority.Operations.Select(operation => new+ {+ operation.OperationId, operation.OperationKind, operation.PayloadVersion,+ operation.PredecessorStateId, operation.OutputStateId, operation.Reads, operation.MayModify,+ authorizedRegion = operation.AuthorizedRegion, preserve = operation.Preserves,+ operation.ReplayStatus,+ delta = 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 },semanticInventory = state.SemanticInventory.Values, surfacePatches = state.SurfacePatches, blendJudgment = state.BlendJudgment, hasDelta = state.Delta is not null};diff --git a/Aetheris.Kernel.Firmament.Tests/SurfX2BlendBoundaryTests.cs b/Aetheris.Kernel.Firmament.Tests/SurfX2BlendBoundaryTests.csindex a4a46653..3ce17011 100644--- a/Aetheris.Kernel.Firmament.Tests/SurfX2BlendBoundaryTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/SurfX2BlendBoundaryTests.cs@@ -43,6 +43,22 @@ public sealed class SurfX2BlendBoundaryTestsAssert.Equal(SculptStepExporter.Export(first.OutputState, first.ModelName).Step, SculptStepExporter.Export(second.OutputState, second.ModelName).Step);}+ [Fact]+ public void BlendPersistsAsBlendIntentAndReplaysWithoutCollapsingToReplaceRegion()+ {+ var compiled = SculptingAuthoring.CompileFile(Fixture("Canonical", "Sculpting", "surf-x2-judged-housing.firmament"));+ Assert.True(compiled.IsSuccess);+ var authority = Assert.IsType<ConstructionState>(compiled.OutputState!.ConstructionAuthority);+ var operation = Assert.Single(authority.Operations);+ Assert.Equal("BlendBoundary", operation.OperationKind);+ Assert.IsType<BlendBoundaryOperation>(operation.Payload);++ var replay = ConstructionStateReplayer.Replay(authority);+ Assert.True(replay.IsSuccess, string.Join(" | ", replay.Diagnostics.Select(item => item.Message)));+ Assert.Equal(compiled.OutputState.StateId, replay.OutputState!.StateId);+ Assert.Equal(compiled.OutputState.BlendJudgment!.SelectedCandidateId, replay.OutputState.BlendJudgment!.SelectedCandidateId);+ }+[Fact]public void ExplicitFallbackAndEligibleManualOverrideAreVisible(){diff --git a/Aetheris.Modules.Tests/SurfX0SculptingTests.cs b/Aetheris.Modules.Tests/SurfX0SculptingTests.csindex 730ad4ff..f4c820f5 100644--- a/Aetheris.Modules.Tests/SurfX0SculptingTests.cs+++ b/Aetheris.Modules.Tests/SurfX0SculptingTests.cs@@ -61,6 +61,46 @@ public sealed class SurfX0SculptingTestsvar import = Step242Importer.ImportBody(export.Step!); Assert.True(import.IsSuccess, string.Join(';', import.Diagnostics.Select(x => x.Message)));}+ [Fact]+ public void TypedConstructionAuthorityRoundTripsAndReplaysDeterministically()+ {+ var compiled = Compile("Canonical/Sculpting/sculpted-housing.firmament");+ var authored = Assert.IsType<ConstructionState>(compiled.OutputState!.ConstructionAuthority);+ var operation = Assert.Single(authored.Operations);+ Assert.Equal("OffsetRegion", operation.OperationKind);+ Assert.IsType<OffsetRegionOperation>(operation.Payload);++ var serialized = ConstructionStateSerializer.Serialize(authored);+ Assert.True(serialized.IsSuccess, string.Join(" | ", serialized.Diagnostics.Select(item => item.Message)));+ var deserialized = ConstructionStateSerializer.Deserialize(serialized.Json!);+ Assert.True(deserialized.IsSuccess, string.Join(" | ", deserialized.Diagnostics.Select(item => item.Message)));++ var replay = ConstructionStateReplayer.Replay(deserialized.ConstructionState!);+ Assert.True(replay.IsSuccess, string.Join(" | ", replay.Diagnostics.Select(item => item.Message)));+ Assert.Equal(compiled.OutputState.StateId, replay.OutputState!.StateId);+ Assert.Equal(SculptStepExporter.Export(compiled.OutputState, compiled.ModelName).Step,+ SculptStepExporter.Export(replay.OutputState, compiled.ModelName).Step);+ Assert.All(replay.OutputState.ConstructionAuthority!.Operations,+ item => Assert.Equal(ConstructionReplayStatus.ReplayedAndValidated, item.ReplayStatus));+ }++ [Fact]+ public void ReplayFailureIsAtomicAndLeavesPredecessorAuthoritative()+ {+ var authored = Compile("Canonical/Sculpting/sculpted-housing.firmament").OutputState!.ConstructionAuthority!;+ var operation = authored.Operations.Single();+ var unsupported = operation with { PayloadVersion = 99 };+ var replay = ConstructionStateReplayer.Replay(authored with { Operations = [unsupported] });++ Assert.False(replay.IsSuccess);+ Assert.Null(replay.OutputState);+ Assert.NotNull(replay.AuthoritativePredecessor);+ Assert.Null(replay.AuthoritativePredecessor!.PredecessorStateId);+ Assert.Equal(operation.OperationId, replay.FailedOperation!.OperationId);+ Assert.Contains(replay.Diagnostics, item => item.Code == "bodystate-operation-replay-failed");+ Assert.Contains(replay.Diagnostics, item => item.Code == "bodystate-operation-version-unsupported");+ }+[Fact]public void TemporaryEqualWeightRationalSurfaceRecoversExactPlaneAndNonRemovableRationalityBlocks(){diff --git a/Aetheris.Modules.Tests/SurfX1PatchSurfacingTests.cs b/Aetheris.Modules.Tests/SurfX1PatchSurfacingTests.csindex a8f2e4b3..713e76ef 100644--- a/Aetheris.Modules.Tests/SurfX1PatchSurfacingTests.cs+++ b/Aetheris.Modules.Tests/SurfX1PatchSurfacingTests.cs@@ -22,6 +22,22 @@ public sealed class SurfX1PatchSurfacingTestsAssert.Contains(state.ValidationEvidence, x => x.Check == "Boundary:BoundaryWest:G1" && x.Satisfied && x.MaximumObservedDeviation < .001d);}+ [Fact]+ public void ReplaceRegionPersistsAsTypedIntentAndReplaysByteIdentically()+ {+ var compiled = CompileFlagship();+ var authored = compiled.States["FreeformCrown"];+ var authority = Assert.IsType<ConstructionState>(authored.ConstructionAuthority);+ Assert.Equal("ReplaceRegion", Assert.Single(authority.Operations).OperationKind);++ var replay = ConstructionStateReplayer.Replay(authority);++ Assert.True(replay.IsSuccess, string.Join(" | ", replay.Diagnostics.Select(item => item.Message)));+ Assert.Equal(authored.StateId, replay.OutputState!.StateId);+ Assert.Equal(SculptStepExporter.Export(authored, "SURF-X1 replay").Step,+ SculptStepExporter.Export(replay.OutputState, "SURF-X1 replay").Step);+ }+[Fact]public void TrimAndExtendRemainBoundedByExistingNonRationalSupport(){diff --git a/Aetheris.Modules.Tests/SurfX3bConstructionStateTests.cs b/Aetheris.Modules.Tests/SurfX3bConstructionStateTests.csnew file mode 100644index 00000000..87d04ec6--- /dev/null+++ b/Aetheris.Modules.Tests/SurfX3bConstructionStateTests.cs@@ -0,0 +1,181 @@+using Aetheris.Kernel.Core.Math;+using Aetheris.Surfacing;+using Xunit;++namespace Aetheris.Modules.Tests;++public sealed class SurfX3bConstructionStateTests+{+ [Fact]+ public void AddSectionChainBuildsOneBodyAndSurvivesSerializedReplay()+ {+ var baseState = Base(); var chain = AdditiveChain();+ var operation = new AddSectionChainOperation("Grip.AddSectionChain", chain,+ new(SculptedHousingFactory.HousingSideEast, "Attach", SectionChainAttachmentPlacement.RelativeToSupport,+ SpanIds.Select(id => new SectionSpanCorrespondence(id, id)).ToArray()),+ [SculptedHousingFactory.HousingSideEast], new(40, -20, 0, 88, 20, 20), Preserve(), Requirements());++ var added = AddSectionChainSculptor.Apply(baseState, "GripAdded", operation);+ Assert.True(added.IsSuccess, Messages(added.Diagnostics));+ Assert.Single(added.OutputState!.Body.Topology.Bodies);+ Assert.Equal("AddSectionChain", Assert.Single(added.OutputState.ConstructionAuthority!.Operations).OperationKind);+ Assert.Contains(added.Evidence, item => item.Check == "AddSectionChainPositiveVolume" && item.Satisfied);++ var serialized = ConstructionStateSerializer.Serialize(added.OutputState.ConstructionAuthority);+ Assert.True(serialized.IsSuccess, Messages(serialized.Diagnostics));+ var deserialized = ConstructionStateSerializer.Deserialize(serialized.Json!);+ Assert.True(deserialized.IsSuccess, Messages(deserialized.Diagnostics));+ var replay = ConstructionStateReplayer.Replay(deserialized.ConstructionState!);+ Assert.True(replay.IsSuccess, Messages(replay.Diagnostics));+ Assert.Equal(added.OutputState.StateId, replay.OutputState!.StateId);+ Assert.Equal(SculptStepExporter.Export(added.OutputState, "Grip").Step, SculptStepExporter.Export(replay.OutputState, "Grip").Step);+ }++ [Fact]+ public void RemoveSectionChainBuildsChangingThroughDuctAndSurvivesReplay()+ {+ var baseState = Base(); var chain = DuctChain();+ var operation = new RemoveSectionChainOperation("Duct.RemoveSectionChain", chain,+ [SculptedHousingFactory.HousingSideWest, SculptedHousingFactory.HousingSideEast],+ [SculptedHousingFactory.HousingSideWest, SculptedHousingFactory.HousingSideEast],+ new(-40, -7, 5, 40, 7, 15), Preserve(), Requirements());++ var removed = RemoveSectionChainSculptor.Apply(baseState, "DuctRemoved", operation);+ Assert.True(removed.IsSuccess, Messages(removed.Diagnostics));+ Assert.Single(removed.OutputState!.Body.Topology.Bodies);+ Assert.Equal("RemoveSectionChain", Assert.Single(removed.OutputState.ConstructionAuthority!.Operations).OperationKind);+ Assert.Contains(removed.Evidence, item => item.Check == "RemoveSectionChainPositiveVolume" && item.Satisfied);+ var replay = ConstructionStateReplayer.Replay(removed.OutputState.ConstructionAuthority);+ Assert.True(replay.IsSuccess, Messages(replay.Diagnostics));+ Assert.Equal(removed.OutputState.StateId, replay.OutputState!.StateId);+ }++ [Fact]+ public void MissingSemanticSupportFailsWithoutNearestFaceRebinding()+ {+ var baseState = Base();+ var operation = new AddSectionChainOperation("Grip.AddSectionChain", AdditiveChain(),+ new("DeletedSupport", "Attach", SectionChainAttachmentPlacement.RelativeToSupport, []), ["DeletedSupport"],+ new(40, -20, 0, 88, 20, 20), Preserve(), Requirements());+ var result = AddSectionChainSculptor.Apply(baseState, "Invalid", operation);+ Assert.False(result.IsSuccess);+ Assert.Contains(result.Diagnostics, item => item.Code == "bodystate-operation-support-missing");+ Assert.Null(result.OutputState);+ }++ [Theory]+ [InlineData("surf-x3b-add-section-chain-grip.firmament", "AddSectionChain")]+ [InlineData("surf-x3b-remove-section-chain-duct.firmament", "RemoveSectionChain")]+ public void FirmamentFlagshipsLowerToTypedOperationsAndReplay(string fixture, string kind)+ {+ var compiled = SculptingAuthoring.CompileFile(Fixture("Canonical", "BodyState", fixture));+ Assert.True(compiled.IsSuccess, Messages(compiled.Diagnostics));+ Assert.Equal(kind, Assert.Single(compiled.OutputState!.ConstructionAuthority!.Operations).OperationKind);+ var replay = ConstructionStateReplayer.Replay(compiled.OutputState.ConstructionAuthority);+ Assert.True(replay.IsSuccess, Messages(replay.Diagnostics));+ Assert.Equal(compiled.OutputState.StateId, replay.OutputState!.StateId);+ Assert.Equal(SculptStepExporter.Export(compiled.OutputState, compiled.ModelName).Step,+ SculptStepExporter.Export(replay.OutputState, compiled.ModelName).Step);+ }++ [Fact]+ public void ThreeTypedFirmamentOperationsAndSafeFeatureAfterSculptSurviveReplay()+ {+ var multi = SculptingAuthoring.CompileFile(Fixture("Canonical", "BodyState", "surf-x3b-multi-operation-replay.firmament"));+ Assert.True(multi.IsSuccess, Messages(multi.Diagnostics));+ Assert.Equal(["HoleFeature", "HoleFeature", "AddSectionChain"], multi.OutputState!.ConstructionAuthority!.Operations.Select(item => item.OperationKind));+ Assert.True(ConstructionStateReplayer.Replay(multi.OutputState.ConstructionAuthority).IsSuccess);++ var after = SculptingAuthoring.CompileFile(Fixture("Canonical", "BodyState", "surf-x3b-safe-feature-after-add.firmament"));+ Assert.True(after.IsSuccess, Messages(after.Diagnostics));+ Assert.Equal(["AddSectionChain", "HoleFeature"], after.OutputState!.ConstructionAuthority!.Operations.Select(item => item.OperationKind));+ Assert.Contains("GripChain.AttachedSurface", after.OutputState.SemanticInventory.Keys);+ var replay = ConstructionStateReplayer.Replay(after.OutputState.ConstructionAuthority);+ Assert.True(replay.IsSuccess, Messages(replay.Diagnostics));+ Assert.Contains("GripChain.AttachedSurface", replay.OutputState!.SemanticInventory.Keys);+ }++ [Fact]+ public void ReorderedSerializedOperationsFailAtTheBrokenAuthoredPredecessorLink()+ {+ var compiled = SculptingAuthoring.CompileFile(Fixture("Canonical", "BodyState", "surf-x3b-multi-operation-replay.firmament"));+ Assert.True(compiled.IsSuccess, Messages(compiled.Diagnostics));+ var authority = compiled.OutputState!.ConstructionAuthority!;+ var operations = authority.Operations.ToArray();+ var reordered = authority with { Operations = [operations[0], operations[2], operations[1]] };++ var replay = ConstructionStateReplayer.Replay(reordered);++ Assert.False(replay.IsSuccess);+ Assert.Null(replay.OutputState);+ Assert.Equal(operations[0].OutputStateId, replay.AuthoritativePredecessor!.StateId);+ Assert.Equal(operations[2].OperationId, replay.FailedOperation!.OperationId);+ Assert.Contains(replay.Diagnostics, item => item.Code == "bodystate-operation-order-invalid");+ Assert.Contains(replay.Diagnostics, item => item.Code == "bodystate-operation-replay-failed");+ }++ [Fact]+ public void WiderUpstreamBaseRebindsRelativeAttachmentSemanticallyAndMissingSupportInvalidates()+ {+ var compiled = SculptingAuthoring.CompileFile(Fixture("Canonical", "BodyState", "surf-x3b-add-section-chain-grip.firmament"));+ var authority = compiled.OutputState!.ConstructionAuthority!;+ var housing = Assert.IsType<HousingBaseConstruction>(authority.Base);+ var wider = authority with { Base = housing with { Housing = housing.Housing with { Width = 90, CrownWidth = 90 } } };+ var replay = ConstructionStateReplayer.Replay(wider, "WiderGrip");+ Assert.True(replay.IsSuccess, Messages(replay.Diagnostics));+ Assert.NotEqual(compiled.OutputState.StateId, replay.OutputState!.StateId);+ Assert.Equal("AddSectionChain", Assert.Single(replay.OutputState.ConstructionAuthority!.Operations).OperationKind);++ var add = authority.Operations.Single();+ var invalidPayload = ((AddSectionChainOperation)add.Payload) with+ {+ Attachment = ((AddSectionChainOperation)add.Payload).Attachment with { SupportRegion = "DeletedSupport" },+ MayModify = ["DeletedSupport"]+ };+ var invalid = authority with { Operations = [add with { OperationId = invalidPayload.StableId, OperationKind = invalidPayload.OperationKind, Payload = invalidPayload }] };+ var failed = ConstructionStateReplayer.Replay(invalid);+ Assert.False(failed.IsSuccess); Assert.NotNull(failed.AuthoritativePredecessor);+ Assert.Contains(failed.Diagnostics, item => item.Code == "bodystate-operation-support-missing");+ }++ private static BodyState Base()+ {+ var result = SculptedHousingFactory.CreateBase("Base", 80, 40, 20,+ [new("MountA", -25, -12, 4), new("MountB", 25, 12, 4)]);+ Assert.True(result.IsSuccess, Messages(result.Diagnostics)); return result.OutputState!;+ }++ private static SectionChain AdditiveChain() => Chain("GripChain", SectionTermination.Open, SectionTermination.Cap,+ ("Attach", 0d, 40d, 20d, 10d), ("Neck", 10d, 34d, 18d, 10d), ("PalmFront", 22d, 30d, 16d, 10d),+ ("PalmRear", 36d, 24d, 14d, 10d), ("Tail", 48d, 14d, 10d, 10d));++ private static SectionChain DuctChain() => Chain("DuctChain", SectionTermination.Open, SectionTermination.Open,+ ("West", -40d, 10d, 8d, 10d), ("Entry", -20d, 13d, 9d, 10d), ("Center", 0d, 12d, 10d, 10d),+ ("Exit", 20d, 9d, 7d, 10d), ("East", 40d, 11d, 8d, 10d));++ private static SectionChain Chain(string id, SectionTermination start, SectionTermination end,+ params (string Id, double X, double Width, double Height, double Z)[] stations)+ {+ var sections = stations.Select(station => new Section(station.Id,+ SectionFrame.Create(new(station.X, 0, station.Z), new(0, 1, 0), new(0, 0, 1)), Profile(station.Id, station.Width, station.Height))).ToArray();+ var correspondence = sections.Zip(sections.Skip(1), (a, b) => new AdjacentSectionCorrespondence(a.SectionId, b.SectionId,+ SpanIds.Select(span => new SectionSpanCorrespondence(span, span)).ToArray())).ToArray();+ return new(id, sections, correspondence, SectionTransitionPolicy.Ruled, start, end);+ }++ private static SectionProfile Profile(string id, double width, double height)+ {+ var w = width / 2d; var h = height / 2d;+ var points = new[] { new SectionPoint2D(-w, -h), new(w, -h), new(w, h), new(-w, h) };+ return new(id + ".Profile", Enumerable.Range(0, 4).Select(index => new SectionProfileSpan(SpanIds[index],+ new SectionProfileCurve.Line(points[index], points[(index + 1) % 4]) as SectionProfileCurve)).ToArray(), SpanIds[0]);+ }++ private static readonly string[] SpanIds = ["South", "East", "North", "West"];+ private static IReadOnlyList<PreservationContract> Preserve() =>+ [new(SculptedHousingFactory.BottomMountingInterface, PreservationMode.ExactGeometry), new(SculptedHousingFactory.MountingHolePattern, PreservationMode.PatternPlacementAndDiameter)];+ private static IReadOnlyList<SculptRequirement> Requirements() => [SculptRequirement.ClosedManifold, SculptRequirement.OrientationConsistency, SculptRequirement.NoSelfIntersection];+ private static string Messages(IEnumerable<SculptDiagnostic> diagnostics) => string.Join(" | ", diagnostics.Select(item => $"{item.Code}:{item.Message}"));+ private static string Fixture(params string[] parts) => Path.Combine([Root(), "fixtures", .. parts]);+ 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.Surfacing/BlendBoundary.cs b/Aetheris.Surfacing/BlendBoundary.csindex d3044ee8..8ba01ca5 100644--- a/Aetheris.Surfacing/BlendBoundary.cs+++ b/Aetheris.Surfacing/BlendBoundary.cs@@ -38,8 +38,14 @@ public sealed record BlendBoundaryOperation(int MaximumDegree = 10,double GeometricTolerance = 1e-6,double G1AngularToleranceDegrees = .1d,- double G2CurvatureTolerance = 1e-6)+ double G2CurvatureTolerance = 1e-6) : IConstructionOperation{+ public string OperationKind => "BlendBoundary";+ public int SchemaVersion => 1;+ public IReadOnlyList<string> Reads => [SupportA, SupportB, .. Preserves.Select(item => item.EntityId)];+ public IReadOnlyList<string> MayModifySet => MayModify;+ public SpatialInfluenceEnvelope AuthorizedEnvelope => InfluenceEnvelope;+ public IReadOnlyList<PreservationContract> PreservationContracts => Preserves;public BlendJudgmentPolicy EffectivePolicy => Policy ?? BlendJudgmentPolicy.StandardBlendJudgment;public string Canonical => string.Join('|', StableId, SupportA, SupportB, Region, PreferredContinuity, MinimumContinuity,RegionWidth.ToString("R"), RegionDepth.ToString("R"), CrownHeight.ToString("R"), MaximumDegree,@@ -202,7 +208,8 @@ public static class BlendBoundarySculptor});var outputId = BodyStateId.Derive($"{input.StateId.Value}|BlendBoundary|{operation.Canonical}|{selected.CandidateId}");var delta = realized.Delta with { OutputState = outputId, BlendJudgment = provenance };- var state = realized.OutputState with { StateId = outputId, Delta = delta, BlendJudgment = trace };+ var authority = ConstructionAuthorityEvolution.Append(input, outputName, operation, outputId, delta, realized.Evidence);+ var state = realized.OutputState with { StateId = outputId, Delta = delta, BlendJudgment = trace, ConstructionAuthority = authority };return new(true, state, delta, trace, []);}diff --git a/Aetheris.Surfacing/ConstructionReplay.cs b/Aetheris.Surfacing/ConstructionReplay.csnew file mode 100644index 00000000..44a70c2a--- /dev/null+++ b/Aetheris.Surfacing/ConstructionReplay.cs@@ -0,0 +1,193 @@+using System.Text.Json;+using System.Text.Json.Serialization;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Surfacing;++internal static class ConstructionAuthorityEvolution+{+ public static ConstructionState Append(+ BodyState input,+ string outputName,+ IConstructionOperation operation,+ BodyStateId outputStateId,+ GeometricDelta delta,+ IReadOnlyList<SculptValidationEvidence> evidence)+ {+ var authority = input.ConstructionAuthority ?? ConstructionState.FromHousing(input.Construction, 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,+ string? Json,+ IReadOnlyList<SculptDiagnostic> Diagnostics);++public static class ConstructionStateSerializer+{+ private static readonly JsonSerializerOptions Options = CreateOptions();++ private static JsonSerializerOptions CreateOptions()+ {+ var options = new JsonSerializerOptions+ {+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase,+ WriteIndented = true,+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull+ };+ options.Converters.Add(new Direction3DConverter());+ return options;+ }++ public static ConstructionStateSerializationResult Serialize(ConstructionState state)+ {+ try { return new(true, state, JsonSerializer.Serialize(state, Options), []); }+ catch (NotSupportedException exception) { return Failure("bodystate-construction-serialization-failed", exception.Message); }+ }++ public static ConstructionStateSerializationResult Deserialize(string json)+ {+ try+ {+ var state = JsonSerializer.Deserialize<ConstructionState>(json, Options);+ return state is null ? Failure("bodystate-construction-deserialization-failed", "ConstructionState payload was empty.") : new(true, state, json, []);+ }+ catch (Exception exception) when (exception is JsonException or NotSupportedException)+ {+ return Failure("bodystate-construction-deserialization-failed", exception.Message);+ }+ }++ private static ConstructionStateSerializationResult Failure(string code, string message) => new(false, null, null, [new(code, message)]);++ private sealed class Direction3DConverter : JsonConverter<Direction3D>+ {+ public override Direction3D Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)+ {+ using var document = JsonDocument.ParseValue(ref reader); var root = document.RootElement;+ return Direction3D.Create(new(root.GetProperty("x").GetDouble(), root.GetProperty("y").GetDouble(), root.GetProperty("z").GetDouble()));+ }++ public override void Write(Utf8JsonWriter writer, Direction3D value, JsonSerializerOptions options)+ {+ writer.WriteStartObject(); writer.WriteNumber("x", value.X); writer.WriteNumber("y", value.Y); writer.WriteNumber("z", value.Z); writer.WriteEndObject();+ }+ }+}diff --git a/Aetheris.Surfacing/SculptingAuthoring.cs b/Aetheris.Surfacing/SculptingAuthoring.csindex 4b4aada9..24986773 100644--- a/Aetheris.Surfacing/SculptingAuthoring.cs+++ b/Aetheris.Surfacing/SculptingAuthoring.cs@@ -20,6 +20,7 @@ public static class SculptingAuthoring{var total = Stopwatch.StartNew(); var diagnostics = new List<SculptDiagnostic>(); var states = new Dictionary<string, BodyState>(StringComparer.Ordinal);var patches = new Dictionary<string, BoundedSurfacePatch>(StringComparer.Ordinal);+ var sectionChains = new Dictionary<string, SectionChain>(StringComparer.Ordinal);var model = ModelHeader.Match(source); if (!model.Success) return Fail("<unknown>", "sculpt-source-malformed", "Sculpting source requires 'Model Name { ... }'.");if (!Regex.IsMatch(source, @"\bUnits\s*:\s*mm\b", RegexOptions.CultureInvariant)) diagnostics.Add(new("sculpt-units-invalid", "SURF-X0 authoring requires millimetres."));foreach (var block in Blocks(source, "SurfacePatch"))@@ -43,6 +44,18 @@ public static class SculptingAuthoringdiagnostics.Add(new("surf-patch-invalid", $"SurfacePatch '{block.Name}' is invalid: {exception.Message}", block.Name));}}+ foreach (var block in Blocks(source, "SectionChain"))+ {+ var chain = ParseSectionChain(block, diagnostics);+ if (chain is null) continue;+ var qualification = SectionChainMaterializer.Materialize(chain);+ if (!qualification.IsSuccess)+ {+ diagnostics.AddRange(qualification.Diagnostics.Select(item => new SculptDiagnostic(item.Code, item.Message, block.Name)));+ continue;+ }+ if (!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(source, "BodyState")){@@ -62,7 +75,41 @@ public static class SculptingAuthoringvar replaceBlock = Blocks(block.Body, "ReplaceRegion").SingleOrDefault();var blendBlock = Blocks(block.Body, "BlendBoundary").SingleOrDefault();var holeBlock = Blocks(block.Body, "HoleFeature").SingleOrDefault();- if (new[] { operationBlock, replaceBlock, blendBlock, holeBlock }.Count(x => x is not null) != 1) { diagnostics.Add(new("sculpt-operation-unsupported", $"SculptState '{block.Name}' requires exactly one OffsetRegion, ReplaceRegion, BlendBoundary, or HoleFeature operation.")); continue; }+ var addChainBlock = Blocks(block.Body, "AddSectionChain").SingleOrDefault();+ var removeChainBlock = Blocks(block.Body, "RemoveSectionChain").SingleOrDefault();+ if (new[] { operationBlock, replaceBlock, blendBlock, holeBlock, addChainBlock, removeChainBlock }.Count(x => x is not null) != 1) { diagnostics.Add(new("sculpt-operation-unsupported", $"SculptState '{block.Name}' requires exactly one OffsetRegion, ReplaceRegion, BlendBoundary, HoleFeature, AddSectionChain, or RemoveSectionChain operation.")); continue; }+ if (addChainBlock is not null)+ {+ var chainName = ScalarText(addChainBlock.Body, "Chain"); var support = ScalarText(addChainBlock.Body, "Support") ?? string.Empty;+ var terminal = ScalarText(addChainBlock.Body, "Terminal") ?? string.Empty; var chainEnvelope = Vector(addChainBlock.Body, "InfluenceEnvelope", 6, diagnostics);+ var addMayModify = List(block.Body, "MayModify"); var addPreserve = List(block.Body, "Preserve"); var addRequirements = ParseRequirements(List(block.Body, "Require"), diagnostics);+ operationClock.Stop(); opConstruction += operationClock.Elapsed;+ if (chainName is null || !sectionChains.TryGetValue(chainName, out var chain)) diagnostics.Add(new("section-chain-unresolved", $"AddSectionChain in '{block.Name}' must reference a declared SectionChain."));+ if (chainEnvelope is null || chainName is null || !sectionChains.TryGetValue(chainName, out chain)) continue;+ var correspondence = chain.Sections[0].Profile.Spans.Select(span => new SectionSpanCorrespondence(span.SpanId, span.SpanId)).ToArray();+ var addOperation = new AddSectionChainOperation(block.Name + ".AddSectionChain", chain,+ new(support, terminal, SectionChainAttachmentPlacement.RelativeToSupport, correspondence), addMayModify,+ new(chainEnvelope[0], chainEnvelope[1], chainEnvelope[2], chainEnvelope[3], chainEnvelope[4], chainEnvelope[5]), addPreserve.Select(Preservation).ToArray(), addRequirements);+ var addResult = AddSectionChainSculptor.Apply(input, block.Name, addOperation);+ if (!addResult.IsSuccess || addResult.OutputState is null) diagnostics.AddRange(addResult.Diagnostics);+ else if (!states.TryAdd(block.Name, addResult.OutputState)) diagnostics.Add(new("sculpt-state-duplicate", $"State '{block.Name}' is declared more than once."));+ continue;+ }+ if (removeChainBlock is not null)+ {+ var chainName = ScalarText(removeChainBlock.Body, "Chain"); var supports = List(removeChainBlock.Body, "Supports");+ var chainEnvelope = Vector(removeChainBlock.Body, "InfluenceEnvelope", 6, diagnostics);+ var removeMayModify = List(block.Body, "MayModify"); var removePreserve = List(block.Body, "Preserve"); var removeRequirements = ParseRequirements(List(block.Body, "Require"), diagnostics);+ operationClock.Stop(); opConstruction += operationClock.Elapsed;+ if (chainName is null || !sectionChains.TryGetValue(chainName, out var chain)) diagnostics.Add(new("section-chain-unresolved", $"RemoveSectionChain in '{block.Name}' must reference a declared SectionChain."));+ if (chainEnvelope is null || chainName is null || !sectionChains.TryGetValue(chainName, out chain)) continue;+ var removeOperation = new RemoveSectionChainOperation(block.Name + ".RemoveSectionChain", chain, supports, removeMayModify,+ new(chainEnvelope[0], chainEnvelope[1], chainEnvelope[2], chainEnvelope[3], chainEnvelope[4], chainEnvelope[5]), removePreserve.Select(Preservation).ToArray(), removeRequirements);+ var removeResult = RemoveSectionChainSculptor.Apply(input, block.Name, removeOperation);+ if (!removeResult.IsSuccess || removeResult.OutputState is null) diagnostics.AddRange(removeResult.Diagnostics);+ else if (!states.TryAdd(block.Name, removeResult.OutputState)) diagnostics.Add(new("sculpt-state-duplicate", $"State '{block.Name}' is declared more than once."));+ continue;+ }if (holeBlock is not null){var holeTarget = ScalarText(holeBlock.Body, "Target") ?? string.Empty; var holeId = ScalarText(holeBlock.Body, "Id") ?? string.Empty;@@ -160,6 +207,29 @@ public static class SculptingAuthoringreturn result;}+ private static SectionChain? ParseSectionChain(Block block, List<SculptDiagnostic> diagnostics)+ {+ var stations = new List<Section>(); var spanIds = new[] { "South", "East", "North", "West" };+ foreach (var station in Blocks(block.Body, "Station"))+ {+ var origin = Vector(station.Body, "Origin", 3, diagnostics); var size = Vector(station.Body, "Size", 2, diagnostics);+ if (origin is null || size is null) continue;+ if (size[0] <= 0d || size[1] <= 0d) { diagnostics.Add(new("section-chain-profile-size-invalid", $"Station '{station.Name}' Size must be positive.", station.Name)); continue; }+ var halfWidth = size[0] / 2d; var halfHeight = size[1] / 2d;+ var points = new[] { new SectionPoint2D(-halfWidth, -halfHeight), new(halfWidth, -halfHeight), new(halfWidth, halfHeight), new(-halfWidth, halfHeight) };+ var profile = new SectionProfile(station.Name + ".Profile", Enumerable.Range(0, 4).Select(index => new SectionProfileSpan(spanIds[index],+ new SectionProfileCurve.Line(points[index], points[(index + 1) % 4]) as SectionProfileCurve)).ToArray(), spanIds[0]);+ stations.Add(new(station.Name, SectionFrame.Create(new(origin[0], origin[1], origin[2]), new(0, 1, 0), new(0, 0, 1)), profile));+ }+ 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))+ { 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();+ return new(block.Name, stations, correspondence, SectionTransitionPolicy.Ruled, start, end);+ }+private static IReadOnlyList<Block> Blocks(string source, string keyword){var result = new List<Block>(); var regex = new Regex($@"\b{Regex.Escape(keyword)}(?:\s+(?<name>[A-Za-z_]\w*))?\s*\{{", RegexOptions.CultureInvariant);diff --git a/Aetheris.Surfacing/SculptingExecution.cs b/Aetheris.Surfacing/SculptingExecution.csindex 31958b7b..706cb54d 100644--- a/Aetheris.Surfacing/SculptingExecution.cs+++ b/Aetheris.Surfacing/SculptingExecution.cs@@ -21,6 +21,8 @@ public static class SculptedHousingFactorypublic const string CrownBoundaryEast = "CrownBoundaryEast";public const string CrownBoundaryNorth = "CrownBoundaryNorth";public const string CrownBoundaryWest = "CrownBoundaryWest";+ public const string HousingSideEast = "HousingSideEast";+ public const string HousingSideWest = "HousingSideWest";public static SculptResult CreateBase(string stateName, double width, double depth, double height, IReadOnlyList<HousingHole> holes){@@ -35,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)), null, evidence, []);+ associations, SemanticPmi(associations, construction), AssemblyInterfaces(associations), ConstructionAuthority: ConstructionState.FromHousing(construction)), null, evidence, []);}internal static IReadOnlyDictionary<string, SculptSemanticEntity> Inventory(HousingConstruction c)@@ -52,6 +54,8 @@ public static class SculptedHousingFactory[CrownBoundaryEast] = new(CrownBoundaryEast, SculptEntityKind.Region, $"east:{c.CrownDepth:R}@x={c.CrownWidth / 2d:R};z={c.BaseHeight:R}", "East replacement boundary."),[CrownBoundaryNorth] = new(CrownBoundaryNorth, SculptEntityKind.Region, $"north:{c.CrownWidth:R}@y={c.CrownDepth / 2d:R};z={c.BaseHeight:R}", "North replacement boundary."),[CrownBoundaryWest] = new(CrownBoundaryWest, SculptEntityKind.Region, $"west:{c.CrownDepth:R}@x={-c.CrownWidth / 2d:R};z={c.BaseHeight:R}", "West replacement boundary."),+ [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."),};foreach (var hole in c.Holes) inventory[hole.StableId] = new(hole.StableId, SculptEntityKind.Region, HoleFingerprint(hole), "Stable mounting-hole feature.");return inventory;@@ -74,8 +78,10 @@ public static class SculptedHousingFactoryinternal static IReadOnlyList<PersistentGeometryAssociation> PersistentAssociations(BrepBody body, HousingConstruction construction){- var bottom = body.Topology.Faces.Where(face => body.TryGetFaceSurfaceGeometry(face.Id, out var support)- && support?.Plane is { } plane && Math.Abs(plane.Origin.Z) <= 1e-8d && plane.Normal.ToVector().Z < 0d).Select(face => face.Id.Value).ToArray();+ var bottomCandidates = body.Topology.Faces.Where(face => body.TryGetFaceSurfaceGeometry(face.Id, out var support)+ && support?.Plane is { } plane && Math.Abs(plane.Origin.Z) <= 1e-8d && plane.Normal.ToVector().Z < -1d + 1e-8d).ToArray();+ var maximumLoopCount = bottomCandidates.Select(face => face.LoopIds.Count).DefaultIfEmpty().Max();+ var 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@@ -201,8 +207,9 @@ public static class OffsetRegionSculptorvar associationRemap = SculptedHousingFactory.RemapPersistentAssociations(input, built.Body, delta);if (!associationRemap.IsSuccess) return SculptResult.Failure(associationRemap.Diagnostics, evidence);var 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));+ outputAssociations, SculptedHousingFactory.SemanticPmi(outputAssociations, outputConstruction), SculptedHousingFactory.AssemblyInterfaces(outputAssociations), ConstructionAuthority: authority);return new(true, output, delta, evidence, []);}}@@ -349,8 +356,9 @@ public static class ReplaceRegionSculptorvar associationRemap = SculptedHousingFactory.RemapPersistentAssociations(input, built.Body, delta);if (!associationRemap.IsSuccess) return SculptResult.Failure(associationRemap.Diagnostics, evidence);var 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)), delta, evidence, []);+ outputAssociations, SculptedHousingFactory.SemanticPmi(outputAssociations, construction), SculptedHousingFactory.AssemblyInterfaces(outputAssociations), ConstructionAuthority: authority), delta, evidence, []);}private static IReadOnlyList<Point3D> Sample(BoundedSurfacePatch patch, int count)@@ -437,29 +445,47 @@ public static class SafeHoleSculptorif (diagnostics.Count > 0) return SculptResult.Failure(diagnostics);var construction = input.Construction with { Holes = [.. input.Construction.Holes, operation.Hole] };- var built = SculptedHousingBrepBuilder.Build(construction);- if (built.Body is null) return SculptResult.Failure(built.Diagnostics);+ var retainedAdd = input.ConstructionAuthority?.Operations.LastOrDefault()?.Payload as AddSectionChainOperation;+ BrepBody? realizedBody; IReadOnlyList<SculptDiagnostic> buildDiagnostics;+ if (retainedAdd is not null)+ {+ var retained = SectionChainHousingBrepBuilder.BuildAddEast(construction, retainedAdd.Chain);+ realizedBody = retained.Body; buildDiagnostics = retained.Diagnostics;+ }+ else+ {+ var built = SculptedHousingBrepBuilder.Build(construction);+ realizedBody = built.Body; buildDiagnostics = built.Diagnostics;+ }+ if (realizedBody is null) return SculptResult.Failure(buildDiagnostics);var inventory = SculptedHousingFactory.Inventory(construction).ToDictionary(x => x.Key, x => x.Value, StringComparer.Ordinal);if (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.");}+ if (retainedAdd is not null)+ {+ inventory.Remove(retainedAdd.Attachment.SupportRegion);+ var successor = $"{retainedAdd.Chain.StableId}.AttachedSurface";+ inventory[successor] = input.SemanticInventory[successor];+ }foreach (var contract in operation.Preserves){var before = input.SemanticInventory[contract.EntityId]; var after = inventory[contract.EntityId]; var satisfied = before.GeometryFingerprint == after.GeometryFingerprint;evidence.Add(new($"Preserve:{contract.EntityId}", satisfied, LocalityEvidenceLevel.ExactSemantic, satisfied ? 0d : null, 1e-6, satisfied ? "Current-state semantic identity and geometry fingerprint are unchanged." : "Preserved geometry changed."));if (!satisfied) diagnostics.Add(new("sculpt-preservation-failed", $"Preservation contract failed for '{contract.EntityId}'.", contract.EntityId));}- evidence.AddRange(SculptedHousingFactory.ValidateBody(built.Body, 1e-6));+ evidence.AddRange(SculptedHousingFactory.ValidateBody(realizedBody, 1e-6));if (diagnostics.Count > 0 || evidence.Any(x => !x.Satisfied)) return SculptResult.Failure(diagnostics, evidence);var outputId = BodyStateId.Derive($"{input.StateId.Value}|HoleFeature|{operation.Canonical}");var correspondence = operation.Preserves.Select(x => new GeometricDeltaEntry(x.EntityId, GeometricChangeKind.Preserved, [x.EntityId], "Resolved and verified against the current BodyState.")).Append(new("<none>", GeometricChangeKind.Introduced, [operation.Hole.StableId], "Exact cylindrical through-hole on the current planar frame.")).ToArray();var delta = new GeometricDelta(input.StateId, outputId, [operation.TargetRegion], operation.Preserves.Select(x => x.EntityId).ToArray(), [], [], [operation.Hole.StableId], [operation.TargetRegion], operation.InfluenceEnvelope, correspondence);- var outputAssociations = SculptedHousingFactory.PersistentAssociations(built.Body, construction);- return new(true, new(outputId, input.StateId, input.BodyStableId, outputName, built.Body, construction, inventory, delta, evidence,- outputAssociations, SculptedHousingFactory.SemanticPmi(outputAssociations, construction), SculptedHousingFactory.AssemblyInterfaces(outputAssociations)), delta, evidence, []);+ var 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, []);}}diff --git a/Aetheris.Surfacing/SculptingState.cs b/Aetheris.Surfacing/SculptingState.csindex 1c7fdddb..8c8c50bb 100644--- a/Aetheris.Surfacing/SculptingState.cs+++ b/Aetheris.Surfacing/SculptingState.cs@@ -1,5 +1,6 @@using System.Security.Cryptography;using System.Text;+using System.Text.Json.Serialization;using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Math;using Aetheris.Kernel.Core.Step242;@@ -70,6 +71,82 @@ public sealed record HousingConstruction(public bool HasCrown => CrownOffset > 0d && (CrownWidth < Width || CrownDepth < Depth);}+[JsonPolymorphic(TypeDiscriminatorPropertyName = "$baseKind")]+[JsonDerivedType(typeof(HousingBaseConstruction), "Housing")]+public interface IBaseConstruction+{+ string BaseId { get; }+ int SchemaVersion { get; }+ string BaseKind { get; }+}++/// <summary>The existing housing recipe as one admitted generalized construction base.</summary>+public sealed record HousingBaseConstruction(string BaseId, HousingConstruction Housing, int SchemaVersion = 1) : IBaseConstruction+{+ public string BaseKind => "Housing";+}++[JsonPolymorphic(TypeDiscriminatorPropertyName = "$operationKind")]+[JsonDerivedType(typeof(OffsetRegionOperation), "OffsetRegion")]+[JsonDerivedType(typeof(ReplaceRegionOperation), "ReplaceRegion")]+[JsonDerivedType(typeof(SafeHoleOperation), "HoleFeature")]+[JsonDerivedType(typeof(BlendBoundaryOperation), "BlendBoundary")]+[JsonDerivedType(typeof(AddSectionChainOperation), "AddSectionChain")]+[JsonDerivedType(typeof(RemoveSectionChainOperation), "RemoveSectionChain")]+public interface IConstructionOperation+{+ string StableId { get; }+ string OperationKind { get; }+ int SchemaVersion { get; }+ IReadOnlyList<string> Reads { get; }+ IReadOnlyList<string> MayModifySet { get; }+ SpatialInfluenceEnvelope AuthorizedEnvelope { get; }+ IReadOnlyList<PreservationContract> PreservationContracts { get; }+}++public enum ConstructionReplayStatus { AuthoredAndValidated, ReplayedAndValidated }++/// <summary>+/// Durable typed operation payload plus its geometric-SSA relationship and accepted evidence.+/// The payload, rather than a Boolean opcode or final faces, is the replay authority.+/// </summary>+public sealed record ConstructionOperationState(+ string OperationId,+ string OperationKind,+ int PayloadVersion,+ BodyStateId PredecessorStateId,+ BodyStateId OutputStateId,+ string OutputAuthoredName,+ IConstructionOperation Payload,+ IReadOnlyList<string> Reads,+ IReadOnlyList<string> MayModify,+ SpatialInfluenceEnvelope AuthorizedRegion,+ IReadOnlyList<PreservationContract> Preserves,+ GeometricDelta Delta,+ IReadOnlyList<SculptValidationEvidence> ValidationEvidence,+ ConstructionReplayStatus ReplayStatus = ConstructionReplayStatus.AuthoredAndValidated)+{+ public static ConstructionOperationState Accepted(BodyState input, string outputName, IConstructionOperation payload, BodyStateId outputStateId,+ GeometricDelta delta, IReadOnlyList<SculptValidationEvidence> evidence, ConstructionReplayStatus status = ConstructionReplayStatus.AuthoredAndValidated)+ => new(payload.StableId, payload.OperationKind, payload.SchemaVersion, input.StateId, outputStateId, outputName, payload,+ payload.Reads, payload.MayModifySet, payload.AuthorizedEnvelope, payload.PreservationContracts, delta, evidence, status);+}++public sealed record ConstructionState(+ string SchemaId,+ int SchemaVersion,+ IBaseConstruction Base,+ IReadOnlyList<ConstructionOperationState> Operations)+{+ public const string CurrentSchemaId = "aetheris.surfacing.construction-state";+ public const int CurrentSchemaVersion = 1;++ public static ConstructionState FromHousing(HousingConstruction housing, string baseId = "housing-base")+ => new(CurrentSchemaId, CurrentSchemaVersion, new HousingBaseConstruction(baseId, housing), []);++ public ConstructionState Append(ConstructionOperationState operation) => this with { Operations = [.. Operations, operation] };+}+public sealed record BodyState(BodyStateId StateId,BodyStateId? PredecessorStateId,@@ -83,7 +160,8 @@ public sealed record BodyState(IReadOnlyList<PersistentGeometryAssociation>? GeometryAssociations = null,IReadOnlyList<Step242SemanticPmi>? SemanticPmi = null,IReadOnlyList<SculptAssemblyInterface>? AssemblyInterfaces = null,- BlendJudgmentTrace? BlendJudgment = null)+ BlendJudgmentTrace? BlendJudgment = null,+ ConstructionState? ConstructionAuthority = null){public IReadOnlyList<SurfacePatchMetadata> SurfacePatches => Construction.ReplacementPatch is { } patch? [SurfacePatchMetadata.From(patch, Body.Topology.Faces.FirstOrDefault(face =>@@ -100,8 +178,14 @@ public sealed record OffsetRegionOperation(SpatialInfluenceEnvelope InfluenceEnvelope,IReadOnlyList<PreservationContract> Preserves,IReadOnlyList<SculptRequirement> Requirements,- string BoundaryContinuity = "G0")+ string BoundaryContinuity = "G0") : IConstructionOperation{+ public string OperationKind => "OffsetRegion";+ public int SchemaVersion => 1;+ public IReadOnlyList<string> Reads => [TargetRegion, .. Preserves.Select(item => item.EntityId)];+ public IReadOnlyList<string> MayModifySet => MayModify;+ public SpatialInfluenceEnvelope AuthorizedEnvelope => InfluenceEnvelope;+ public IReadOnlyList<PreservationContract> PreservationContracts => Preserves;public string Canonical => string.Join('|', StableId, TargetRegion, Offset.ToString("R"), RegionWidth.ToString("R"), RegionDepth.ToString("R"),string.Join(',', MayModify.Order(StringComparer.Ordinal)),$"{InfluenceEnvelope.MinX:R},{InfluenceEnvelope.MinY:R},{InfluenceEnvelope.MinZ:R},{InfluenceEnvelope.MaxX:R},{InfluenceEnvelope.MaxY:R},{InfluenceEnvelope.MaxZ:R}",@@ -119,8 +203,14 @@ public sealed record ReplaceRegionOperation(IReadOnlyList<SculptRequirement> Requirements,double GeometricTolerance = 1e-6,double G1AngularToleranceDegrees = 0.1,- double G2CurvatureTolerance = 1e-6)+ double G2CurvatureTolerance = 1e-6) : IConstructionOperation{+ public string OperationKind => "ReplaceRegion";+ public int SchemaVersion => 1;+ public IReadOnlyList<string> Reads => [TargetRegion, .. Preserves.Select(item => item.EntityId)];+ public IReadOnlyList<string> MayModifySet => MayModify;+ public SpatialInfluenceEnvelope AuthorizedEnvelope => InfluenceEnvelope;+ public IReadOnlyList<PreservationContract> PreservationContracts => Preserves;public string Canonical => string.Join('|', StableId, TargetRegion, ReplacementPatch.PatchId,ReplacementPatch.SurfaceClass, ReplacementPatch.DegreeU, ReplacementPatch.DegreeV,ReplacementPatch.ControlCountU, ReplacementPatch.ControlCountV,@@ -138,11 +228,62 @@ public sealed record SafeHoleOperation(HousingHole Hole,SpatialInfluenceEnvelope InfluenceEnvelope,IReadOnlyList<PreservationContract> Preserves,- IReadOnlyList<SculptRequirement> Requirements)+ IReadOnlyList<SculptRequirement> Requirements) : IConstructionOperation{+ public string OperationKind => "HoleFeature";+ public int SchemaVersion => 1;+ public IReadOnlyList<string> Reads => [TargetRegion, .. Preserves.Select(item => item.EntityId)];+ public IReadOnlyList<string> MayModifySet => [TargetRegion];+ public SpatialInfluenceEnvelope AuthorizedEnvelope => InfluenceEnvelope;+ public IReadOnlyList<PreservationContract> PreservationContracts => Preserves;public string Canonical => $"{StableId}|{TargetRegion}|{Hole.StableId}|{Hole.CenterX:R}|{Hole.CenterY:R}|{Hole.Diameter:R}|{InfluenceEnvelope.MinX:R},{InfluenceEnvelope.MinY:R},{InfluenceEnvelope.MinZ:R},{InfluenceEnvelope.MaxX:R},{InfluenceEnvelope.MaxY:R},{InfluenceEnvelope.MaxZ:R}";}+public enum SectionChainAttachmentPlacement { RelativeToSupport }++public sealed record SectionChainAttachment(+ string SupportRegion,+ string TerminalSectionId,+ SectionChainAttachmentPlacement Placement,+ IReadOnlyList<SectionSpanCorrespondence> BoundaryCorrespondence);++public sealed record AddSectionChainOperation(+ string StableId,+ SectionChain Chain,+ SectionChainAttachment Attachment,+ IReadOnlyList<string> MayModify,+ SpatialInfluenceEnvelope InfluenceEnvelope,+ IReadOnlyList<PreservationContract> Preserves,+ IReadOnlyList<SculptRequirement> Requirements) : IConstructionOperation+{+ public string OperationKind => "AddSectionChain";+ public int SchemaVersion => 1;+ public IReadOnlyList<string> Reads => [Attachment.SupportRegion, .. Preserves.Select(item => item.EntityId)];+ public IReadOnlyList<string> MayModifySet => MayModify;+ public SpatialInfluenceEnvelope AuthorizedEnvelope => InfluenceEnvelope;+ public IReadOnlyList<PreservationContract> PreservationContracts => Preserves;+ public string Canonical => $"{StableId}|{Chain.StableId}|{SectionChainCanonical.Fingerprint(Chain)}|{Attachment.SupportRegion}|{Attachment.TerminalSectionId}|{Attachment.Placement}|{CanonicalContract()}";+ private string CanonicalContract() => $"{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(item => item.EntityId, StringComparer.Ordinal).Select(item => $"{item.EntityId}:{item.Mode}"))}|{string.Join(',', Requirements.Order())}";+}++public sealed record RemoveSectionChainOperation(+ string StableId,+ SectionChain Chain,+ IReadOnlyList<string> SupportRegions,+ IReadOnlyList<string> MayModify,+ SpatialInfluenceEnvelope InfluenceEnvelope,+ IReadOnlyList<PreservationContract> Preserves,+ IReadOnlyList<SculptRequirement> Requirements) : IConstructionOperation+{+ public string OperationKind => "RemoveSectionChain";+ public int SchemaVersion => 1;+ public IReadOnlyList<string> Reads => [.. SupportRegions, .. Preserves.Select(item => item.EntityId)];+ public IReadOnlyList<string> MayModifySet => MayModify;+ public SpatialInfluenceEnvelope AuthorizedEnvelope => InfluenceEnvelope;+ public IReadOnlyList<PreservationContract> PreservationContracts => Preserves;+ public string Canonical => $"{StableId}|{Chain.StableId}|{SectionChainCanonical.Fingerprint(Chain)}|{string.Join(',', SupportRegions)}|{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(item => item.EntityId, StringComparer.Ordinal).Select(item => $"{item.EntityId}:{item.Mode}"))}|{string.Join(',', Requirements.Order())}";+}+public sealed record SculptDiagnostic(string Code, string Message, string? Entity = null);public sealed record SculptResult(bool IsSuccess, BodyState? OutputState, GeometricDelta? Delta, IReadOnlyList<SculptValidationEvidence> Evidence, IReadOnlyList<SculptDiagnostic> Diagnostics){diff --git a/Aetheris.Surfacing/SectionChainHousingBrepBuilder.cs b/Aetheris.Surfacing/SectionChainHousingBrepBuilder.csnew file mode 100644index 00000000..c1cd803e--- /dev/null+++ b/Aetheris.Surfacing/SectionChainHousingBrepBuilder.cs@@ -0,0 +1,255 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Geometry;+using Aetheris.Kernel.Core.Geometry.Curves;+using Aetheris.Kernel.Core.Geometry.Surfaces;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Core.Topology;++namespace Aetheris.Surfacing;++/// <summary>+/// SectionChain-specific shared-topology construction for the admitted X3b planar housing lane.+/// It never asks the generic Boolean classifier to rediscover attachment or penetration intent.+/// </summary>+internal static class SectionChainHousingBrepBuilder+{+ internal sealed record BuildResult(BrepBody? Body, SectionChain? RealizedChain, SectionChainPcurveEvidence? ToolPcurves,+ IReadOnlyList<SculptDiagnostic> Diagnostics);++ public static BuildResult BuildAddEast(HousingConstruction construction, SectionChain authored)+ {+ var placed = PlaceRelativeToEast(authored, construction.Width / 2d);+ var diagnostics = ValidateCommon(construction, placed).ToList();+ if (placed.StartTermination != SectionTermination.Open || placed.EndTermination != SectionTermination.Cap)+ diagnostics.Add(new("section-chain-add-termination-invalid", "The admitted east-support additive lane requires Open at the attached start and Cap at the free end."));+ if (diagnostics.Count == 0)+ {+ var expected = new[]+ {+ new Point3D(construction.Width / 2d, -construction.Depth / 2d, 0d),+ new Point3D(construction.Width / 2d, construction.Depth / 2d, 0d),+ new Point3D(construction.Width / 2d, construction.Depth / 2d, construction.BaseHeight),+ new Point3D(construction.Width / 2d, -construction.Depth / 2d, construction.BaseHeight),+ };+ if (!Matches(Points(placed.Sections[0]), expected))+ diagnostics.Add(new("section-chain-add-not-attached", "The attached terminal profile must exactly correspond to the complete HousingSideEast boundary in the admitted lane."));+ if (placed.Sections.Skip(1).SelectMany(Points).Any(point => point.X <= construction.Width / 2d + 1e-8d))+ diagnostics.Add(new("section-chain-add-remote-intersection", "Every non-terminal additive section must remain strictly outside HousingSideEast; a second body intersection was detected."));+ }+ return diagnostics.Count > 0 ? new(null, placed, null, diagnostics) : Build(construction, placed, additive: true);+ }++ public static BuildResult BuildRemoveThroughX(HousingConstruction construction, SectionChain chain)+ {+ var diagnostics = ValidateCommon(construction, chain).ToList();+ if (chain.StartTermination != SectionTermination.Open || chain.EndTermination != SectionTermination.Open)+ diagnostics.Add(new("section-chain-remove-termination-invalid", "The admitted through-duct lane requires Open terminations at both housing support faces."));+ if (diagnostics.Count == 0)+ {+ var sections = chain.Sections.Select(Points).ToArray();+ var west = -construction.Width / 2d; var east = construction.Width / 2d;+ if (sections[0].Any(point => Math.Abs(point.X - west) > 1e-6d)+ || sections[^1].Any(point => Math.Abs(point.X - east) > 1e-6d))+ diagnostics.Add(new("section-chain-remove-not-through", "RemoveSectionChain must terminate exactly on HousingSideWest and HousingSideEast."));+ if (sections.SelectMany(points => points).Any(point => point.Y <= -construction.Depth / 2d + 1e-6d+ || point.Y >= construction.Depth / 2d - 1e-6d || point.Z <= 1e-6d || point.Z >= construction.BaseHeight - 1e-6d))+ diagnostics.Add(new("section-chain-remove-disconnects-body", "The through-duct profile must remain strictly inside the housing Y/Z boundary so the result stays connected."));+ if (chain.Sections.Zip(chain.Sections.Skip(1), (a, b) => b.Frame.Origin.X - a.Frame.Origin.X).Any(delta => delta <= 1e-8d))+ diagnostics.Add(new("section-chain-remove-order-invalid", "Through-duct sections must progress monotonically from HousingSideWest to HousingSideEast."));+ foreach (var hole in construction.Holes)+ {+ var radius = hole.Diameter / 2d;+ if (sections.SelectMany(points => points).Any(point => Math.Abs(point.Y - hole.CenterY) <= radius + 1e-6d)+ && sections.SelectMany(points => points).Min(point => point.Z) <= construction.BaseHeight)+ diagnostics.Add(new("bodystate-preserved-region-modified", $"RemoveSectionChain intersects preserved mounting hole '{hole.StableId}'.", hole.StableId));+ }+ }+ return diagnostics.Count > 0 ? new(null, chain, null, diagnostics) : Build(construction, chain, additive: false);+ }++ private static BuildResult Build(HousingConstruction construction, SectionChain chain, bool additive)+ {+ var tool = SectionChainMaterializer.Materialize(chain);+ if (!tool.IsSuccess)+ return new(null, chain, tool.Pcurves, tool.Diagnostics.Select(item => new SculptDiagnostic(item.Code, item.Message, chain.StableId)).ToArray());++ var builder = new TopologyBuilder();+ var points = new Dictionary<VertexId, Point3D>();+ var curves = new Dictionary<EdgeId, (CurveGeometry Curve, ParameterInterval Interval)>();+ var faces = new List<(FaceId Face, SurfaceGeometry Surface)>();+ var bottom = HousingSection(construction.Width, construction.Depth, 0d);+ var top = HousingSection(construction.Width, construction.Depth, construction.BaseHeight);+ var vb = bottom.Select(point => AddVertex(point)).ToArray();+ var vt = top.Select(point => AddVertex(point)).ToArray();+ var eb = Enumerable.Range(0, 4).Select(index => AddLine(vb[index], vb[(index + 1) % 4])).ToArray();+ var et = Enumerable.Range(0, 4).Select(index => AddLine(vt[index], vt[(index + 1) % 4])).ToArray();+ var ev = Enumerable.Range(0, 4).Select(index => AddLine(vb[index], vt[index])).ToArray();++ var bottomHoleEdges = new EdgeId[construction.Holes.Count];+ var topHoleEdges = new EdgeId[construction.Holes.Count];+ var seamEdges = new EdgeId[construction.Holes.Count];+ for (var index = 0; index < construction.Holes.Count; index++)+ {+ var hole = construction.Holes[index]; var seamX = hole.CenterX + hole.Diameter / 2d;+ var bottomSeam = AddVertex(new(seamX, hole.CenterY, 0d));+ var topSeam = AddVertex(new(seamX, hole.CenterY, construction.BaseHeight));+ bottomHoleEdges[index] = AddCircle(bottomSeam, hole, 0d);+ topHoleEdges[index] = AddCircle(topSeam, hole, construction.BaseHeight);+ seamEdges[index] = AddLine(bottomSeam, topSeam);+ }++ var chainPoints = chain.Sections.Select(Points).ToArray();+ var chainVertices = new VertexId[chain.Sections.Count][];+ var chainEdges = new DirectedEdge[chain.Sections.Count][];+ for (var section = 0; section < chain.Sections.Count; section++)+ {+ if (additive && section == 0)+ {+ chainVertices[section] = [vb[1], vb[2], vt[2], vt[1]];+ chainEdges[section] = [new(eb[1], true), new(ev[2], true), new(et[1], false), new(ev[1], false)];+ continue;+ }+ chainVertices[section] = chainPoints[section].Select(AddVertex).ToArray();+ chainEdges[section] = Enumerable.Range(0, 4).Select(index =>+ new DirectedEdge(AddLine(chainVertices[section][index], chainVertices[section][(index + 1) % 4]), true)).ToArray();+ }++ var longitudinal = new EdgeId[chain.Sections.Count - 1][];+ for (var transition = 0; transition < longitudinal.Length; transition++)+ longitudinal[transition] = Enumerable.Range(0, 4).Select(index => AddLine(chainVertices[transition][index], chainVertices[transition + 1][index])).ToArray();++ var bottomLoops = new List<LoopId> { AddLoop(eb.Select(edge => new Use(edge, false)).ToArray()) };+ var topLoops = new List<LoopId> { AddLoop(et.Select(edge => new Use(edge, true)).Reverse().ToArray()) };+ for (var index = 0; index < construction.Holes.Count; index++)+ {+ bottomLoops.Add(AddLoop([new(bottomHoleEdges[index], true)]));+ topLoops.Add(AddLoop([new(topHoleEdges[index], false)]));+ }+ faces.Add((builder.AddFace(bottomLoops), SurfaceGeometry.FromPlane(new PlaneSurface(Point3D.Origin, Dir(0, 0, -1), Dir(1, 0, 0)))));+ faces.Add((builder.AddFace(topLoops), SurfaceGeometry.FromPlane(new PlaneSurface(new(0, 0, construction.BaseHeight), Dir(0, 0, 1), Dir(1, 0, 0)))));++ for (var side = 0; side < 4; side++)+ {+ if (additive && side == 1) continue;+ var next = (side + 1) % 4;+ var loops = new List<LoopId> { AddLoop([new(eb[side], false), new(ev[next], false), new(et[side], true), new(ev[side], true)]) };+ if (!additive && side == 3)+ loops.Add(AddLoop(chainEdges[0].Select(edge => new Use(edge.Edge, !edge.Forward)).ToArray()));+ if (!additive && side == 1)+ loops.Add(AddLoop(chainEdges[^1].Reverse().Select(edge => new Use(edge.Edge, edge.Forward)).ToArray()));+ var edge = bottom[next] - bottom[side]; var rise = top[side] - bottom[side];+ faces.Add((builder.AddFace(loops), SurfaceGeometry.FromPlane(new PlaneSurface(bottom[side], Direction3D.Create(edge.Cross(rise)), Direction3D.Create(edge)))));+ }++ for (var transition = 0; transition < longitudinal.Length; transition++)+ for (var span = 0; span < 4; span++)+ {+ var next = (span + 1) % 4; IReadOnlyList<Use> uses;+ if (additive)+ uses = [Cycle(chainEdges[transition][span], true), new(longitudinal[transition][next], false),+ Cycle(chainEdges[transition + 1][span], false), new(longitudinal[transition][span], true)];+ else+ uses = [Cycle(chainEdges[transition][span], false), new(longitudinal[transition][span], false),+ Cycle(chainEdges[transition + 1][span], true), new(longitudinal[transition][next], true)];+ faces.Add((builder.AddFace([AddLoop(uses)]), TransitionSurface(chainPoints[transition][span], chainPoints[transition][next],+ chainPoints[transition + 1][span], chainPoints[transition + 1][next])));+ }++ if (additive)+ {+ var capUses = chainEdges[^1].Select(edge => Cycle(edge, true)).ToArray();+ var frame = chain.Sections[^1].Frame;+ faces.Add((builder.AddFace([AddLoop(capUses)]), SurfaceGeometry.FromPlane(new PlaneSurface(frame.Origin, frame.Normal, frame.XAxis))));+ }++ for (var index = 0; index < construction.Holes.Count; index++)+ {+ var loop = AddLoop([new(bottomHoleEdges[index], false), new(seamEdges[index], false), new(topHoleEdges[index], true), new(seamEdges[index], true)]);+ var hole = construction.Holes[index];+ faces.Add((builder.AddFace([loop]), SurfaceGeometry.FromCylinder(new CylinderSurface(new(hole.CenterX, hole.CenterY, 0d), Dir(0, 0, 1), hole.Diameter / 2d, Dir(1, 0, 0)))));+ }++ var shell = builder.AddShell(faces.Select(face => face.Face).ToArray()); builder.AddBody([shell]);+ var geometry = new BrepGeometryStore(); var bindings = new BrepBindingModel(); var curveId = 1; var surfaceId = 1;+ foreach (var pair in curves.OrderBy(pair => pair.Key.Value))+ {+ var id = new CurveGeometryId(curveId++); geometry.AddCurve(id, pair.Value.Curve); bindings.AddEdgeBinding(new(pair.Key, id, pair.Value.Interval));+ }+ foreach (var face in faces)+ {+ var id = new SurfaceGeometryId(surfaceId++); geometry.AddSurface(id, face.Surface); bindings.AddFaceBinding(new(face.Face, id));+ }+ var body = new BrepBody(builder.Model, geometry, bindings, points);+ var pcurveBuild = BoundedPcurveBuilder.Populate(builder.Model, geometry, bindings, 1e-5d);+ if (!pcurveBuild.IsSuccess) return new(null, chain, tool.Pcurves, pcurveBuild.Diagnostics);+ var binding = BrepBindingValidator.Validate(body, true);+ if (!binding.IsSuccess) return new(null, chain, tool.Pcurves, binding.Diagnostics.Select(item => new SculptDiagnostic("section-chain-brep-invalid", item.Message)).ToArray());+ var pcurves = BrepPcurveValidator.Validate(body, 1e-5d, requireEveryCoedge: true);+ if (!pcurves.IsValid) return new(null, chain, tool.Pcurves, pcurves.Diagnostics.Select(message => new SculptDiagnostic("section-chain-pcurve-error", message)).ToArray());+ return new(body, chain, tool.Pcurves, []);++ VertexId AddVertex(Point3D point) { var vertex = builder.AddVertex(); points[vertex] = point; return vertex; }+ EdgeId AddLine(VertexId start, VertexId end)+ {+ var edge = builder.AddEdge(start, end); var vector = points[end] - points[start];+ curves[edge] = (CurveGeometry.FromLine(new Line3Curve(points[start], Direction3D.Create(vector))), new(0d, vector.Length)); return edge;+ }+ EdgeId AddCircle(VertexId seam, HousingHole hole, double z)+ {+ var edge = builder.AddEdge(seam, seam);+ curves[edge] = (CurveGeometry.FromCircle(new Circle3Curve(new(hole.CenterX, hole.CenterY, z), Dir(0, 0, 1), hole.Diameter / 2d, Dir(1, 0, 0))), new(0d, 2d * Math.PI)); return edge;+ }+ LoopId AddLoop(IReadOnlyList<Use> uses)+ {+ var loop = builder.AllocateLoopId(); var coedges = uses.Select(_ => builder.AllocateCoedgeId()).ToArray();+ for (var index = 0; index < coedges.Length; index++) builder.AddCoedge(new(coedges[index], uses[index].Edge, loop,+ coedges[(index + 1) % coedges.Length], coedges[(index + coedges.Length - 1) % coedges.Length], uses[index].Reversed));+ builder.AddLoop(new Loop(loop, coedges)); return loop;+ }+ }++ private static IEnumerable<SculptDiagnostic> ValidateCommon(HousingConstruction construction, SectionChain chain)+ {+ if (construction.HasCrown || construction.ReplacementPatch is not null)+ yield return new("section-chain-housing-base-unsupported", "The admitted X3b composition lane requires a planar uncrowned Housing base; replay fails closed for upstream crown/patch changes.");+ if (chain.Sections.Count < 2) yield return new("section-chain-section-count-invalid", "SectionChain requires at least two sections.");+ if (chain.TransitionPolicy != SectionTransitionPolicy.Ruled) yield return new("section-chain-transition-policy-invalid", "Only Ruled transitions are admitted.");+ foreach (var section in chain.Sections)+ {+ if (section.Profile.Spans.Count != 4 || section.Profile.Spans.Any(span => span.Curve is not SectionProfileCurve.Line))+ yield return new("section-chain-profile-topology-unsupported", $"Section '{section.SectionId}' must contain four ordered line spans in the bounded housing composition lane.", section.SectionId);+ if (Math.Abs(section.Frame.Normal.ToVector().Dot(new Vector3D(1, 0, 0)) - 1d) > 1e-8d)+ yield return new("section-chain-frame-unsupported", $"Section '{section.SectionId}' must use +X progression for the admitted housing lane.", section.SectionId);+ }+ }++ private static SectionChain PlaceRelativeToEast(SectionChain chain, double supportX) => chain with+ {+ Sections = chain.Sections.Select(section => section with+ {+ Frame = section.Frame with { Origin = new(section.Frame.Origin.X + supportX, section.Frame.Origin.Y, section.Frame.Origin.Z) }+ }).ToArray()+ };++ private static Point3D[] Points(Section section) => section.Profile.Spans.Select(span =>+ section.Frame.Transform(((SectionProfileCurve.Line)span.Curve).Start)).ToArray();+ private static bool Matches(IReadOnlyList<Point3D> actual, IReadOnlyList<Point3D> expected) => actual.Count == expected.Count+ && actual.Zip(expected).All(pair => (pair.First - pair.Second).Length <= 1e-6d);+ private static Point3D[] HousingSection(double width, double depth, double z)+ {+ var x = width / 2d; var y = depth / 2d; return [new(-x, -y, z), new(x, -y, z), new(x, y, z), new(-x, y, z)];+ }+ private static SurfaceGeometry TransitionSurface(Point3D a, Point3D b, Point3D c, Point3D d)+ {+ var normal = (b - a).Cross(c - a);+ if (normal.Length > 1e-10d && Math.Abs((d - a).Dot(normal / normal.Length)) <= 1e-8d)+ return SurfaceGeometry.FromPlane(new PlaneSurface(a, Direction3D.Create(normal), Direction3D.Create(b - a)));+ var spline = new BSplineSurfaceWithKnots(1, 1, [[a, b], [c, d]], "UNSPECIFIED", false, false, false,+ [2, 2], [2, 2], [0d, 1d], [0d, 1d], "UNSPECIFIED");+ return SurfaceGeometry.FromBSplineSurfaceWithKnots(spline);+ }+ private static Use Cycle(DirectedEdge edge, bool forward) => new(edge.Edge, forward ? !edge.Forward : edge.Forward);+ private static Direction3D Dir(double x, double y, double z) => Direction3D.Create(new Vector3D(x, y, z));+ private readonly record struct DirectedEdge(EdgeId Edge, bool Forward);+ private readonly record struct Use(EdgeId Edge, bool Reversed);+}diff --git a/Aetheris.Surfacing/SectionChainSculpting.cs b/Aetheris.Surfacing/SectionChainSculpting.csnew file mode 100644index 00000000..59f2d358--- /dev/null+++ b/Aetheris.Surfacing/SectionChainSculpting.cs@@ -0,0 +1,160 @@+using Aetheris.Kernel.Core.Brep;+using Aetheris.Kernel.Core.Brep.Verification;+using Aetheris.Kernel.Core.Math;++namespace Aetheris.Surfacing;++public static class AddSectionChainSculptor+{+ public static SculptResult Apply(BodyState input, string outputName, AddSectionChainOperation operation)+ {+ ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(operation);+ var diagnostics = ValidateContract(input, operation).ToList();+ var evidence = new List<SculptValidationEvidence>();+ var bounds = Bounds(operation.Chain, input.Construction.Width / 2d);+ if (!operation.InfluenceEnvelope.Contains(bounds, 1e-6d))+ diagnostics.Add(new("sculpt-outside-authorized-region", "AddSectionChain realized tool bounds exceed AuthorizedRegion.", operation.StableId));+ if (diagnostics.Count > 0) return SculptResult.Failure(diagnostics);++ var built = SectionChainHousingBrepBuilder.BuildAddEast(input.Construction, operation.Chain);+ if (built.Body is null) return SculptResult.Failure(built.Diagnostics);+ var bodyEvidence = SculptedHousingFactory.ValidateBody(built.Body, 1e-6d); evidence.AddRange(bodyEvidence);+ foreach (var failed in bodyEvidence.Where(item => !item.Satisfied)) diagnostics.Add(new("surf-body-invalid", $"{failed.Check}: {failed.Detail}"));+ var beforeMass = BrepMassProperties.Evaluate(input.Body); var afterMass = BrepMassProperties.Evaluate(built.Body);+ var volumeIncreased = beforeMass.IsEnclosed && afterMass.IsEnclosed && afterMass.AbsoluteVolume > beforeMass.AbsoluteVolume + 1e-6d;+ evidence.Add(new("AddSectionChainPositiveVolume", volumeIncreased, LocalityEvidenceLevel.CertifiedBounded,+ volumeIncreased ? afterMass.AbsoluteVolume - beforeMass.AbsoluteVolume : null, 1e-6d,+ $"before={beforeMass.AbsoluteVolume:R}; after={afterMass.AbsoluteVolume:R}; one shared-topology shell={built.Body.Topology.Shells.Count() == 1}."));+ if (!volumeIncreased) diagnostics.Add(new("section-chain-add-not-attached", "AddSectionChain did not produce a larger enclosed one-body result."));++ var inventory = input.SemanticInventory.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal);+ inventory.Remove(operation.Attachment.SupportRegion);+ var successor = $"{operation.Chain.StableId}.AttachedSurface";+ inventory[successor] = new(successor, SculptEntityKind.Region, SectionChainCanonical.Fingerprint(built.RealizedChain!),+ $"AddSectionChain successor of {operation.Attachment.SupportRegion} with {operation.Chain.Sections.Count} sections.");+ VerifyPreservation(input, inventory, operation.Preserves, evidence, diagnostics);+ evidence.Add(new("AuthorizedLocality", true, LocalityEvidenceLevel.ExactSemantic, 0d, 1e-6d,+ "Direct construction changed only HousingSideEast and the analytically bounded SectionChain envelope; no topology rediscovery or remote intersection is admitted."));+ if (diagnostics.Count > 0 || evidence.Any(item => !item.Satisfied)) return SculptResult.Failure(diagnostics, evidence);++ var outputId = BodyStateId.Derive($"{input.StateId.Value}|AddSectionChain|{operation.Canonical}");+ var correspondence = operation.Preserves.Select(contract => new GeometricDeltaEntry(contract.EntityId, GeometricChangeKind.Preserved, [contract.EntityId], "Exact semantic fingerprint retained during shared-topology graft."))+ .Append(new(operation.Attachment.SupportRegion, GeometricChangeKind.Replaced, [successor], "Explicit terminal-profile/support boundary correspondence; nearest-face rediscovery is prohibited."))+ .Append(new("<none>", GeometricChangeKind.Introduced, [operation.Chain.StableId], $"Typed {operation.Chain.Sections.Count}-section additive volume.")).ToArray();+ var delta = new GeometricDelta(input.StateId, outputId, operation.Reads, operation.Preserves.Select(item => item.EntityId).ToArray(),+ [operation.Attachment.SupportRegion], [], [operation.Chain.StableId], operation.MayModify, operation.InfluenceEnvelope, correspondence);+ var 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);+ return new(true, output, delta, evidence, []);+ }++ private static IEnumerable<SculptDiagnostic> ValidateContract(BodyState input, AddSectionChainOperation operation)+ {+ if (!input.SemanticInventory.ContainsKey(operation.Attachment.SupportRegion))+ yield return new("bodystate-operation-support-missing", $"AddSectionChain '{operation.StableId}' support '{operation.Attachment.SupportRegion}' is absent; replay will not guess a nearest face.", operation.Attachment.SupportRegion);+ if (!StringComparer.Ordinal.Equals(operation.Attachment.SupportRegion, SculptedHousingFactory.HousingSideEast))+ yield return new("section-chain-add-support-unsupported", "The admitted X3b additive lane supports HousingSideEast only.");+ if (operation.Chain.Sections.Count == 0 || !StringComparer.Ordinal.Equals(operation.Attachment.TerminalSectionId, operation.Chain.Sections[0].SectionId))+ yield return new("section-chain-add-terminal-invalid", "Attachment terminal must identify the first ordered Section in the admitted outward lane.");+ if (!operation.MayModify.Contains(operation.Attachment.SupportRegion, StringComparer.Ordinal))+ yield return new("sculpt-target-not-authorized", "AddSectionChain support is absent from MayModify.", operation.Attachment.SupportRegion);+ foreach (var preserve in operation.Preserves)+ if (!input.SemanticInventory.ContainsKey(preserve.EntityId)) yield return new("sculpt-preserve-unresolved", $"Preserved entity '{preserve.EntityId}' is absent.", preserve.EntityId);+ else if (operation.MayModify.Contains(preserve.EntityId, StringComparer.Ordinal)) yield return new("sculpt-breaks-preserved-interface", $"'{preserve.EntityId}' cannot be both modified and preserved.", preserve.EntityId);+ }++ internal static SpatialInfluenceEnvelope Bounds(SectionChain chain, double translateX = 0d)+ {+ var points = chain.Sections.SelectMany(section => section.Profile.Spans.Select(span => section.Frame.Transform(((SectionProfileCurve.Line)span.Curve).Start)))+ .Select(point => new Point3D(point.X + translateX, point.Y, point.Z)).ToArray();+ return new(points.Min(point => point.X), points.Min(point => point.Y), points.Min(point => point.Z),+ points.Max(point => point.X), points.Max(point => point.Y), points.Max(point => point.Z));+ }++ internal static void VerifyPreservation(BodyState input, IReadOnlyDictionary<string, SculptSemanticEntity> inventory,+ IReadOnlyList<PreservationContract> preserves, ICollection<SculptValidationEvidence> evidence, ICollection<SculptDiagnostic> diagnostics)+ {+ foreach (var contract in preserves)+ {+ var satisfied = input.SemanticInventory.TryGetValue(contract.EntityId, out var before) && inventory.TryGetValue(contract.EntityId, out var after)+ && before.StableId == after.StableId && before.GeometryFingerprint == after.GeometryFingerprint;+ evidence.Add(new($"Preserve:{contract.EntityId}", satisfied, LocalityEvidenceLevel.ExactSemantic, satisfied ? 0d : null, 1e-6d,+ satisfied ? $"Stable identity and {contract.Mode} fingerprint are identical." : "Protected identity or geometry fingerprint changed."));+ if (!satisfied) diagnostics.Add(new("bodystate-preserved-region-modified", $"Operation modified preserved region '{contract.EntityId}'.", contract.EntityId));+ }+ }+}++public static class RemoveSectionChainSculptor+{+ public static SculptResult Apply(BodyState input, string outputName, RemoveSectionChainOperation operation)+ {+ ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(operation);+ 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]."));+ foreach (var support in operation.SupportRegions)+ {+ if (!input.SemanticInventory.ContainsKey(support)) diagnostics.Add(new("bodystate-operation-support-missing", $"RemoveSectionChain '{operation.StableId}' support '{support}' is absent; replay will not guess a nearest face.", support));+ if (!operation.MayModify.Contains(support, StringComparer.Ordinal)) diagnostics.Add(new("sculpt-target-not-authorized", $"RemoveSectionChain support '{support}' is absent from MayModify.", support));+ }+ foreach (var preserve in operation.Preserves)+ if (!input.SemanticInventory.ContainsKey(preserve.EntityId)) diagnostics.Add(new("sculpt-preserve-unresolved", $"Preserved entity '{preserve.EntityId}' is absent.", preserve.EntityId));+ var bounds = AddSectionChainSculptor.Bounds(operation.Chain);+ if (!operation.InfluenceEnvelope.Contains(bounds, 1e-6d)) diagnostics.Add(new("sculpt-outside-authorized-region", "RemoveSectionChain tool bounds exceed AuthorizedRegion."));+ if (diagnostics.Count > 0) return SculptResult.Failure(diagnostics);++ var built = SectionChainHousingBrepBuilder.BuildRemoveThroughX(input.Construction, operation.Chain);+ if (built.Body is null) return SculptResult.Failure(built.Diagnostics);+ var bodyEvidence = SculptedHousingFactory.ValidateBody(built.Body, 1e-6d); evidence.AddRange(bodyEvidence);+ foreach (var failed in bodyEvidence.Where(item => !item.Satisfied)) diagnostics.Add(new("surf-body-invalid", $"{failed.Check}: {failed.Detail}"));+ var beforeMass = BrepMassProperties.Evaluate(input.Body); var afterMass = BrepMassProperties.Evaluate(built.Body);+ var removedVolume = EstimatedVolume(operation.Chain);+ var removed = beforeMass.IsEnclosed && afterMass.IsEnclosed && removedVolume > 1e-6d;+ evidence.Add(new("RemoveSectionChainPositiveVolume", removed, LocalityEvidenceLevel.CertifiedBounded,+ removed ? removedVolume : null, 1e-6d, $"section-prismoid removed-volume estimate={removedVolume:R}; before diagnostic mass={beforeMass.AbsoluteVolume:R}; after diagnostic mass={afterMass.AbsoluteVolume:R}; both shells enclosed={beforeMass.IsEnclosed && afterMass.IsEnclosed}."));+ if (!removed) diagnostics.Add(new("section-chain-remove-no-material", "RemoveSectionChain did not remove a positive bounded volume."));++ var inventory = input.SemanticInventory.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal);+ foreach (var support in operation.SupportRegions) inventory.Remove(support);+ var duct = $"{operation.Chain.StableId}.Duct";+ inventory[duct] = new(duct, SculptEntityKind.Region, SectionChainCanonical.Fingerprint(operation.Chain),+ $"Changing-profile through duct with {operation.Chain.Sections.Count} sections.");+ AddSectionChainSculptor.VerifyPreservation(input, inventory, operation.Preserves, evidence, diagnostics);+ evidence.Add(new("AuthorizedLocality", true, LocalityEvidenceLevel.ExactSemantic, 0d, 1e-6d,+ "Direct through-duct construction changed only the two explicit support trims and bounded SectionChain corridor."));+ if (diagnostics.Count > 0 || evidence.Any(item => !item.Satisfied)) return SculptResult.Failure(diagnostics, evidence);++ var outputId = BodyStateId.Derive($"{input.StateId.Value}|RemoveSectionChain|{operation.Canonical}");+ var correspondence = operation.Preserves.Select(contract => new GeometricDeltaEntry(contract.EntityId, GeometricChangeKind.Preserved, [contract.EntityId], "Exact semantic fingerprint retained during duct construction."))+ .Concat(operation.SupportRegions.Select(support => new GeometricDeltaEntry(support, GeometricChangeKind.Replaced, [$"{support}@{outputId.Value}"], "Explicit opening loop introduced on the selected support; old selector is stale.")))+ .Append(new(operation.Chain.StableId, GeometricChangeKind.Introduced, [duct], "Typed changing-profile removal corridor.")).ToArray();+ var delta = new GeometricDelta(input.StateId, outputId, operation.Reads, operation.Preserves.Select(item => item.EntityId).ToArray(),+ operation.SupportRegions, [], [duct], operation.MayModify, operation.InfluenceEnvelope, correspondence);+ var 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);+ return new(true, output, delta, evidence, []);+ }++ private static double EstimatedVolume(SectionChain chain)+ {+ static double Area(Section section)+ {+ var points = section.Profile.Spans.Select(span => ((SectionProfileCurve.Line)span.Curve).Start).ToArray(); var twice = 0d;+ for (var index = 0; index < points.Length; index++) { var next = points[(index + 1) % points.Length]; twice += points[index].X * next.Y - next.X * points[index].Y; }+ return Math.Abs(twice) / 2d;+ }+ var volume = 0d;+ for (var index = 0; index < chain.Sections.Count - 1; index++)+ {+ var a = Area(chain.Sections[index]); var b = Area(chain.Sections[index + 1]);+ var length = (chain.Sections[index + 1].Frame.Origin - chain.Sections[index].Frame.Origin).Length;+ volume += length * (a + b + Math.Sqrt(a * b)) / 3d;+ }+ return volume;+ }+}diff --git a/Aetheris.Surfacing/SectionChains.cs b/Aetheris.Surfacing/SectionChains.csindex c6934cc3..bac0d5ec 100644--- a/Aetheris.Surfacing/SectionChains.cs+++ b/Aetheris.Surfacing/SectionChains.cs@@ -5,6 +5,7 @@ using Aetheris.Kernel.Core.Geometry.Curves;using Aetheris.Kernel.Core.Geometry.Surfaces;using Aetheris.Kernel.Core.Math;using Aetheris.Kernel.Core.Topology;+using System.Text.Json.Serialization;namespace Aetheris.Surfacing;@@ -25,6 +26,10 @@ public sealed record SectionFrame(Point3D Origin, Direction3D XAxis, Direction3Dpublic Point3D Transform(SectionPoint2D point) => Origin + XAxis.ToVector() * point.X + YAxis.ToVector() * point.Y;}+[JsonPolymorphic(TypeDiscriminatorPropertyName = "$curveKind")]+[JsonDerivedType(typeof(SectionProfileCurve.Line), "Line")]+[JsonDerivedType(typeof(SectionProfileCurve.Arc), "Arc")]+[JsonDerivedType(typeof(SectionProfileCurve.PolynomialBSpline), "PolynomialBSpline")]public abstract record SectionProfileCurve{public sealed record Line(SectionPoint2D Start, SectionPoint2D End) : SectionProfileCurve;@@ -58,6 +63,25 @@ public sealed record SectionChain(SectionTermination StartTermination,SectionTermination EndTermination);+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)}";+ });+ return string.Join('|', chain.StableId, chain.TransitionPolicy, chain.StartTermination, chain.EndTermination, string.Join(';', sections));+ }+}+public sealed record SectionTransitionSurfaceEvidence(string SpanId,string SourceBoundaryId,diff --git a/docs/public/firmament/sculpting.md b/docs/public/firmament/sculpting.mdindex 311d3108..969ec7dd 100644--- a/docs/public/firmament/sculpting.md+++ b/docs/public/firmament/sculpting.md@@ -15,6 +15,10 @@ 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.+## X0 authoringThe current operation is `OffsetRegion`. The canonical controller-cover example is [`fixtures/Canonical/Sculpting/sculpted-housing.firmament`](../../../fixtures/Canonical/Sculpting/sculpted-housing.firmament):@@ -172,6 +176,29 @@ An invalid candidate never receives utility. The standard policy scores only eliThis utility judgment is a repeatable engineering selector, not proof of aesthetic superiority. Review highlight flow, unexpected flat spots, curvature bumps, creases, symmetry, locality, and mounting-interface preservation in a capable STEP viewer before aesthetic approval.+## X3b persistent SectionChain sculpting++The bounded additive form is:++```firmament+SculptState GripAdded {+ Input: Base+ AddSectionChain Grip {+ Chain: GripChain+ Support: HousingSideEast+ Terminal: Attach+ InfluenceEnvelope: [40mm, -20mm, 0mm, 100mm, 20mm, 20mm]+ }+ MayModify: [HousingSideEast]+ Preserve: [BottomMountingInterface, MountingHolePattern]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+}+```++In sculpting sources, the qualified compact chain form contains ordered `Station` blocks with +X `Origin` and rectangular `Size`; the first additive station is support-relative. The complete canonical fixture has five changing stations. `RemoveSectionChain` instead declares `Supports: [HousingSideWest, HousingSideEast]` and uses absolute monotonically increasing X stations for the through-duct corridor.++Support identity is semantic. Deleting or replacing it does not trigger nearest-face discovery; replay fails with `bodystate-operation-support-missing`. A wider housing keeps `HousingSideEast`, so the relative additive attachment translates deterministically when its authorized envelope still contains the result. Preservation and locality are rechecked on every replay. A safe `HoleFeature` after the admitted additive lane reconstructs the retained chain rather than erasing it.+## Guarantees and evidenceThe housing lane verifies:@@ -199,4 +226,4 @@ The X0 housing emits only `PLANE` and `CYLINDRICAL_SURFACE`. The X1 flagship add## Current limits-The admitted X2 materializer is limited to one rectangular housing crown transitioning to its coplanar analytic shoulder through the exact polynomial family above. It does not provide arbitrary intersection networks, general Plane/Cylinder or Cylinder/Cylinder blends, general Cylinder/B-spline or B-spline/B-spline discovery, arbitrary nested islands, variable blend laws, a free control-net optimizer, N-way junctions, Shell, Draft, or arbitrary patch networks. [SectionChain](section-chains.md) now has standalone Firmament text authoring and a ruled-loft materialization path, but BodyState `AddSectionChain`/`RemoveSectionChain` remain unqualified. Existing exact Fillet and Chamfer authoring and materializers are unchanged: a fillet is conceptually a constrained blend specialization, while a planar chamfer should remain planar rather than being forced through freeform machinery.+The admitted X2 materializer is limited to one rectangular housing crown transitioning to its coplanar analytic shoulder through the exact polynomial family above. It does not provide arbitrary intersection networks, general Plane/Cylinder or Cylinder/Cylinder blends, general Cylinder/B-spline or B-spline/B-spline discovery, arbitrary nested islands, variable blend laws, a free control-net optimizer, N-way junctions, Shell, Draft, or arbitrary patch networks. [SectionChain](section-chains.md) BodyState composition is limited to the documented planar east attachment and west-to-east through-duct lanes. Existing exact Fillet and Chamfer authoring and materializers are unchanged: a fillet is conceptually a constrained blend specialization, while a planar chamfer should remain planar rather than being forced through freeform machinery.diff --git a/docs/public/firmament/section-chains.md b/docs/public/firmament/section-chains.mdindex b9cbc909..e1ca72e7 100644--- a/docs/public/firmament/section-chains.md+++ b/docs/public/firmament/section-chains.md@@ -83,12 +83,23 @@ aetheris section-chain build fixtures/Canonical/SectionChain/eight-section-ergonOn a source checkout where the tool is not installed, replace `aetheris` with `dotnet run --project Aetheris.CLI -c Release --`.-The compatibility command also supports the generated `flagship`, `twist`, and `two-profile` witnesses. A build writes sibling `.evidence.json` containing section frames, spans, correspondence, transition classes, terminations, topology, pcurve qualification, conservative intersection evidence, timings, SHA-256, rational-surface count, and STEP reimport evidence.+The compatibility `section-chain build` command also supports the generated `flagship`, `twist`, and `two-profile` witnesses. That standalone command writes sibling `.evidence.json` containing section frames, spans, correspondence, transition classes, terminations, topology, pcurve qualification, conservative intersection evidence, timings, SHA-256, rational-surface count, and STEP reimport evidence. Ordinary X3b BodyState `build` instead writes the sculpting `.delta.json` construction/delta evidence described in the sculpting guide; it does not write both sibling formats.-`AddSectionChain` and `RemoveSectionChain` are not yet qualified BodyState operations. The current kernel's bounded Boolean families do not admit arbitrary changing ruled/B-spline tools, and the existing housing state rebuild would erase an attached chain during a downstream feature. A future admitted lane must construct a single shared-topology shell, retain chain history, enforce an authorized region and preservation contracts, and fail transactionally. These operations must not be represented publicly as arbitrary Boolean authoring.+SURF-X3b adds a bounded `BodyState` composition lane. `AddSectionChain` retains the chain, terminal Section, semantic support, span correspondence, authorized envelope, preservation contracts, and requirements as one typed replay operation. `RemoveSectionChain` retains the changing-profile tool and both explicit penetration supports. Neither lowers to public `Union` or `Difference`; a SectionChain-specific builder emits the known shared topology directly.++The admitted additive lane attaches an `Open` first terminal to the complete planar `HousingSideEast` boundary, progresses in support-relative +X, and caps the free end. The admitted subtractive lane runs an `Open/Open` four-line-span chain monotonically from `HousingSideWest` to `HousingSideEast`, strictly inside the housing Y/Z boundary. These restrictions make intended attachment, remote intersection, connectedness, and opening topology explicit and deterministic.++Canonical BodyState sources are [`surf-x3b-add-section-chain-grip.firmament`](../../../fixtures/Canonical/BodyState/surf-x3b-add-section-chain-grip.firmament) and [`surf-x3b-remove-section-chain-duct.firmament`](../../../fixtures/Canonical/BodyState/surf-x3b-remove-section-chain-duct.firmament). Build them with the ordinary command:++```powershell+aetheris build fixtures/Canonical/BodyState/surf-x3b-add-section-chain-grip.firmament --out artifacts/local/surf-x3b-add-section-chain-grip.step --json+aetheris build fixtures/Canonical/BodyState/surf-x3b-remove-section-chain-duct.firmament --out artifacts/local/surf-x3b-remove-section-chain-duct.step --json+```++The current canonical grip qualifies 24 faces, 50 edges, 28 vertices, and 100 pcurves after STEP reimport. The canonical duct qualifies 24 faces, 54 edges, 32 vertices, and 108 pcurves. These are regression evidence for the named fixtures, not general formulas for arbitrary chains.## Current limits-The admitted lane has one closed outer loop, no holes, same-topology one-to-one correspondence, ruled transitions, and Cap/Open terminals. It checks frame handedness, loop closure and orientation, sampled profile self-intersection, section spacing, semantic mapping order, sampled transition Jacobian foldover, non-neighbour transition crossings, and remote cap penetration using a deterministic validation-only triangle proxy. The proxy is conservative detection evidence, not a global proof. It does not claim general smooth lofting, rails, topology-changing correspondence, globally proven intersection freedom, or production arbitrary sculpt attachment/subtraction. Invalid chains fail closed rather than producing a faceted product fallback.+The standalone lane has one closed outer loop, no holes, same-topology one-to-one correspondence, ruled transitions, and Cap/Open terminals. It checks frame handedness, loop closure and orientation, sampled profile self-intersection, section spacing, semantic mapping order, sampled transition Jacobian foldover, non-neighbour transition crossings, and remote cap penetration using a deterministic validation-only triangle proxy. The proxy is conservative detection evidence, not a global proof. BodyState composition is additionally limited to the planar housing support lanes described above; arbitrary supports, rotated/non-four-line profiles, crown/patch predecessors, branches, G1/G2 continuity, and arbitrary freeform Boolean composition fail closed. Invalid chains never produce a faceted product fallback.Stable diagnostic families include `section-chain-correspondence-missing`, `section-chain-correspondence-duplicate`, `section-chain-profile-orientation-mismatch`, `section-chain-transition-foldover`, `section-chain-self-intersection`, and `section-chain-pcurve-error`. `section-chain validate` returns a nonzero exit status and emits no STEP when any of these blocks materialization. Transition identities are formatted `SourceSection->TargetSection` in structured evidence and diagnostic detail.diff --git a/docs/public/reference/diagnostics.md b/docs/public/reference/diagnostics.mdindex c4e523cb..f41fe493 100644--- a/docs/public/reference/diagnostics.md+++ b/docs/public/reference/diagnostics.md@@ -30,6 +30,19 @@- `surf-certified-bounds-invalid`: a claimed exact polynomial bounds certificate does not contain deterministic surface samples.- `surf-selector-target-replaced`: a historical native or imported selector has an explicit successor and cannot be reused.+## Construction-state replay and SectionChain sculpting (SURF-X3b)++- `bodystate-operation-replay-failed`: replay stopped atomically at the named typed operation; the reported predecessor remains authoritative.+- `bodystate-operation-order-invalid`: an operation's authored predecessor does not equal the preceding operation's authored output; replay does not reorder or guess intent.+- `bodystate-operation-version-unsupported`: the retained operation payload version is not admitted.+- `bodystate-operation-support-missing`: a semantic support read by an operation is absent; Aetheris does not guess a nearest face.+- `bodystate-preserved-region-modified`: realized construction touched a protected semantic region.+- `section-chain-add-not-attached`: the additive terminal does not exactly correspond to its support, or no positive connected volume resulted.+- `section-chain-add-remote-intersection`: a non-terminal additive section crosses the predecessor outside the intended attachment.+- `section-chain-remove-no-material`: the admitted removal corridor does not remove positive bounded material.+- `section-chain-remove-disconnects-body`: a duct reaches the protected outer boundary and would sever the admitted housing result.+- `section-chain-housing-base-unsupported`: an upstream crown/patch changed the predecessor outside the currently qualified planar composition lane.+Start with `aetheris validate source.firmament --json`; use `build` when geometry, AP242, assertions, or artifacts are involved. A diagnostic code is the stable automation key, while its message identifies the value/target and expected category where useful.Common recovery patterns:diff --git a/docs/public/reference/supported-features.md b/docs/public/reference/supported-features.mdindex e3c6172d..1a6c052b 100644--- a/docs/public/reference/supported-features.md+++ b/docs/public/reference/supported-features.md@@ -5,12 +5,12 @@| Area | Status | Preview 3 boundary ||---|---|---|| Firmament V2 native primitives/profiles | Bounded | Named Box/Cylinder/Frustum/RoundedBox and admitted line/arc profile construction/composition |-| Bounded mathematical sculpting | Bounded (SURF-X2 subset) | Immutable single-predecessor `BodyState`; rectangular-housing `OffsetRegion`; direct or imported-face `ReplaceRegion`; qualified crown-to-planar-shoulder `BlendBoundary` with hard G1/G2 evidence, four deterministic polynomial candidates, fairness/curvature/compactness/complexity judgment, override/fallback trace, qualified intersections and pcurves, exact lower-body locality, AP242 association persistence, and rational-free STEP. General blend networks remain unsupported. See the [sculpting guide](../firmament/sculpting.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). || 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 || Circular Sweep | Bounded (X0) | Open planar XY Concept Path, tangent line/arc segments, constant circular diameter, analytic cylinder/torus faces, capped solid; no general 3D/variable/rail/twist sweep |-| SectionChain ruled loft substrate | Experimental (SURF-X3a progression) | Firmament Concept Path/Profile authoring lowers into ordered framed, same-topology semantic SectionChain IR; one-to-one ruled transitions; shared internal edges; Cap/Open; strict face-local pcurves; deterministic validation-only non-neighbour/cap intersection detection; exact Plane and non-rational B-spline STEP with reimport. BodyState Add/Remove is not yet qualified. See [Section chains](../firmament/section-chains.md). |+| SectionChain ruled loft substrate | Bounded (SURF-X3b subset) | Firmament authoring lowers into ordered framed, same-topology semantic SectionChain IR; one-to-one ruled transitions; shared edges; Cap/Open; strict pcurves; deterministic intersection checks; persistent typed BodyState Add/Remove through documented planar housing lanes; no generic CSG authoring, rational product surface, or faceted fallback. See [Section chains](../firmament/section-chains.md). || Structural / weldment | Bounded (X2) | Explicit 3D nodes and straight paths; identifiable members; square/rectangular/round tube, angle, flat/round bar; orientation; catalog material; two-member butt and polygonal miter joints; semantic fillet welds; AP242 member assembly and deterministic JSON Cut List. No coping, curved routing, multi-member miter, connection design, weld analysis, or structural FEA. See [guide](../firmament/structural.md). || Semantic piping / routing | Bounded (X3a) | Logical connections; equipment-owned port Interfaces and hollow nozzle stubs; target-port-scoped owner KeepOut exemptions; coincident endpoint mates; explicit orthogonal 3D routes; deterministic A* proposals; editable accepted routes; 90-degree elbows; bounded local rerouting; AP242 assembly, BOM, and pipe Cut List. No freeform, stress-, flow-, slope-, or plant-scale routing. See [guide](../firmament/piping.md). || Boss | Bounded | First-class connected finite `On: Top` profile addition on an admitted Compose host; positive height; lowers through existing `Add`; no arbitrary solid union |diff --git a/docs/release/SURF-X3B-GENERALIZED-BODYSTATE.md b/docs/release/SURF-X3B-GENERALIZED-BODYSTATE.mdnew file mode 100644index 00000000..a0eecdc7--- /dev/null+++ b/docs/release/SURF-X3B-GENERALIZED-BODYSTATE.md@@ -0,0 +1,134 @@+# SURF-X3b — generalized BodyState construction authority++## Executive verdict++**Accepted for the documented bounded lanes.** `BodyState` now owns a versioned `ConstructionState` containing a generalized `BaseConstruction` and an ordered linear list of typed operations. Rebuild realizes the base and replays each operation transactionally. `AddSectionChain` and `RemoveSectionChain` are persistent semantic operations and use a SectionChain-specific shared-topology construction path, not public generic CSG history.++This is not a claim of arbitrary SectionChain/body composition. X3b qualifies one planar housing east-support addition and one west-to-east through-duct removal. Unsupported bases, supports, frame/profile topology, crowns/patch predecessors, or payload versions fail closed.++## Authority audit++Before X3b, `BodyState` stored a deterministic state ID, one predecessor ID, stable body ID, authored name, realized BRep, a mutated `HousingConstruction`, semantic inventory, the latest `GeometricDelta`, validation evidence, persistent geometry associations, AP242 PMI/interfaces, and optional blend judgment trace.++The mutated `HousingConstruction` was authoritative during rebuild. `OffsetRegion`, `ReplaceRegion`, `BlendBoundary`, and `HoleFeature` each produced a new recipe and called `SculptedHousingBrepBuilder.Build`. Offset/Replace/Blend/Hole therefore survived only insofar as their effect had been collapsed into housing fields. Blend retained judgment evidence but its selected patch was the actual rebuild input. Imported-face replacement mutated only a realized imported BRep and a housing-shaped evidence recipe; it did not have a process-independent generalized base authority. Standalone SectionChain materialization bypassed BodyState entirely. A transient SectionChain graft would consequently have been erased by the next housing rebuild.++Housing-specific assumptions were present in the `BodyState.Construction` type, every SURF sculptor's dimension checks, inventory/PMI construction, blend candidate realization, safe-hole rebuild, and CLI inspection shape. The generalized portion needed to be base identity, operation payload/identity, reads, authorization, preservation, predecessor/output relationship, replay, schema version, and failure semantics. Geometry realization can remain bounded per operation family.++## Old versus new authority++```text+Before+HousingConstruction -> BRep -> latest transient/mutated sculpt evidence++After+BaseConstruction + typed ConstructionOperation[]+ -> failure-atomic replay+ -> validated GeometricDelta/correspondence+ -> realized BRep evidence+```++`HousingBaseConstruction` is the first admitted base kind. The interface and versioned envelope no longer require all future states to be housing-derived; no unsupported imported/ordinary CAD base kind is falsely advertised yet.++## Construction-state contract++The schema is `aetheris.surfacing.construction-state` version 1. Every operation envelope retains `OperationId`, `OperationKind`, payload version, authored and output state relationship, typed payload, reads, `MayModify`, authorized envelope, preservation contracts, delta, validation evidence, and replay status. JSON serialization has explicit polymorphic base/operation/SectionProfileCurve discriminators and a normalized `Direction3D` converter.++Replay is linear geometric SSA. Full replay is the correctness baseline. Every operation after the first must name the preceding authored operation's output as its predecessor; reordered serialized operations fail with `bodystate-operation-order-invalid`. An operation order/payload/identity/version mismatch or a geometric validation failure emits `bodystate-operation-replay-failed`, returns no new output, and exposes the last accepted predecessor as authoritative. No BRep mutation from the failed operation is committed.++## Persistent operation table++| Operation | Persistent typed payload | Rebuild tested | Delta retained |+|---|---:|---:|---:|+| OffsetRegion | yes | yes, including JSON round-trip | yes |+| ReplaceRegion | yes | existing X1/X1a path plus generalized envelope | yes |+| BlendBoundary | yes; request, policy, candidates/selection evidence retained | yes; remains BlendBoundary rather than ReplaceRegion | yes, including judgment provenance |+| HoleFeature | yes | yes, before and after admitted additive sculpt | yes |+| AddSectionChain | yes; chain and attachment retained | yes, source/JSON/repeat replay | yes |+| RemoveSectionChain | yes; chain and penetration supports retained | yes, source/repeat replay | yes |++## SectionChain blocker closure++| X3a blocker | X3b result |+|---|---|+| arbitrary changing SectionChain not admitted in BodyState | bounded four-line-span ruled chains are admitted on explicit planar housing supports |+| HousingConstruction rebuild erases graft | construction authority replays the typed chain; a downstream safe hole uses retained chain construction |+| AddSectionChain unavailable | first-class Firmament operation, semantic terminal/support attachment, direct one-shell topology, replay and invalidation tests |+| RemoveSectionChain unavailable | first-class Firmament operation, explicit two-support through corridor, inner opening loops, reversed cavity shell, replay tests |++## Bounded kernel expansion++No generic freeform Boolean was added. `SectionChainHousingBrepBuilder` consumes known sections, support identity, attachment/penetration topology, and ordered span correspondence. It emits housing faces, shared attachment/opening edges, ruled transition faces, cap where applicable, hole cylinders, one shell, and face-local pcurves directly.++The admitted addition uses `HousingSideEast`, support-relative +X frames, an `Open` attached first section equal to the complete support boundary, strictly exterior later sections, and a `Cap` free end. The admitted removal uses `Open/Open`, monotonically increasing +X sections from `HousingSideWest` to `HousingSideEast`, and profiles strictly inside the Y/Z housing boundary. Four ordered line spans are admitted; each transition is exact planar when coplanar and the builder has a non-rational bilinear B-spline path when not. General freeform Booleans, rotated arbitrary supports, profile topology changes, crowns/replacement-patch predecessors, and G1/G2 remain fail-closed.++## Flagship evidence++| Evidence | Additive grip | Subtractive duct |+|---|---:|---:|+| BaseConstruction | `housing-base`, Housing/v1 | `housing-base`, Housing/v1 |+| operation | `GripAdded.AddSectionChain` | `DuctRemoved.RemoveSectionChain` |+| sections / transitions | 5 / 4 | 5 / 4 |+| support | `HousingSideEast`, terminal `Attach` | `HousingSideWest`, `HousingSideEast` |+| preserved | bottom mounting interface, mounting-hole pattern | bottom mounting interface, mounting-hole pattern |+| bodies / shells after | 1 / 1 | 1 / 1 |+| faces / edges / vertices after STEP reimport | 24 / 50 / 28 | 24 / 54 / 32 |+| pcurves / edges | 100 / 50 | 108 / 54 |+| maximum pcurve error | `1.464821375527116E-14` mm | `7.32410687763558E-15` mm |+| surface inventory | 22 Plane, 2 Cylinder | 22 Plane, 2 Cylinder |+| rational / faceted product fallback | 0 / 0 | 0 / 0 |+| structural reimport | enclosed manifold | enclosed manifold |+| state ID | `state-5ddd57c502db352b2ea0` | `state-5e2cb0816724ebbb96e5` |++The additive independent diagnostic volume increases from `64165.64418886558` to `86201.64418886561` cubic millimetres. The subtractive SectionChain prismoid estimate is `7630.959341876355` cubic millimetres. The generic tessellated mass diagnostic does not subtract inner loops reliably and is therefore not promoted to removal authority; enclosure, reversed cavity topology, two explicit openings, edge incidence, and the semantic prismoid calculation are the qualified evidence.++## Replay, locality, and preservation++For identical authority, initial, deserialized/reloaded, and repeat replay produce the same StateId and byte-identical STEP in tests. The additive attachment is support-relative: changing base width from 80 mm to 90 mm preserves semantic `HousingSideEast`, translates the chain, and derives a new deterministic state. Replacing the support with `DeletedSupport` produces `bodystate-operation-support-missing`; no proximity binding occurs.++Every rebuild rechecks `realized bounds subset-of AuthorizedRegion`, SectionChain self-intersection qualification, intended attachment/penetration, remote intersection constraints, enclosure/orientation/pcurves, operation requirements, and exact semantic preservation fingerprints. `GeometricDelta` explicitly marks preserved, replaced, and introduced identities. Old side-support selectors become stale because their explicit successors are recorded rather than name-matched.++## Multi-operation and downstream feature witnesses++[`surf-x3b-multi-operation-replay.firmament`](../../fixtures/Canonical/BodyState/surf-x3b-multi-operation-replay.firmament) retains and replays `HoleFeature -> HoleFeature -> AddSectionChain`. [`surf-x3b-safe-feature-after-add.firmament`](../../fixtures/Canonical/BodyState/surf-x3b-safe-feature-after-add.firmament) retains `AddSectionChain -> HoleFeature`; the second operation reconstructs the grip instead of reverting to housing-only geometry.++## Manual artifacts++Generated artifacts follow the local-artifact policy and are not committed:++| Artifact | SHA-256 |+|---|---|+| `artifacts/local/surf-x3b-add-section-chain-grip.step` | `BF38176C38E2C3B4251EF487E0C81A7F7FCD3CF7DF0477736D4461D80EFDE9A3` |+| `artifacts/local/surf-x3b-remove-section-chain-duct.step` | `0AD39A465F25A0AD5C51FCC688011CB699BE75725F901D81984192C90692C9FF` |+| `artifacts/local/surf-x3b-multi-operation-replay.step` | `214D353818FC039912C0B00B73E098405795A82CD1B7F1BB5518B12ED0BB3F7D` |++Reproduce them with `aetheris build fixtures/Canonical/BodyState/<fixture>.firmament --output artifacts/local/<name>.step`.++## Validation record++- `dotnet build Aetheris.slnx -c Release --no-restore -m:1`: passed with 0 warnings and 0 errors.+- `dotnet test Aetheris.slnx -c Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1`: 3,191 passed, 0 failed. The pre-existing `Aetheris.FrictionLab.Tests` assembly reports no discoverable tests; all other test assemblies passed.+- `scripts/Test-CanonicalFixtures.ps1 -NoBuild`: all 112 canonical fixtures passed. This includes the four X3b BodyState programs, all four standalone SectionChain fixtures, and `Integration/paperclip-maximizer.firmament`.+- Fresh packed CLI: `Aetheris.CLI.2.0.0-preview.3.nupkg` installed into an empty isolated tool path. Its source validator accepted both flagships with zero warnings/fatals; it then built, inspected, analyzed, and reimport-verified the additive flagship. STEP reimport was `Valid`, one body/one shell was retained, and the installed tool reproduced SHA-256 `BF38176C38E2C3B4251EF487E0C81A7F7FCD3CF7DF0477736D4461D80EFDE9A3`.+- The same packed CLI built and analyzed the subtractive flagship with zero build diagnostics and the expected `state-5e2cb0816724ebbb96e5`, one-body/one-shell enclosed-manifold result.+- The invalid missing-support fixture failed closed with process exit 1, no STEP output, and `bodystate-operation-support-missing` among its typed diagnostics.+- NativeAOT, Forge interop, browser client, and VS Code extension lanes were not run because X3b changes only the managed Surfacing/CLI path and its fixtures; no code or packaging contract in those lanes changed.++The canonical harness now declares the already-documented `plastic-shell-constant-section-feature-zero-draft` warning for the exact six PlasticShell fixtures that intentionally exercise zero-draft constant sections. Missing expected diagnostics and all undeclared warning/error/fatal diagnostics remain qualification failures.++## Fresh-agent authoring audit++Two clean-context agents independently read the public documentation and authored test programs without implementation guidance. Both selected the intended `SculptState` / typed SectionChain operation path, correctly distinguished Add from Remove terminal/support semantics, and predicted persistent replay and downstream-hole retention. Their only ambiguity was whether a wider base should move the east support symmetrically and whether subtractive station coordinates were support-relative. The public contract now states this explicitly: admitted Add stations are relative to the semantic east support; admitted Remove stations are absolute +X corridor stations spanning west to east. The audit also prompted clarification that standalone SectionChain emits `.evidence.json`, while BodyState build emits construction authority and delta in `.delta.json`.++## Known limits++- `HousingBaseConstruction` is the only realized base kind in X3b. The interface is generalized; imported STEP and ordinary CAD bases remain future admitted kinds.+- Imported-face adoption is not serialized as a generalized base and is not claimed as process-independent replay.+- Add/Remove composition deliberately excludes crown/ReplaceRegion predecessors and arbitrary support surfaces.+- The compact sculpting-source SectionChain form currently accepts ordered rectangular line-span `Station` values. Standalone Concept Path/Profile SectionChain authoring remains available through the SectionChain command.+- The subtractive mass-property verifier's tessellation route does not account for inner loops as occupied-volume subtraction; X3b reports that limitation rather than presenting its larger diagnostic magnitude as physical volume.+- Incremental prefix caching is not implemented; full replay remains the correctness path.+- G1/G2 SectionChain continuity, rails, arbitrary freeform Boolean completeness, and mesh product fallback remain non-goals.++## Manual review request++Inspect the additive STEP for terminal attachment quality, surface seams, slivers, remote changes, and whether the grip reads as one body. Inspect the subtractive STEP for continuous openings/corridor, internal membranes, taper progression, and preserved mounting geometry.diff --git a/fixtures/Canonical/BodyState/surf-x3b-add-section-chain-grip.firmament b/fixtures/Canonical/BodyState/surf-x3b-add-section-chain-grip.firmamentnew file mode 100644index 00000000..f6da760d--- /dev/null+++ b/fixtures/Canonical/BodyState/surf-x3b-add-section-chain-grip.firmament@@ -0,0 +1,41 @@+Model SurfX3bAddSectionChainGrip {+ Units: mm++ SectionChain GripChain {+ StartTermination: Open+ EndTermination: Cap+ Station Attach { Origin: [0mm, 0mm, 10mm]+ Size: [40mm, 20mm] }+ Station Neck { Origin: [10mm, 0mm, 10mm]+ Size: [34mm, 18mm] }+ Station PalmFront { Origin: [22mm, 0mm, 10mm]+ Size: [30mm, 16mm] }+ Station PalmRear { Origin: [36mm, 0mm, 10mm]+ Size: [24mm, 14mm] }+ Station Tail { Origin: [48mm, 0mm, 10mm]+ Size: [14mm, 10mm] }+ }++ 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, 100mm, 20mm, 20mm]+ }+ MayModify: [HousingSideEast]+ Preserve: [BottomMountingInterface, MountingHolePattern]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }++ Output: GripAdded+}diff --git a/fixtures/Canonical/BodyState/surf-x3b-multi-operation-replay.firmament b/fixtures/Canonical/BodyState/surf-x3b-multi-operation-replay.firmamentnew file mode 100644index 00000000..17ce6eea--- /dev/null+++ b/fixtures/Canonical/BodyState/surf-x3b-multi-operation-replay.firmament@@ -0,0 +1,55 @@+Model SurfX3bMultiOperationReplay {+ Units: mm++ SectionChain GripChain {+ StartTermination: Open+ EndTermination: Cap+ Station Attach { Origin: [0mm, 0mm, 10mm]+ Size: [40mm, 20mm] }+ Station Neck { Origin: [12mm, 0mm, 10mm]+ Size: [32mm, 18mm] }+ Station Palm { Origin: [28mm, 0mm, 10mm]+ Size: [25mm, 15mm] }+ Station Tail { Origin: [45mm, 0mm, 10mm]+ Size: [12mm, 9mm] }+ }++ BodyState Base {+ Size: [80mm, 40mm, 20mm]+ Hole MountA { Center: [-25mm, -12mm]+ Diameter: 4mm }+ Hole MountB { Center: [25mm, 12mm]+ Diameter: 4mm }+ }+ SculptState HoleOne {+ Input: Base+ HoleFeature AuxOne { Target: HousingCrown+ Id: AuxOne+ Center: [-10mm, 10mm]+ Diameter: 3mm+ InfluenceEnvelope: [-11.5mm, 8.5mm, 0mm, -8.5mm, 11.5mm, 20mm] }+ Preserve: [OuterFootprintBoundary]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ SculptState HoleTwo {+ Input: HoleOne+ HoleFeature AuxTwo { Target: HousingCrown+ Id: AuxTwo+ Center: [10mm, -10mm]+ Diameter: 3mm+ InfluenceEnvelope: [8.5mm, -11.5mm, 0mm, 11.5mm, -8.5mm, 20mm] }+ Preserve: [OuterFootprintBoundary]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ SculptState GripAdded {+ Input: HoleTwo+ AddSectionChain Grip { Chain: GripChain+ Support: HousingSideEast+ Terminal: Attach+ InfluenceEnvelope: [40mm, -20mm, 0mm, 85mm, 20mm, 20mm] }+ MayModify: [HousingSideEast]+ Preserve: [BottomMountingInterface, MountingHolePattern]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }+ Output: GripAdded+}diff --git a/fixtures/Canonical/BodyState/surf-x3b-remove-section-chain-duct.firmament b/fixtures/Canonical/BodyState/surf-x3b-remove-section-chain-duct.firmamentnew file mode 100644index 00000000..5079418b--- /dev/null+++ b/fixtures/Canonical/BodyState/surf-x3b-remove-section-chain-duct.firmament@@ -0,0 +1,40 @@+Model SurfX3bRemoveSectionChainDuct {+ Units: mm++ SectionChain DuctChain {+ StartTermination: Open+ EndTermination: Open+ Station West { Origin: [-40mm, 0mm, 10mm]+ Size: [10mm, 8mm] }+ Station Entry { Origin: [-20mm, 0mm, 10mm]+ Size: [13mm, 9mm] }+ Station Center { Origin: [0mm, 0mm, 10mm]+ Size: [12mm, 10mm] }+ Station Exit { Origin: [20mm, 0mm, 10mm]+ Size: [9mm, 7mm] }+ Station East { Origin: [40mm, 0mm, 10mm]+ Size: [11mm, 8mm] }+ }++ BodyState Base {+ Size: [80mm, 40mm, 20mm]+ Hole MountA { Center: [-25mm, -12mm]+ Diameter: 4mm }+ Hole MountB { Center: [25mm, 12mm]+ Diameter: 4mm }+ }++ SculptState DuctRemoved {+ Input: Base+ RemoveSectionChain Duct {+ Chain: DuctChain+ Supports: [HousingSideWest, HousingSideEast]+ InfluenceEnvelope: [-40mm, -7mm, 5mm, 40mm, 7mm, 15mm]+ }+ MayModify: [HousingSideWest, HousingSideEast]+ Preserve: [BottomMountingInterface, MountingHolePattern]+ Require: [ClosedManifold, OrientationConsistency, NoSelfIntersection]+ }++ Output: DuctRemoved+}diff --git a/fixtures/Canonical/BodyState/surf-x3b-safe-feature-after-add.firmament b/fixtures/Canonical/BodyState/surf-x3b-safe-feature-after-add.firmamentnew file mode 100644index 00000000..8cc659cb--- /dev/null+++ b/fixtures/Canonical/BodyState/surf-x3b-safe-feature-after-add.firmament@@ -0,0 +1,41 @@+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]+ }+ Output: PortAdded+}diff --git a/fixtures/Canonical/coverage.json b/fixtures/Canonical/coverage.jsonindex 289cb843..4852e4fb 100644--- a/fixtures/Canonical/coverage.json+++ b/fixtures/Canonical/coverage.json@@ -36,6 +36,10 @@"ReplaceRegion": "Sculpting/surf-x1-freeform-housing.firmament","PatchG1": "Sculpting/surf-x1-freeform-housing.firmament","PostSculptHole": "Sculpting/surf-x1-freeform-housing.firmament",+ "ConstructionStateReplay": "BodyState/surf-x3b-multi-operation-replay.firmament",+ "AddSectionChain": "BodyState/surf-x3b-add-section-chain-grip.firmament",+ "RemoveSectionChain": "BodyState/surf-x3b-remove-section-chain-duct.firmament",+ "PostSectionChainHole": "BodyState/surf-x3b-safe-feature-after-add.firmament","SurfaceIntersection": "Sculpting/surf-x1a-trimmed-freeform-housing.firmament","Pcurve": "Sculpting/surf-x1a-trimmed-freeform-housing.firmament","InnerTrimLoops": "Sculpting/surf-x1a-trimmed-freeform-housing.firmament",diff --git a/fixtures/Canonical/qualification.json b/fixtures/Canonical/qualification.jsonindex 2acfe63d..e23b53ea 100644--- a/fixtures/Canonical/qualification.json+++ b/fixtures/Canonical/qualification.json@@ -1,5 +1,13 @@{"schemaVersion": 1,+ "expectedDiagnostics": [+ { "path": "PlasticShell/plastic-shell-autorib-materialized.firmament", "codes": ["plastic-shell-constant-section-feature-zero-draft"] },+ { "path": "PlasticShell/plastic-shell-enclosure.firmament", "codes": ["plastic-shell-constant-section-feature-zero-draft"] },+ { "path": "PlasticShell/plastic-shell-materialized-enclosure.firmament", "codes": ["plastic-shell-constant-section-feature-zero-draft"] },+ { "path": "PlasticShell/plastic-shell-materialized-rib.firmament", "codes": ["plastic-shell-constant-section-feature-zero-draft"] },+ { "path": "PlasticShell/plastic-shell-materialized-standoff.firmament", "codes": ["plastic-shell-constant-section-feature-zero-draft"] },+ { "path": "PlasticShell/plastic-shell-rib-standoff-junction.firmament", "codes": ["plastic-shell-constant-section-feature-zero-draft"] }+ ],"actions": [{ "path": "Assembly", "operation": "assembly-inspect" },{ "path": "Drawings", "operation": "drawing-compile" },@@ -7,6 +15,8 @@{ "path": "Materials", "operation": "fea-solve" },{ "path": "SheetMetal", "operation": "sheet-metal-flatten" },{ "path": "Sculpting", "operation": "build-step" },+ { "path": "BodyState", "operation": "build-step" },+ { "path": "SectionChain", "operation": "section-chain-build" },{ "path": "Structural", "operation": "build-step" },{ "path": "Piping", "operation": "build-step" },{ "path": "PlasticShell", "operation": "build-step" },diff --git a/fixtures/Invalid/BodyState/surf-x3b-missing-support.firmament b/fixtures/Invalid/BodyState/surf-x3b-missing-support.firmamentnew file mode 100644index 00000000..eedaf1b8--- /dev/null+++ b/fixtures/Invalid/BodyState/surf-x3b-missing-support.firmament@@ -0,0 +1,27 @@+Model SurfX3bMissingSupport {+ Units: mm+ SectionChain GripChain {+ StartTermination: Open+ EndTermination: Cap+ Station Attach { Origin: [0mm, 0mm, 10mm]+ Size: [40mm, 20mm] }+ Station Tail { Origin: [20mm, 0mm, 10mm]+ Size: [12mm, 8mm] }+ }+ BodyState Base {+ Size: [80mm, 40mm, 20mm]+ Hole MountA { Center: [-25mm, -12mm]+ Diameter: 4mm }+ }+ SculptState InvalidGrip {+ Input: Base+ AddSectionChain Grip { Chain: GripChain+ Support: DeletedSupport+ Terminal: Attach+ InfluenceEnvelope: [40mm, -20mm, 0mm, 60mm, 20mm, 20mm] }+ MayModify: [DeletedSupport]+ Preserve: [BottomMountingInterface]+ Require: [ClosedManifold]+ }+ Output: InvalidGrip+}diff --git a/scripts/Test-CanonicalFixtures.ps1 b/scripts/Test-CanonicalFixtures.ps1index 65556f00..70eeb4f4 100644--- a/scripts/Test-CanonicalFixtures.ps1+++ b/scripts/Test-CanonicalFixtures.ps1@@ -28,7 +28,7 @@ $forbidden = @()$failures = [Collections.Generic.List[string]]::new()-$requiredFeatures = @('Box', 'Cylinder', 'Sphere', 'Cone', 'Torus', 'Profile', 'Sweep', 'Paperclip', 'Boss', 'Pocket', 'Hole', 'BlindHole', 'Counterbore', 'Countersink', 'Slot', 'Pattern', 'Chamfer', 'Fillet', 'Material', 'PMI', 'Template', 'SheetMetal', 'FEA', 'inlineSTEP', 'Assembly', 'Piping')+$requiredFeatures = @('Box', 'Cylinder', 'Sphere', 'Cone', 'Torus', 'Profile', 'Sweep', 'Paperclip', 'Boss', 'Pocket', 'Hole', 'BlindHole', 'Counterbore', 'Countersink', 'Slot', 'Pattern', 'Chamfer', 'Fillet', 'Material', 'PMI', 'Template', 'SheetMetal', 'FEA', 'inlineSTEP', 'Assembly', 'Piping', 'ConstructionStateReplay', 'AddSectionChain', 'RemoveSectionChain', 'PostSectionChainHole')foreach ($feature in $requiredFeatures) {$entry = $coverage.features.$featureif ([string]::IsNullOrWhiteSpace($entry)) { $failures.Add("coverage: missing $feature"); continue }@@ -52,6 +52,7 @@ foreach ($file in Get-ChildItem -LiteralPath $canonicalRoot -Recurse -Filter '*.New-Item -ItemType Directory -Force -Path $outputDirectory | Out-Null$arguments = switch ($action.operation) {'build-step' { @('build', $file.FullName, '--output', (Join-Path $outputDirectory "$stem.step"), '--json') }+ 'section-chain-build' { @('section-chain', 'build', $file.FullName, '--out', (Join-Path $outputDirectory "$stem.step"), '--json') }'sheet-metal-flatten' { @('sheetmetal', 'flatten', $file.FullName, '--step', (Join-Path $outputDirectory "$stem-flat.step"), '--svg', (Join-Path $outputDirectory "$stem-flat.svg"), '--json') }'fea-solve' { @('fea', $file.FullName, '--out-dir', $outputDirectory, '--json') }'assembly-inspect' { @('asm', 'inspect', $file.FullName, '--json') }@@ -63,8 +64,22 @@ foreach ($file in Get-ChildItem -LiteralPath $canonicalRoot -Recurse -Filter '*.$failures.Add("${relative}: $($action.operation) exited $LASTEXITCODE`n$output")continue}- if ($output -match '"severity"\s*:\s*"(?:warning|error|fatal)"') {- $failures.Add("${relative}: qualification emitted a warning/error diagnostic`n$output")+ try {+ $result = $output | ConvertFrom-Json+ }+ catch {+ $failures.Add("${relative}: qualification did not emit valid JSON`n$output")+ continue+ }+ $expectedEntry = $manifest.expectedDiagnostics | Where-Object { $_.path -eq $relative } | Select-Object -First 1+ $expectedCodes = @($expectedEntry.codes)+ $emitted = @($result.diagnostics | Where-Object { $_.severity -in @('warning', 'error', 'fatal') })+ $unexpected = @($emitted | Where-Object { $_.code -notin $expectedCodes })+ $missing = @($expectedCodes | Where-Object { $_ -notin @($emitted.code) })+ if ($unexpected.Count -gt 0 -or $missing.Count -gt 0) {+ $unexpectedCodes = @($unexpected.code) -join ', '+ $missingCodes = $missing -join ', '+ $failures.Add("${relative}: diagnostic contract mismatch (unexpected: [$unexpectedCodes]; missing: [$missingCodes])`n$output")continue}$qualified++