Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add CIR-BREP-X4 recognizer source-contract friction lab
Yuechen Li682c6442773d
diff --git a/Aetheris.Firmament.FrictionLab/CIRLab/CirBrepX4RecognizerSourceContractLab.cs b/Aetheris.Firmament.FrictionLab/CIRLab/CirBrepX4RecognizerSourceContractLab.csnew file mode 100644index 00000000..3652678e--- /dev/null+++ b/Aetheris.Firmament.FrictionLab/CIRLab/CirBrepX4RecognizerSourceContractLab.cs@@ -0,0 +1,122 @@+using System.Reflection;+using Aetheris.Kernel.Core.Cir;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament;+using Aetheris.Kernel.Firmament.Execution;+using Aetheris.Kernel.Firmament.Lowering;++namespace Aetheris.FrictionLab;++public sealed record CirBoxCylinderRecognizerInput(+ CirNode Root,+ NativeGeometryReplayLog? ReplayLog = null,+ NativeGeometryState? NativeState = null,+ FirmamentPrimitiveLoweringPlan? LoweringPlan = null,+ FirmamentPrimitiveExecutionResult? ExecutionResult = null,+ string? SourceLabel = null)+{+ public static CirBoxCylinderRecognizerInput FromNode(CirNode root, NativeGeometryReplayLog? replayLog = null, string? sourceLabel = null)+ => new(root, replayLog, null, null, null, sourceLabel);++ public static CirBoxCylinderRecognizerInput FromNativeState(NativeGeometryState nativeState, CirNode? root = null, string? sourceLabel = null)+ {+ ArgumentNullException.ThrowIfNull(nativeState);+ if (root is null)+ {+ throw new InvalidOperationException("NativeGeometryState does not contain a traversable CIR root; explicit CirNode root is required for geometric recognition.");+ }++ return new(root, nativeState.ReplayLog, nativeState, null, null, sourceLabel);+ }+}++public sealed record CirRecognizerSourceInventory(+ bool HasRootNode,+ bool HasLoweringPlan,+ bool HasExecutionResult,+ bool HasNativeGeometryState,+ bool HasReplayLog,+ bool HasCirMirrorSummary,+ string RootNodeKind,+ string? CirIntentRootReference);++public sealed record CirBoxCylinderRecognitionWithDiagnostics(+ CirBoxCylinderRecognitionLabResult Recognition,+ IReadOnlyList<string> Diagnostics,+ bool ReplayGeometryMismatch);++public static class CirBrepX4RecognizerSourceContractLab+{+ public static CirRecognizerSourceInventory BuildInventory(FirmamentCompilationArtifact compile, CirNode loweredRoot)+ {+ var execution = compile.PrimitiveExecutionResult;+ var state = execution?.NativeGeometryState;+ return new(+ HasRootNode: true,+ HasLoweringPlan: compile.PrimitiveLoweringPlan is not null,+ HasExecutionResult: execution is not null,+ HasNativeGeometryState: state is not null,+ HasReplayLog: state?.ReplayLog is not null,+ HasCirMirrorSummary: state?.CirMirror.Summary is not null,+ RootNodeKind: loweredRoot.Kind.ToString(),+ CirIntentRootReference: state?.CirIntentRootReference);+ }++ public static CirBoxCylinderRecognitionWithDiagnostics Recognize(CirBoxCylinderRecognizerInput input)+ {+ var recognition = CirBoxCylinderRecognitionLab.Recognize(input.Root, allowTranslationWrappers: true);+ var diagnostics = new List<string>();+ var mismatch = false;++ if (input.ReplayLog is null)+ {+ diagnostics.Add("Replay unavailable; provenance fields (op/feature/tool ids) not attached.");+ }+ else+ {+ var subtractOps = input.ReplayLog.Operations.Where(o => string.Equals(o.OperationKind, "boolean:subtract", StringComparison.Ordinal)).ToArray();+ if (subtractOps.Length == 0)+ {+ diagnostics.Add("Replay present but no boolean:subtract operations were found.");+ }++ var boxCylinderSubtract = subtractOps.FirstOrDefault(o => string.Equals(o.ToolKind, "cylinder", StringComparison.Ordinal));+ if (boxCylinderSubtract is not null)+ {+ diagnostics.Add($"Replay matched subtract op '{boxCylinderSubtract.FeatureId}' from '{boxCylinderSubtract.SourceFeatureId}'.");+ }+ else if (recognition.Success)+ {+ diagnostics.Add("Geometry recognized as box-cylinder, but replay did not confirm cylinder subtract tool kind.");+ mismatch = true;+ }++ if (!recognition.Success && boxCylinderSubtract is not null)+ {+ diagnostics.Add("Replay suggests subtract+cylinder provenance, but geometry was not recognized from CirNode.");+ mismatch = true;+ }+ }++ return new(recognition, diagnostics, mismatch);+ }++ public static CirLoweringResult LowerViaReflection(FirmamentPrimitiveLoweringPlan plan)+ {+ var lowererType = typeof(FirmamentCompiler).Assembly.GetType("Aetheris.Kernel.Firmament.Lowering.FirmamentCirLowerer");+ var method = lowererType?.GetMethod("Lower", BindingFlags.Public | BindingFlags.Static);+ var kernelResult = method?.Invoke(null, [plan]);+ if (kernelResult is null)+ {+ throw new InvalidOperationException("Unable to resolve FirmamentCirLowerer.Lower via reflection.");+ }++ dynamic result = kernelResult;+ if (!result.IsSuccess)+ {+ throw new InvalidOperationException("FirmamentCirLowerer.Lower returned failure.");+ }++ return (CirLoweringResult)result.Value;+ }+}diff --git a/Aetheris.FrictionLab.Tests/CIRLab/CirBrepX4RecognizerSourceContractLabTests.cs b/Aetheris.FrictionLab.Tests/CIRLab/CirBrepX4RecognizerSourceContractLabTests.csnew file mode 100644index 00000000..81c5f727--- /dev/null+++ b/Aetheris.FrictionLab.Tests/CIRLab/CirBrepX4RecognizerSourceContractLabTests.cs@@ -0,0 +1,132 @@+using Aetheris.FrictionLab;+using Aetheris.Kernel.Core.Cir;+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament;+using Aetheris.Kernel.Firmament.Execution;+using Aetheris.Kernel.Firmament.Lowering;++namespace Aetheris.FrictionLab.Tests.CIRLab;++public sealed class CirBrepX4RecognizerSourceContractLabTests+{+ [Fact]+ public void Experiment1_SourceInventory_CollectsAllCandidateSourcesForBooleanBoxCylinderHole()+ {+ var compile = CompileFixture();+ var lowered = CirBrepX4RecognizerSourceContractLab.LowerViaReflection(compile.PrimitiveLoweringPlan!);++ var inventory = CirBrepX4RecognizerSourceContractLab.BuildInventory(compile, lowered.Root);++ Assert.True(inventory.HasRootNode, "Lowered CirNode root must be available for direct geometric recognition.");+ Assert.True(inventory.HasLoweringPlan, "Lowering plan should be available in Firmament compilation artifact.");+ Assert.True(inventory.HasExecutionResult, "Execution result should be available after successful compile.");+ Assert.True(inventory.HasNativeGeometryState, "NativeGeometryState should be available from execution result.");+ Assert.True(inventory.HasReplayLog, "Replay log should be available as provenance source.");+ Assert.True(inventory.HasCirMirrorSummary, "CIR mirror summary should be available as envelope diagnostic.");+ }++ [Fact]+ public void Experiment2_NodeOnlyEnvelope_RecognizesDirectAndTransformWrappedSubtract_ButLacksProvenance()+ {+ var direct = new CirSubtractNode(new CirBoxNode(10, 10, 10), new CirCylinderNode(2, 12));+ var wrapped = new CirTransformNode(direct, Transform3D.CreateTranslation(new Vector3D(3, 0, 0)));++ var directResult = CirBrepX4RecognizerSourceContractLab.Recognize(CirBoxCylinderRecognizerInput.FromNode(direct));+ var wrappedResult = CirBrepX4RecognizerSourceContractLab.Recognize(CirBoxCylinderRecognizerInput.FromNode(wrapped));++ Assert.True(directResult.Recognition.Success, $"Node-only direct subtract should recognize; got {directResult.Recognition.Reason}: {directResult.Recognition.Diagnostic}");+ Assert.True(wrappedResult.Recognition.Success, $"Node-only wrapped subtract should recognize; got {wrappedResult.Recognition.Reason}: {wrappedResult.Recognition.Diagnostic}");+ Assert.Contains(directResult.Diagnostics, d => d.Contains("Replay unavailable", StringComparison.Ordinal));+ }++ [Fact]+ public void Experiment3_NodePlusReplay_PreservesRecognition_AndAddsProvenanceDiagnostics()+ {+ var compile = CompileFixture();+ var lowered = CirBrepX4RecognizerSourceContractLab.LowerViaReflection(compile.PrimitiveLoweringPlan!);+ var replay = compile.PrimitiveExecutionResult!.NativeGeometryState.ReplayLog;++ var result = CirBrepX4RecognizerSourceContractLab.Recognize(CirBoxCylinderRecognizerInput.FromNode(lowered.Root, replay));++ Assert.True(result.Recognition.Success, $"Node+replay should preserve geometric recognition; got {result.Recognition.Reason}: {result.Recognition.Diagnostic}");+ Assert.Contains(result.Diagnostics, d => d.Contains("Replay matched subtract op", StringComparison.Ordinal));+ Assert.False(result.ReplayGeometryMismatch, "Replay should match node geometry for canonical fixture.");+ }++ [Fact]+ public void Experiment4_NativeStateAlone_IsInsufficientWithoutExplicitRoot()+ {+ var compile = CompileFixture();+ var nativeState = compile.PrimitiveExecutionResult!.NativeGeometryState;++ var ex = Assert.Throws<InvalidOperationException>(() => CirBoxCylinderRecognizerInput.FromNativeState(nativeState));+ Assert.Contains("explicit CirNode root is required", ex.Message, StringComparison.Ordinal);++ var lowered = CirBrepX4RecognizerSourceContractLab.LowerViaReflection(compile.PrimitiveLoweringPlan!);+ var input = CirBoxCylinderRecognizerInput.FromNativeState(nativeState, lowered.Root);+ var recognized = CirBrepX4RecognizerSourceContractLab.Recognize(input);+ Assert.True(recognized.Recognition.Success, "NativeState wrapper with explicit root should recognize because geometry still comes from node.");+ }++ [Fact]+ public void Experiment5_LoweringPlanAndExecutionResult_AreUsefulEnvelopesButNotPrimaryGeometrySource()+ {+ var compile = CompileFixture();+ var plan = compile.PrimitiveLoweringPlan!;+ var execution = compile.PrimitiveExecutionResult!;++ Assert.Contains(plan.Booleans, b => b.Kind == FirmamentLoweredBooleanKind.Subtract && b.Tool.OpName == "cylinder");+ Assert.NotNull(execution.NativeGeometryState.ReplayLog);+ Assert.True(string.IsNullOrWhiteSpace(execution.NativeGeometryState.CirIntentRootReference) || execution.NativeGeometryState.CirIntentRootReference == "hole");+ }++ [Fact]+ public void Experiment6_MismatchPolicy_NodeGeometryIsAuthoritative_ReplayIsDiagnosticOnly()+ {+ var geometry = new CirSubtractNode(new CirBoxNode(10, 10, 10), new CirSphereNode(2));+ var replay = new NativeGeometryReplayLog([+ new NativeGeometryReplayOperation(2, "hole", "boolean:subtract", "base", "cylinder", "tool", null, default, "ref")+ ]);++ var result = CirBrepX4RecognizerSourceContractLab.Recognize(CirBoxCylinderRecognizerInput.FromNode(geometry, replay));++ Assert.False(result.Recognition.Success, "Node geometry should reject non-cylinder subtract even if replay claims cylinder tool kind.");+ Assert.True(result.ReplayGeometryMismatch, "Node/replay disagreement should be surfaced as mismatch diagnostic.");+ }++ [Fact]+ public void Experiment7_RecommendedInputShape_SupportsNodeOnlyAndNodePlusReplayConstruction()+ {+ var nodeInput = CirBoxCylinderRecognizerInput.FromNode(new CirSubtractNode(new CirBoxNode(8, 8, 8), new CirCylinderNode(1, 10)));+ Assert.NotNull(nodeInput.Root);+ Assert.Null(nodeInput.ReplayLog);++ var replay = new NativeGeometryReplayLog([]);+ var nodeReplayInput = CirBoxCylinderRecognizerInput.FromNode(nodeInput.Root, replay, "fixture");+ Assert.Same(replay, nodeReplayInput.ReplayLog);+ Assert.Equal("fixture", nodeReplayInput.SourceLabel);+ }++ private static FirmamentCompilationArtifact CompileFixture()+ {+ var root = ResolveRepoRoot();+ var absolute = Path.Combine(root, "testdata/firmament/examples/boolean_box_cylinder_hole.firmament");+ var source = File.ReadAllText(absolute);+ var compiler = new FirmamentCompiler();+ var result = compiler.Compile(new FirmamentCompileRequest(new FirmamentSourceDocument(source, absolute)));+ Assert.True(result.Compilation.IsSuccess, string.Join(" | ", result.Compilation.Diagnostics.Select(d => d.Message)));+ return result.Compilation.Value;+ }++ private static string ResolveRepoRoot()+ {+ var dir = new DirectoryInfo(AppContext.BaseDirectory);+ while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "AGENTS.md")))+ {+ dir = dir.Parent;+ }++ Assert.NotNull(dir);+ return dir!.FullName;+ }+}diff --git a/docs/frictionlab/cir-brep-x4-recognizer-source-contract-lab.md b/docs/frictionlab/cir-brep-x4-recognizer-source-contract-lab.mdnew file mode 100644index 00000000..25b42973--- /dev/null+++ b/docs/frictionlab/cir-brep-x4-recognizer-source-contract-lab.md@@ -0,0 +1,98 @@+# CIR-BREP-X4: recognizer source-shape contract lab++## 1) Setup verification+- Verified existing X3/X3.1 artifacts exist in `Aetheris.Firmament.FrictionLab/CIRLab/`, `Aetheris.FrictionLab.Tests/CIRLab/`, and docs reports.+- Verified previous CIRLab tests pass on net10.0 baseline before X4 changes.+- Kept all experiment code within FrictionLab-only folders.++## 2) Source APIs inspected+- CIR nodes: `CirNode`, `CirSubtractNode`, `CirTransformNode`, `CirBoxNode`, `CirCylinderNode`.+- Lowering/execution: `FirmamentPrimitiveLoweringPlan`, `FirmamentPrimitiveExecutor`, `FirmamentPrimitiveExecutionResult`, `FirmamentCirLowerer`.+- Native state: `NativeGeometryState`, `NativeGeometryReplayLog`, `NativeGeometryReplayOperation`, `NativeGeometryCirMirrorState`.+- Analysis/readiness: `CirNativeAnalysisService`, `MaterializationReadinessAnalyzer`.++## 3) Experiment 1 source inventory table+Fixture: `testdata/firmament/examples/boolean_box_cylinder_hole.firmament`.++| Source | Available at recognizer call site | Geometry tree | Dimensions/transforms | Provenance ids/tool/source | Sufficient alone | Diagnostic value |+|---|---|---:|---:|---:|---:|---:|+| Raw lowered `CirNode` root | Yes (via lowering) | Yes | Yes | No | Yes (v1 geometry) | Medium |+| `FirmamentPrimitiveLoweringPlan` | Yes | Indirect (needs lower) | Yes (parametric intent) | Feature-level intent | No | Medium |+| `FirmamentPrimitiveExecutionResult` | Yes | Indirect (via state only) | Partial | Yes | No | High |+| `NativeGeometryState` | Yes | No traversable root (only root reference string) | No direct tree | Yes | No | High |+| `NativeGeometryReplayLog` | Yes | No | No direct dimensions | Yes (best provenance) | No | High |+| `CirMirror` summary | Yes | No | Bounds + approximate volume only | No | No | Low/Medium |++## 4) Experiment 2 node-only envelope findings+- `FromNode(CirNode)` successfully recognizes canonical direct and translation-wrapped forms.+- Unsupported transforms still reject via existing recognizer behavior.+- Missing provenance is explicit: no op/feature/tool diagnostics without replay.+- Conclusion: node-only is sufficient for v1 **geometry classification**, not sufficient for richer diagnostics.++## 5) Experiment 3 node+replay findings+- `FromNode(CirNode, NativeGeometryReplayLog?)` preserves recognition parity with node-only.+- When replay exists, diagnostics can include subtract op / feature / source feature / tool kind context.+- Recognition still works when replay is absent.+- Mismatch policy validated: replay contradiction is surfaced as mismatch diagnostic; it does not override node geometry.+- Conclusion: replay should be optional in v1 API and treated as provenance/diagnostic layer.++## 6) Experiment 4 NativeGeometryState findings+- `NativeGeometryState` alone cannot provide traversable CIR root; only `CirIntentRootReference` string is available.+- Therefore state-alone recognition is insufficient.+- A convenience adapter can accept `NativeGeometryState` only when caller also provides explicit `CirNode root`.++## 7) Experiment 5 lowering plan / execution result findings+- Plan/execution expose strong intent/provenance context and are stable upstream entrypoints.+- Neither is a direct substitute for geometric root inspection.+- Recommended usage: higher layer extracts/retains lowered `CirNode`, then attaches plan/result-derived diagnostics.++## 8) Experiment 6 mismatch / precedence policy+- Authoritative geometry source: lowered `CirNode`.+- Diagnostic-only sources: replay log, native state, plan, execution result.+- Precedence:+ 1. Node geometry decides recognition success/failure.+ 2. Replay/native/plan can enrich diagnostics and mismatch evidence.+ 3. Replay contradictions must never force a geometry-positive result.++## 9) Experiment 7 recommended API shape+Lab prototype:++```csharp+public sealed record CirBoxCylinderRecognizerInput(+ CirNode Root,+ NativeGeometryReplayLog? ReplayLog = null,+ NativeGeometryState? NativeState = null,+ FirmamentPrimitiveLoweringPlan? LoweringPlan = null,+ FirmamentPrimitiveExecutionResult? ExecutionResult = null,+ string? SourceLabel = null);+```++Constructors/adapters validated:+- `FromNode(root)`+- `FromNode(root, replay)`+- `FromNativeState(state, root)` (requires explicit root)++## 10) Final v1 recognizer source contract+**Recommended v1 production contract:**+- Required: `CirNode Root`+- Optional: `NativeGeometryReplayLog? ReplayLog`++Rationale: `CirNode` is only source that consistently carries exact subtract topology + primitive dimensions + transform wrappers needed for canonical recognition. Replay is a high-value optional provenance channel.++## 11) Recommended v2 adapters+- Adapter from `FirmamentPrimitiveExecutionResult` -> `CirBoxCylinderRecognizerInput` requiring explicit root retention.+- Adapter from `(FirmamentPrimitiveLoweringPlan + lowered root + optional state)` -> input envelope.+- Optional policy flag for mismatch severity (warn vs reject for specific contradiction classes), while preserving node authority.++## 12) Production implementation guidance+- Implement recognizer API as node-first with optional replay.+- Keep geometry matching isolated from provenance matching.+- Add stable mismatch diagnostics schema (opIndex/featureId/toolKind/sourceFeatureId).+- Do not add recognizer dependency on BRep/native body objects.++## 13) Confidence ratings+- Node-only geometric sufficiency: **High**.+- Replay optionality and value: **High**.+- Native-state-alone insufficiency: **High**.+- Plan/result as primary geometry source: **High (negative)**.+- Mismatch precedence policy robustness: **Medium-High** (more exotic fixtures can further stress).