Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add source-derived sheet metal flat recovery commands

Yuechen Li8d742c10f4b7
diff --git a/Aetheris.CLI.Tests/SheetMetalCliTests.cs b/Aetheris.CLI.Tests/SheetMetalCliTests.cs
index 5e1d8225..d3be1420 100644
--- a/Aetheris.CLI.Tests/SheetMetalCliTests.cs
+++ b/Aetheris.CLI.Tests/SheetMetalCliTests.cs
@@ -73,5 +73,21 @@ public sealed class SheetMetalCliTests
finally{Directory.Delete(dir,true);}
}
+ [Fact]
+ public void RecognizeThenRecoverFlat_WritesInspectableSourceDerivedArtifacts()
+ {
+ var dir=Path.Combine(Path.GetTempPath(),$"aetheris-recognized-flat-{Guid.NewGuid():N}");Directory.CreateDirectory(dir);
+ try
+ {
+ var source=Path.Combine(RepoRoot,"testdata/step242/nist/CTC/nist_ctc_03_asme1_ap242-e2.stp");var plan=Path.Combine(dir,"recognition-plan.json");var output=new StringWriter();var error=new StringWriter();
+ var recognize=CliRunner.Run(["sheetmetal","recognize",source,"--plan",plan,"--json"],output,error);Assert.Equal(0,recognize);Assert.Empty(error.ToString());Assert.True(File.Exists(plan));
+ using(var report=JsonDocument.Parse(output.ToString())){Assert.Equal(7,report.RootElement.GetProperty("bends").GetArrayLength());Assert.All(report.RootElement.GetProperty("bends").EnumerateArray(),x=>Assert.Equal("Recognized",x.GetProperty("acceptedStatus").GetString()));}
+ output.GetStringBuilder().Clear();var recover=CliRunner.Run(["sheetmetal","recover-flat",source,"--recognition-plan",plan,"--out-dir",dir,"--json"],output,error);Assert.Equal(0,recover);Assert.Empty(error.ToString());
+ var reference=Path.Combine(dir,"recovered-flat.json");Assert.True(File.Exists(reference));Assert.True(File.Exists(Path.Combine(dir,"recovered-flat.svg")));
+ using var flat=JsonDocument.Parse(File.ReadAllText(reference));Assert.Equal("aetheris.recovered-flat-reference.v2",flat.RootElement.GetProperty("schema").GetString());Assert.Equal("RecoveredWithRepairs",flat.RootElement.GetProperty("contourAcceptance").GetString());Assert.Equal(3,flat.RootElement.GetProperty("junctionRepairs").GetArrayLength());Assert.Equal(17,flat.RootElement.GetProperty("cuts").GetArrayLength());Assert.Equal(7,flat.RootElement.GetProperty("bendLines").GetArrayLength());Assert.True(flat.RootElement.GetProperty("sourceProvenance").GetArrayLength()>=100);
+ }
+ finally{Directory.Delete(dir,true);}
+ }
+
private static string FindRepoRoot(){var dir=new DirectoryInfo(AppContext.BaseDirectory);while(dir is not null&&!File.Exists(Path.Combine(dir.FullName,"Aetheris.slnx")))dir=dir.Parent;return dir?.FullName??throw new InvalidOperationException("Repo root not found.");}
}
diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.cs
index 101b392b..4290981b 100644
--- a/Aetheris.CLI/CliRunner.cs
+++ b/Aetheris.CLI/CliRunner.cs
@@ -158,7 +158,7 @@ public static class CliRunner
private const string ExperimentalPrismaticMapUsage = "Usage: aetheris experimental prismatic-map --case <case> --rows <N> --cols <N> --json";
private const string FeaUsage = "Usage: aetheris fea <analysis.firmament> [--rotate <x,y,z-degrees>] [--out-dir <directory>] [--json]";
private const string DrawingUsage = "Usage: aetheris drawing compile <drawing.firmament> --out-dir <directory> [--json]";
- private const string SheetMetalUsage = "Usage: aetheris sheetmetal inspect <part.step|part.firmament> [--k-factor <0..1>] [--json] | aetheris sheetmetal paths <part.firmament> [--json] | aetheris sheetmetal recover <part.step> --out-dir <directory> [--json] | aetheris sheetmetal compare <part.step|part.firmament> <intent.firmament> [--json] | aetheris sheetmetal flatten <part.step|part.firmament> [--step <flat.step>] [--firmament <recovered.firmament>] [--svg <flat.svg>] [--k-factor <0..1>] [--json]";
+ private const string SheetMetalUsage = "Usage: aetheris sheetmetal recognize <part.step> [--plan <recognition.json>] [--json] | aetheris sheetmetal recover-flat <part.step> --out-dir <directory> [--recognition-plan <recognition.json>] [--json] | aetheris sheetmetal compare-flat <recovered-flat.json> <native.firmament> [--json] | aetheris sheetmetal inspect <part.step|part.firmament> [--k-factor <0..1>] [--json] | aetheris sheetmetal paths <part.firmament> [--json] | aetheris sheetmetal recover <part.step> --out-dir <directory> [--json] | aetheris sheetmetal compare <part.step|part.firmament> <intent.firmament> [--json] | aetheris sheetmetal flatten <part.step|part.firmament> [--step <flat.step>] [--firmament <recovered.firmament>] [--svg <flat.svg>] [--k-factor <0..1>] [--json]";
private const string ExperimentalLoopChamferCorpusUsage = "Usage: aetheris experimental loop-chamfer-corpus --out-dir <dir> [--json]";
internal static readonly JsonSerializerOptions JsonOptions = new()
@@ -498,6 +498,9 @@ public static class CliRunner
private static int RunSheetMetal(string[] args, TextWriter stdout, TextWriter stderr)
{
if(args.Length==0||IsHelpFlag(args[0])){WriteSheetMetalHelp(stdout);return args.Length==0?1:0;}
+ if(args[0]=="recognize")return RunSheetMetalRecognize(args.Skip(1).ToArray(),stdout,stderr);
+ if(args[0]=="recover-flat")return RunSheetMetalRecoverFlat(args.Skip(1).ToArray(),stdout,stderr);
+ if(args[0]=="compare-flat")return RunSheetMetalCompareFlat(args.Skip(1).ToArray(),stdout,stderr);
if(args[0]=="recover")return RunSheetMetalRecover(args.Skip(1).ToArray(),stdout,stderr);
if(args[0]=="compare")return RunSheetMetalCompare(args.Skip(1).ToArray(),stdout,stderr);
var operation=args[0];if(operation is not ("inspect" or "flatten" or "paths")||args.Length<2){stderr.WriteLine(SheetMetalUsage);return 1;}
@@ -551,6 +554,77 @@ public static class CliRunner
void WriteFailure(IReadOnlyList<SheetMetalDiagnostic> ds){if(json)stdout.WriteLine(JsonSerializer.Serialize(new{command=$"sheetmetal {operation}",success=false,input,diagnostics=ds},JsonOptions));else foreach(var d in ds)stderr.WriteLine($"[{d.Severity}] {d.Code}: {d.Message}");}
}
+ private static int RunSheetMetalRecognize(string[] args, TextWriter stdout, TextWriter stderr)
+ {
+ if(args.Length<1){stderr.WriteLine(SheetMetalUsage);return 1;}
+ var input=Path.GetFullPath(args[0]);string? planPath=null;var json=false;
+ for(var i=1;i<args.Length;i++)if(args[i]=="--json")json=true;else if(args[i]=="--plan"&&i+1<args.Length)planPath=Path.GetFullPath(args[++i]);else{stderr.WriteLine(SheetMetalUsage);return 1;}
+ if(!File.Exists(input)){stderr.WriteLine($"Sheet Metal input was not found: {input}");return 1;}
+ var detection=SheetMetalRecognizer.RecognizeStep(input);if(detection.Part is null){WriteSheetMetalDiagnostics(detection.Diagnostics,stderr);return 2;}
+ var model=RecognizedSheetMetalRecovery.FromDetection(detection);var plan=RecognizedSheetMetalRecovery.CreateAutomaticPlan(model);var validation=RecognizedSheetMetalRecovery.ValidatePlan(model,plan);
+ if(planPath is not null){Directory.CreateDirectory(Path.GetDirectoryName(planPath)!);File.WriteAllText(planPath,JsonSerializer.Serialize(plan,JsonOptions));}
+ var report=new{command="sheetmetal recognize",success=validation.IsValid,input,model=model.StableId,model.RecognitionStatus,model.Thickness,rootRegion=model.RootRegionId,
+ regions=model.Regions.Where(x=>x.Kind==SheetRegionKind.Planar).Select(x=>new{x.StableId,sourceFaces=x.Source.FaceIds}),
+ bends=model.Bends.Select(x=>new{x.SourceBendId,x.Name,candidateStatus=x.Status,acceptedStatus=plan.Bends.Single(y=>y.BendId==x.SourceBendId).Status,x.Confidence,axisOrigin=x.Geometry.AxisOrigin,axisDirection=x.Geometry.AxisDirection,angleDegrees=x.Geometry.BendAngleRadians*180/Math.PI,x.Geometry.InsideRadius,x.Geometry.AdjacentRegionA,x.Geometry.AdjacentRegionB,sourceFaces=x.Geometry.Source.FaceIds,evidence=x.Evidence}),
+ cuts=model.Cuts.Select(x=>new{x.StableId,x.Kind,x.OwningRegionId,sourceFaces=x.Source.FaceIds}),recognitionPlan=planPath,plan.DeterministicHash,diagnostics=detection.Diagnostics.Concat(validation.Diagnostics),timingsMilliseconds=new{import=detection.ImportTime.TotalMilliseconds,recognition=detection.RecognitionTime.TotalMilliseconds}};
+ if(json)stdout.WriteLine(JsonSerializer.Serialize(report,JsonOptions));else{stdout.WriteLine($"Recognized imported Sheet Metal: {model.Regions.Count(x=>x.Kind==SheetRegionKind.Planar)} planar regions, {model.Bends.Count} bend candidates, {plan.Bends.Count(x=>x.Status==RecognizedBendStatus.Recognized)} accepted, {model.Cuts.Count} cuts.");foreach(var b in report.bends)stdout.WriteLine($" {b.Name} ({b.SourceBendId}): {b.acceptedStatus}, {b.angleDegrees:G6} deg, R{b.InsideRadius:G6}, {b.AdjacentRegionA} -> {b.AdjacentRegionB}");if(planPath is not null)stdout.WriteLine($"Recognition plan: {planPath}");}
+ return validation.IsValid?0:2;
+ }
+
+ private static int RunSheetMetalRecoverFlat(string[] args, TextWriter stdout, TextWriter stderr)
+ {
+ if(args.Length<1){stderr.WriteLine(SheetMetalUsage);return 1;}
+ var input=Path.GetFullPath(args[0]);string? outDir=null,planPath=null;var json=false;
+ for(var i=1;i<args.Length;i++)if(args[i]=="--json")json=true;else if(args[i]=="--out-dir"&&i+1<args.Length)outDir=Path.GetFullPath(args[++i]);else if(args[i]=="--recognition-plan"&&i+1<args.Length)planPath=Path.GetFullPath(args[++i]);else{stderr.WriteLine(SheetMetalUsage);return 1;}
+ if(!File.Exists(input)){stderr.WriteLine($"Sheet Metal input was not found: {input}");return 1;}if(outDir is null){stderr.WriteLine("sheetmetal recover-flat requires --out-dir.");return 1;}
+ var detection=SheetMetalRecognizer.RecognizeStep(input);if(detection.Part is null){WriteSheetMetalDiagnostics(detection.Diagnostics,stderr);return 2;}
+ var model=RecognizedSheetMetalRecovery.FromDetection(detection);SheetMetalRecognitionPlan plan;
+ if(planPath is null)plan=RecognizedSheetMetalRecovery.CreateAutomaticPlan(model);else
+ {
+ if(!File.Exists(planPath)){stderr.WriteLine($"Recognition plan was not found: {planPath}");return 1;}
+ var loaded=JsonSerializer.Deserialize<SheetMetalRecognitionPlan>(File.ReadAllText(planPath),JsonOptions)??throw new InvalidDataException("Recognition plan JSON was empty.");
+ plan=RecognizedSheetMetalRecovery.CreatePlan(model,loaded.Bends,loaded.RootRegionId,loaded.ReferenceKind,loaded.Authority);
+ }
+ var recovered=RecoveredSourceFlattener.Flatten(model,plan);Directory.CreateDirectory(outDir);
+ var artifactPath=Path.Combine(outDir,"recovered-flat.json");var svgPath=Path.Combine(outDir,"recovered-flat.svg");var persistedPlanPath=Path.Combine(outDir,"recognition-plan.json");
+ File.WriteAllText(persistedPlanPath,JsonSerializer.Serialize(plan,JsonOptions));File.WriteAllText(artifactPath,JsonSerializer.Serialize(RecoveredFlatArtifact(input,recovered),JsonOptions));SheetMetalSvgRenderer.Write(svgPath,RecoveredSourceFlattener.ToFlatPattern(recovered));
+ var report=new{command="sheetmetal recover-flat",success=recovered.Status!=FlatPatternStatus.Unsupported,input,recovered.StableId,recovered.ReferenceKind,recovered.RootRegionId,recovered.Status,recovered.ContourAcceptance,recovered.Bounds,outerSegments=recovered.OuterAndInnerContours?.OuterLoop.Segments.Count??0,innerLoops=recovered.OuterAndInnerContours?.InnerLoops.Count??recovered.InnerContours.Count,cuts=recovered.InnerContours.Count,bendLines=recovered.BendLines.Count,regions=recovered.Regions.Count,sourceProvenance=recovered.SourceProvenance.Count,junctionRepairs=recovered.JunctionRepairs,recovered.StitchSummary,recovered.DeterministicHash,artifacts=new{reference=artifactPath,svg=svgPath,recognitionPlan=persistedPlanPath},timingsMilliseconds=new{graph=recovered.GraphTime.TotalMilliseconds,unfold=recovered.UnfoldTime.TotalMilliseconds,stitch=recovered.StitchTime.TotalMilliseconds,cluster=recovered.StitchSummary?.EndpointClusteringMilliseconds,candidateSelection=recovered.StitchSummary?.CandidateSelectionMilliseconds,validate=recovered.StitchSummary?.ContourValidationMilliseconds},recovered.Diagnostics};
+ if(json)stdout.WriteLine(JsonSerializer.Serialize(report,JsonOptions));else stdout.WriteLine($"Recovered source flat: {recovered.Status} ({recovered.ContourAcceptance}); {(recovered.Bounds is null?"no bounds":$"{recovered.Bounds.Width:G8} x {recovered.Bounds.Height:G8} mm")}; {recovered.InnerContours.Count} cuts; {recovered.BendLines.Count} bend lines; {recovered.JunctionRepairs.Count} repaired junctions; {recovered.JunctionRepairs.Count(x=>x.Confidence==RecoveryRepairConfidence.Ambiguous)} unresolved/ambiguous.\nReference: {artifactPath}\nSVG: {svgPath}\nPlan: {persistedPlanPath}");
+ return recovered.Status==FlatPatternStatus.Unsupported?2:0;
+ }
+
+ private static int RunSheetMetalCompareFlat(string[] args, TextWriter stdout, TextWriter stderr)
+ {
+ if(args.Length<2||args.Skip(2).Any(x=>x!="--json")){stderr.WriteLine(SheetMetalUsage);return 1;}
+ var referencePath=Path.GetFullPath(args[0]);var nativePath=Path.GetFullPath(args[1]);var json=args.Contains("--json",StringComparer.Ordinal);
+ if(!File.Exists(referencePath)||!File.Exists(nativePath)){stderr.WriteLine("Recovered flat or native Firmament input was not found.");return 1;}
+ using var document=JsonDocument.Parse(File.ReadAllText(referencePath));var root=document.RootElement;var sourcePath=root.GetProperty("sourcePath").GetString();var planElement=root.GetProperty("recognitionPlan");
+ if(string.IsNullOrWhiteSpace(sourcePath)||!File.Exists(sourcePath)){stderr.WriteLine("Recovered flat sourcePath is unavailable; deterministic source revalidation cannot proceed.");return 2;}
+ var loadedPlan=planElement.Deserialize<SheetMetalRecognitionPlan>(JsonOptions);if(loadedPlan is null){stderr.WriteLine("Recovered flat recognition plan is invalid.");return 2;}
+ var detection=SheetMetalRecognizer.RecognizeStep(sourcePath);if(detection.Part is null){WriteSheetMetalDiagnostics(detection.Diagnostics,stderr);return 2;}var model=RecognizedSheetMetalRecovery.FromDetection(detection);var plan=RecognizedSheetMetalRecovery.CreatePlan(model,loadedPlan.Bends,loadedPlan.RootRegionId,loadedPlan.ReferenceKind,loadedPlan.Authority);var source=RecoveredSourceFlattener.Flatten(model,plan);
+ var native=SheetMetalFirmament.CompileFile(nativePath);if(!native.IsSuccess||native.FlatPattern is null){WriteSheetMetalDiagnostics(native.Diagnostics,stderr);return 2;}
+ var comparison=RecoveredFlatComparer.Compare(source,native.FlatPattern);var report=new{command="sheetmetal compare-flat",success=comparison.Status!=SheetMetalComparisonStatus.Fail,reference=referencePath,native=nativePath,comparison};
+ if(json)stdout.WriteLine(JsonSerializer.Serialize(report,JsonOptions));else{stdout.WriteLine($"Recovered source flat -> native flat: {comparison.Status}");stdout.WriteLine($"source->native RMS/p95/max: {comparison.SourceToNative.Rms:G6}/{comparison.SourceToNative.P95:G6}/{comparison.SourceToNative.Maximum:G6} mm");stdout.WriteLine($"native->source RMS/p95/max: {comparison.NativeToSource.Rms:G6}/{comparison.NativeToSource.P95:G6}/{comparison.NativeToSource.Maximum:G6} mm");foreach(var item in comparison.LocalizedDifferences)stdout.WriteLine($" {item}");}
+ return comparison.Status==SheetMetalComparisonStatus.Fail?2:0;
+ }
+
+ private static object RecoveredFlatArtifact(string sourcePath, RecoveredFlatReference recovered) => new
+ {
+ schema="aetheris.recovered-flat-reference.v2",sourcePath=Path.GetFullPath(sourcePath),recovered.StableId,recovered.ReferenceKind,recovered.RootRegionId,recovered.Frame,recovered.Status,recovered.ContourAcceptance,recovered.Bounds,recovered.DeterministicHash,recovered.RecognitionPlan,recovered.JunctionRepairs,recovered.StitchSummary,
+ outerContour=ContourArtifact(recovered.OuterAndInnerContours?.OuterLoop),innerContours=(recovered.OuterAndInnerContours?.InnerLoops??[]).Select(ContourArtifact),
+ regions=recovered.Regions.Select(x=>new{x.StableId,x.SourceRegionId,x.Kind,x.MappingKind,contour=ContourArtifact(x.ExactContour?.OuterLoop)}),
+ cuts=recovered.InnerContours.Select(x=>new{x.FeatureId,x.Kind,x.SourceRegionId,contour=ContourArtifact(x.ExactContour?.OuterLoop)}),recovered.BendLines,recovered.RegionMap,recovered.SourceProvenance,recovered.Diagnostics
+ };
+ private static object? ContourArtifact(PlanarContourLoop2? loop)=>loop is null?null:new{loop.StableId,loop.IsOuter,segments=loop.Segments.Select(x=>new{x.StableId,kind=x.Geometry.GetType().Name,geometry=CurveArtifact(x.Geometry),x.Provenance})};
+ private static object CurveArtifact(LineArcProfileCurve2D curve)=>curve switch
+ {
+ LineArcLineSegment2D line=>new{start=new{x=line.Start.X,y=line.Start.Y},end=new{x=line.End.X,y=line.End.Y}},
+ LineArcCircularArc2D arc=>new{center=new{x=arc.Center.X,y=arc.Center.Y},arc.Radius,arc.StartAngleRadians,arc.SweepAngleRadians,start=new{x=arc.Center.X+arc.Radius*Math.Cos(arc.StartAngleRadians),y=arc.Center.Y+arc.Radius*Math.Sin(arc.StartAngleRadians)},end=new{x=arc.Center.X+arc.Radius*Math.Cos(arc.StartAngleRadians+arc.SweepAngleRadians),y=arc.Center.Y+arc.Radius*Math.Sin(arc.StartAngleRadians+arc.SweepAngleRadians)}},
+ LineArcFullCircle2D circle=>new{center=new{x=circle.Center.X,y=circle.Center.Y},circle.Radius},
+ _=>new{unsupported=curve.GetType().Name}
+ };
+ private static void WriteSheetMetalDiagnostics(IEnumerable<SheetMetalDiagnostic> diagnostics,TextWriter stderr){foreach(var d in diagnostics)stderr.WriteLine($"[{d.Severity}] {d.Code}: {d.Message}");}
+
private static int RunSheetMetalRecover(string[] args, TextWriter stdout, TextWriter stderr)
{
if(args.Length<1){stderr.WriteLine(SheetMetalUsage);return 1;}var input=Path.GetFullPath(args[0]);string? outDir=null;var json=false;
@@ -3685,6 +3759,9 @@ Model CanonicalPanel {
stdout.WriteLine(SheetMetalUsage);
stdout.WriteLine();
stdout.WriteLine(" inspect Print a compact recognition, bend-evidence, flat-status, DFM, and timing summary.");
+ stdout.WriteLine(" recognize Separate machine bend candidates from a validated, editable recognition plan.");
+ stdout.WriteLine(" recover-flat Unfold accepted imported bends into a source-derived geometric mid-surface reference.");
+ stdout.WriteLine(" compare-flat Compare a recovered source reference directly with a native Firmament flat.");
stdout.WriteLine(" paths List stable authored Sheet Metal Concept Paths, capabilities, and formed/flat correspondence.");
stdout.WriteLine(" recover Emit forensic summary JSON, editable recovered draft, and concise LLM/engineer reconstruction brief.");
stdout.WriteLine(" compare Compare source and reconstructed intent with localized formed, bend, feature, and flat residuals.");
@@ -3696,6 +3773,9 @@ Model CanonicalPanel {
stdout.WriteLine(" --json Emit compact deterministic JSON.");
stdout.WriteLine();
stdout.WriteLine("Examples:");
+ stdout.WriteLine(" aetheris sheetmetal recognize part.step --plan artifacts/recognition-plan.json --json");
+ stdout.WriteLine(" aetheris sheetmetal recover-flat part.step --recognition-plan artifacts/recognition-plan.json --out-dir artifacts/recovered-flat --json");
+ stdout.WriteLine(" aetheris sheetmetal compare-flat artifacts/recovered-flat/recovered-flat.json reconstructed.firmament --json");
stdout.WriteLine(" aetheris sheetmetal inspect testdata/step242/nist/CTC/nist_ctc_03_asme1_ap242-e2.stp");
stdout.WriteLine(" aetheris sheetmetal paths fixtures/FirmamentV2/SheetMetal/m3-electronics-tray.firmament");
stdout.WriteLine(" aetheris sheetmetal recover part.step --out-dir artifacts/recovery --json");
diff --git a/Aetheris.SheetMetal.Tests/RecognizedImportRecoveryM1Tests.cs b/Aetheris.SheetMetal.Tests/RecognizedImportRecoveryM1Tests.cs
new file mode 100644
index 00000000..3313f9a9
--- /dev/null
+++ b/Aetheris.SheetMetal.Tests/RecognizedImportRecoveryM1Tests.cs
@@ -0,0 +1,57 @@
+using Aetheris.Kernel.Core.Step242;
+using Xunit;
+
+namespace Aetheris.SheetMetal.Tests;
+
+public sealed class RecognizedImportRecoveryM1Tests
+{
+ private static readonly string RepoRoot=FindRepoRoot();
+ private static string Ctc=>Path.Combine(RepoRoot,"testdata/step242/nist/CTC/nist_ctc_03_asme1_ap242-e2.stp");
+
+ [Fact]
+ public void Ctc03_DetectionCandidatesRequireAnExplicitValidatedRecognitionPlan()
+ {
+ var detection=SheetMetalRecognizer.RecognizeStep(Ctc);var model=RecognizedSheetMetalRecovery.FromDetection(detection);
+ Assert.Equal(7,model.Bends.Count);Assert.All(model.Bends,x=>Assert.Equal(RecognizedBendStatus.Candidate,x.Status));
+ var plan=RecognizedSheetMetalRecovery.CreateAutomaticPlan(model);Assert.Equal(7,plan.Bends.Count(x=>x.Status==RecognizedBendStatus.Recognized));
+ var renamed=plan with { Bends=plan.Bends.Select((x,i)=>i==0?x with{Name="FrontWallBend"}:x).ToArray(),Authority="engineer/LLM assertion checked against imported geometry" };
+ var validation=RecognizedSheetMetalRecovery.ValidatePlan(model,renamed);Assert.True(validation.IsValid,string.Join('\n',validation.Diagnostics.Select(x=>x.Message)));
+ Assert.Contains(validation.Model!.Bends,x=>x.Name=="FrontWallBend"&&x.Status==RecognizedBendStatus.Recognized&&x.Geometry.Source.FaceIds.Count==2);
+ }
+
+ [Fact]
+ public void RecognitionPlan_RejectsAClaimWithoutCylindricalSourceEvidence()
+ {
+ var model=RecognizedSheetMetalRecovery.FromDetection(SheetMetalRecognizer.RecognizeStep(Ctc));var plan=RecognizedSheetMetalRecovery.CreateAutomaticPlan(model);
+ plan=plan with { Bends=[..plan.Bends,new("invented-bend","Impossible",RecognizedBendStatus.Recognized)] };
+ var validation=RecognizedSheetMetalRecovery.ValidatePlan(model,plan);Assert.False(validation.IsValid);
+ Assert.Contains(validation.Diagnostics,x=>x.Code==SheetMetalDiagnosticCodes.RecognitionAssertionInvalid&&x.Message.Contains("no machine-detected cylindrical support",StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public void Ctc03_SourceUnfold_PreservesAllExactRegionLoopsCutsBendsAndProvenanceDeterministically()
+ {
+ var detection=SheetMetalRecognizer.RecognizeStep(Ctc);var model=RecognizedSheetMetalRecovery.FromDetection(detection);var plan=RecognizedSheetMetalRecovery.CreateAutomaticPlan(model);
+ var first=RecoveredSourceFlattener.Flatten(model,plan);var second=RecoveredSourceFlattener.Flatten(model,plan);
+ Assert.NotEqual(FlatPatternStatus.Unsupported,first.Status);Assert.Equal(7,first.BendLines.Count);Assert.Equal(17,first.InnerContours.Count);
+ Assert.All(first.Regions,x=>Assert.NotNull(x.ExactContour));Assert.All(first.InnerContours,x=>Assert.NotNull(x.ExactContour));
+ Assert.Contains(first.Regions.SelectMany(x=>x.ExactContour!.OuterLoop.Segments),x=>x.Geometry is Aetheris.Kernel.Firmament.Materializer.LineArcCircularArc2D);
+ Assert.True(first.SourceProvenance.Count>=100);Assert.Equal(first.DeterministicHash,second.DeterministicHash);
+ Assert.Equal(RecoveredFlatReferenceKind.GeometricMidSurface,first.ReferenceKind);Assert.Equal(.5,RecoveredSourceFlattener.ToFlatPattern(first).Policy.KFactor);
+ Assert.Equal(FlatPatternStatus.Valid,first.Status);Assert.NotNull(first.OuterAndInnerContours);
+ }
+
+ [Fact]
+ public void NonCtcUChannel_StepOnlyRoundTripRecognizesAndUnfoldsWithoutNativeConstructionAuthority()
+ {
+ var authored=SheetMetalFirmament.CompileFile(Path.Combine(RepoRoot,"fixtures/FirmamentV2/SheetMetal/simple-u-channel.firmament"));Assert.True(authored.IsSuccess);
+ var exported=Step242Exporter.ExportBody(authored.Part!.FormedBody!);Assert.True(exported.IsSuccess);
+ var imported=Step242Importer.ImportBody(exported.Value);Assert.True(imported.IsSuccess);
+ var detection=SheetMetalRecognizer.Recognize(imported.Value,"generic-u-channel.step");var model=RecognizedSheetMetalRecovery.FromDetection(detection);var plan=RecognizedSheetMetalRecovery.CreateAutomaticPlan(model);
+ var recovered=RecoveredSourceFlattener.Flatten(model,plan);Assert.Equal(2,recovered.BendLines.Count);Assert.Equal(FlatPatternStatus.Valid,recovered.Status);Assert.NotNull(recovered.OuterAndInnerContours);
+ Assert.All(model.Bends,x=>Assert.Equal(RecognizedBendStatus.Candidate,x.Status));Assert.All(plan.Bends,x=>Assert.Equal(RecognizedBendStatus.Recognized,x.Status));
+ Assert.All(recovered.Regions.Where(x=>x.Kind==SheetRegionKind.Planar),x=>Assert.NotNull(x.ExactContour));
+ }
+
+ private static string FindRepoRoot(){var dir=new DirectoryInfo(AppContext.BaseDirectory);while(dir is not null&&!File.Exists(Path.Combine(dir.FullName,"Aetheris.slnx")))dir=dir.Parent;return dir?.FullName??throw new InvalidOperationException("Repo root not found.");}
+}
diff --git a/Aetheris.SheetMetal.Tests/RecoveredContourStitchingM2Tests.cs b/Aetheris.SheetMetal.Tests/RecoveredContourStitchingM2Tests.cs
new file mode 100644
index 00000000..bed22aa6
--- /dev/null
+++ b/Aetheris.SheetMetal.Tests/RecoveredContourStitchingM2Tests.cs
@@ -0,0 +1,81 @@
+using Aetheris.Kernel.Core.Step242;
+using Aetheris.Kernel.Firmament.Materializer;
+using Xunit;
+
+namespace Aetheris.SheetMetal.Tests;
+
+public sealed class RecoveredContourStitchingM2Tests
+{
+ private static readonly string RepoRoot=FindRepoRoot();
+ private static string Ctc=>Path.Combine(RepoRoot,"testdata/step242/nist/CTC/nist_ctc_03_asme1_ap242-e2.stp");
+
+ [Fact]
+ public void Ctc03_RecoveryCollapsesExactlyThreePointTangentMicroClosuresIntoAValidAnalyticBlank()
+ {
+ var model=RecognizedSheetMetalRecovery.FromDetection(SheetMetalRecognizer.RecognizeStep(Ctc));
+ var recovered=RecoveredSourceFlattener.Flatten(model,RecognizedSheetMetalRecovery.CreateAutomaticPlan(model));
+ Assert.Equal(FlatPatternStatus.Valid,recovered.Status);Assert.Equal(RecoveredContourAcceptance.RecoveredWithRepairs,recovered.ContourAcceptance);
+ Assert.NotNull(recovered.OuterAndInnerContours);Assert.True(PlanarContourKernel.Validate(recovered.OuterAndInnerContours).IsValid);
+ Assert.Equal(17,recovered.OuterAndInnerContours.InnerLoops.Count);Assert.Equal(7,recovered.BendLines.Count);
+ Assert.Equal(3,recovered.JunctionRepairs.Count);Assert.All(recovered.JunctionRepairs,x=>
+ {
+ Assert.Equal(RecoveryJunctionKind.PointTangentContinuation,x.Kind);Assert.Equal(RecoveryRepairConfidence.Strong,x.Confidence);
+ Assert.InRange(x.MaximumDisplacement,0,RecoveryContourStitcher.JunctionTolerance);
+ });
+ Assert.Equal(3,recovered.StitchSummary!.AmbiguousJunctionCount);Assert.Empty(recovered.StitchSummary.Rejections);
+ Assert.Contains(recovered.OuterAndInnerContours.OuterLoop.Segments,x=>x.Geometry is LineArcCircularArc2D);
+ }
+
+ [Fact]
+ public void SameProfileVendorGap_IsClusteredLocally_WithoutPolygonizingComplementaryArcs()
+ {
+ var p=Provenance("vendor-loop");
+ ArrangementFragment2D F(string id,LineArcProfileCurve2D geometry)=>new(id,
+ new(id,"region",PrismaticProfileIntent.Add,"vendor-loop","outer",id,geometry,p with{StableId=id}),0,1,geometry,true,true);
+ const double noise=1e-6;
+ var fragments=new[]
+ {
+ F("bottom",new LineArcLineSegment2D((0,0),(10,0))),
+ F("right",new LineArcLineSegment2D((10+noise,0),(10,10))),
+ F("top",new LineArcLineSegment2D((10,10),(0,10))),
+ F("left",new LineArcLineSegment2D((0,10),(0,0)))
+ };
+ var arrangement=new ProfileArrangement2D("XY",fragments.Select(x=>x.Source).ToArray(),[],fragments,[],0,[],TimeSpan.Zero,TimeSpan.Zero,TimeSpan.Zero,TimeSpan.Zero);
+ var result=RecoveryContourStitcher.Stitch(arrangement,"noisy-vendor-square");
+ Assert.NotNull(result.Contour);Assert.Equal(RecoveredContourAcceptance.RecoveredWithRepairs,result.Acceptance);
+ Assert.Single(result.Repairs);Assert.Equal(RecoveryJunctionKind.WithinToleranceEndpointMatch,result.Repairs[0].Kind);
+ Assert.True(PlanarContourKernel.Validate(result.Contour).IsValid);
+
+ var arcs=new LineArcProfileCurve2D[]
+ {
+ new LineArcCircularArc2D((0,0),5,0,Math.PI),
+ new LineArcCircularArc2D((0,0),5,Math.PI,Math.PI)
+ };
+ var arcFragments=arcs.Select((x,i)=>F($"arc-{i}",x)).ToArray();
+ var arcArrangement=new ProfileArrangement2D("XY",arcFragments.Select(x=>x.Source).ToArray(),[],arcFragments,[],0,[],TimeSpan.Zero,TimeSpan.Zero,TimeSpan.Zero,TimeSpan.Zero);
+ var circle=RecoveryContourStitcher.Stitch(arcArrangement,"complementary-arcs");
+ Assert.NotNull(circle.Contour);Assert.Equal(2,circle.Contour.OuterLoop.Segments.Count);
+ Assert.NotEqual(circle.Contour.OuterLoop.Segments[0].Geometry,circle.Contour.OuterLoop.Segments[1].Geometry);
+ }
+
+ [Fact]
+ public void SignedZeroPerturbedDumbStep_StillRecognizesAndRecoversGenericUChannel()
+ {
+ var source=SheetMetalFirmament.CompileFile(Path.Combine(RepoRoot,"fixtures/FirmamentV2/SheetMetal/simple-u-channel.firmament"));Assert.True(source.IsSuccess);
+ var exported=Step242Exporter.ExportBody(source.Part!.FormedBody!);Assert.True(exported.IsSuccess);
+ // A vendor-style text perturbation changes numeric spelling only; native
+ // Firmament source is deliberately absent from the recovery call below.
+ var dirty=exported.Value.Replace("(0.,", "(-0.,",StringComparison.Ordinal);
+ var path=Path.Combine(Path.GetTempPath(),$"aetheris-noisy-u-{Guid.NewGuid():N}.step");
+ try
+ {
+ File.WriteAllText(path,dirty);var detection=SheetMetalRecognizer.RecognizeStep(path);Assert.NotNull(detection.Part);
+ var model=RecognizedSheetMetalRecovery.FromDetection(detection);var recovered=RecoveredSourceFlattener.Flatten(model,RecognizedSheetMetalRecovery.CreateAutomaticPlan(model));
+ Assert.Equal(FlatPatternStatus.Valid,recovered.Status);Assert.NotNull(recovered.OuterAndInnerContours);Assert.Equal(2,recovered.BendLines.Count);
+ }
+ finally{File.Delete(path);}
+ }
+
+ private static ProfileSegmentProvenance Provenance(string id)=>new(id,id,"test","vendor-noise recovery fixture","XY");
+ private static string FindRepoRoot(){var dir=new DirectoryInfo(AppContext.BaseDirectory);while(dir is not null&&!File.Exists(Path.Combine(dir.FullName,"Aetheris.slnx")))dir=dir.Parent;return dir?.FullName??throw new InvalidOperationException("Repo root not found.");}
+}
diff --git a/Aetheris.SheetMetal/RecognizedSheetMetalModel.cs b/Aetheris.SheetMetal/RecognizedSheetMetalModel.cs
new file mode 100644
index 00000000..cff92007
--- /dev/null
+++ b/Aetheris.SheetMetal/RecognizedSheetMetalModel.cs
@@ -0,0 +1,229 @@
+using System.Globalization;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.SheetMetal;
+
+/// <summary>
+/// One machine-detected bend plus the explicit authority that decides whether source
+/// unfolding may consume it. The recovered geometric ID remains immutable underneath
+/// an optional engineer/LLM name.
+/// </summary>
+public sealed record RecognizedBend(
+ string SourceBendId,
+ string Name,
+ RecognizedBendStatus Status,
+ SheetBendIr Geometry,
+ double Confidence,
+ IReadOnlyList<SheetEvidence> Evidence,
+ string Authority);
+
+public sealed record RecognizedRegionAdjacency(
+ string BendId,
+ string RegionA,
+ string RegionB);
+
+public sealed record RecognizedSheetMetalModel(
+ string StableId,
+ BrepBody SourceBody,
+ string SourcePath,
+ double Thickness,
+ IReadOnlyList<SheetRegionIr> Regions,
+ IReadOnlyList<RecognizedBend> Bends,
+ IReadOnlyList<SheetFeatureIr> Cuts,
+ IReadOnlyList<RecognizedRegionAdjacency> RegionAdjacency,
+ string RootRegionId,
+ SheetMetalRecognitionStatus RecognitionStatus,
+ IReadOnlyList<SheetEvidence> RecognitionEvidence,
+ IReadOnlyList<SheetMetalDiagnostic> Diagnostics,
+ SheetMetalPartIr DetectedPart);
+
+public sealed record SheetMetalBendRecognitionDecision(
+ string BendId,
+ string? Name,
+ RecognizedBendStatus Status);
+
+public sealed record SheetMetalRecognitionPlan(
+ string StableId,
+ string SourcePath,
+ double RecognizedThickness,
+ string RootRegionId,
+ RecoveredFlatReferenceKind ReferenceKind,
+ IReadOnlyList<SheetMetalBendRecognitionDecision> Bends,
+ string Authority,
+ string DeterministicHash);
+
+public sealed record RecognitionPlanValidation(
+ bool IsValid,
+ RecognizedSheetMetalModel? Model,
+ IReadOnlyList<SheetMetalDiagnostic> Diagnostics);
+
+public sealed record RecoveredFlatSegmentProvenance(
+ string FlatSegmentId,
+ string SourceRegionId,
+ IReadOnlyList<int> SourceFaceIds,
+ IReadOnlyList<int> SourceEdgeIds,
+ string Derivation);
+
+public sealed record RecoveredFlatReference(
+ string StableId,
+ RecoveredFlatReferenceKind ReferenceKind,
+ string RootRegionId,
+ string Frame,
+ PlanarContour2? OuterAndInnerContours,
+ IReadOnlyList<FlatRegion2D> Regions,
+ IReadOnlyList<FlatCutLoop> InnerContours,
+ IReadOnlyList<FlatBendLine> BendLines,
+ IReadOnlyList<SourceToFlatMapping> RegionMap,
+ IReadOnlyList<RecoveredFlatSegmentProvenance> SourceProvenance,
+ SheetMetalRecognitionPlan RecognitionPlan,
+ FlatPatternBounds? Bounds,
+ FlatPatternStatus Status,
+ IReadOnlyList<SheetMetalDiagnostic> Diagnostics,
+ RecoveredContourAcceptance ContourAcceptance,
+ IReadOnlyList<RecoveryJunctionRepair> JunctionRepairs,
+ RecoveryStitchSummary? StitchSummary,
+ string DeterministicHash,
+ TimeSpan GraphTime,
+ TimeSpan UnfoldTime,
+ TimeSpan StitchTime);
+
+public static class RecognizedSheetMetalRecovery
+{
+ public static RecognizedSheetMetalModel FromDetection(SheetMetalRecognitionResult detection)
+ {
+ ArgumentNullException.ThrowIfNull(detection);
+ var part = detection.Part ?? throw new ArgumentException("Detection did not produce a Sheet Metal interpretation.", nameof(detection));
+ var body = part.FormedBody ?? throw new ArgumentException("Imported recognition must retain its source body.", nameof(detection));
+ var bends = part.Bends.OrderBy(x => x.StableId, StringComparer.Ordinal).Select((bend, index) => new RecognizedBend(
+ bend.StableId,
+ DefaultName(part, bend, index),
+ IsGeometricallyStrong(bend, part) ? RecognizedBendStatus.Candidate : RecognizedBendStatus.Ambiguous,
+ bend,
+ IsGeometricallyStrong(bend, part) ? 1d : .5d,
+ bend.Evidence,
+ "machine-detected candidate; not yet unfolding authority")).ToArray();
+ var sourcePath = part.Regions.Select(x => x.Source.SourcePath).FirstOrDefault(x => !string.IsNullOrWhiteSpace(x)) ?? "BRep";
+ var adjacency = bends.Select(x => new RecognizedRegionAdjacency(x.SourceBendId, x.Geometry.AdjacentRegionA, x.Geometry.AdjacentRegionB)).ToArray();
+ var id = $"recognized-{SheetMetalRecognizer.StableHash(part.StableId + "|" + string.Join('|', bends.Select(x => x.SourceBendId)))[..16]}";
+ return new(id, body, sourcePath, part.Thickness, part.Regions, bends, part.Features, adjacency,
+ part.BaseRegionId, part.RecognitionStatus, part.Evidence, detection.Diagnostics, part);
+ }
+
+ /// <summary>Deterministically accepts only geometry-supported, unambiguous candidates.</summary>
+ public static SheetMetalRecognitionPlan CreateAutomaticPlan(RecognizedSheetMetalModel model)
+ {
+ ArgumentNullException.ThrowIfNull(model);
+ var decisions = model.Bends.OrderBy(x => x.SourceBendId, StringComparer.Ordinal).Select(x => new SheetMetalBendRecognitionDecision(
+ x.SourceBendId, x.Name,
+ x.Status == RecognizedBendStatus.Candidate && x.Confidence >= .99d ? RecognizedBendStatus.Recognized : x.Status)).ToArray();
+ return CreatePlan(model, decisions, model.RootRegionId, RecoveredFlatReferenceKind.GeometricMidSurface,
+ "deterministic validated automatic recognition");
+ }
+
+ public static SheetMetalRecognitionPlan CreatePlan(
+ RecognizedSheetMetalModel model,
+ IReadOnlyList<SheetMetalBendRecognitionDecision> decisions,
+ string rootRegionId,
+ RecoveredFlatReferenceKind referenceKind,
+ string authority)
+ {
+ var canonical = string.Join('|', model.SourcePath, model.Thickness.ToString("R", CultureInfo.InvariantCulture), rootRegionId,
+ referenceKind, authority, string.Join(';', decisions.OrderBy(x => x.BendId, StringComparer.Ordinal).Select(x => $"{x.BendId}:{x.Name}:{x.Status}")));
+ var hash = SheetMetalRecognizer.StableHash(canonical);
+ return new($"recognition-plan-{hash[..16]}", model.SourcePath, model.Thickness, rootRegionId, referenceKind,
+ decisions.OrderBy(x => x.BendId, StringComparer.Ordinal).ToArray(), authority, hash);
+ }
+
+ public static RecognitionPlanValidation ValidatePlan(RecognizedSheetMetalModel detected, SheetMetalRecognitionPlan plan)
+ {
+ ArgumentNullException.ThrowIfNull(detected); ArgumentNullException.ThrowIfNull(plan);
+ var diagnostics = new List<SheetMetalDiagnostic>();
+ if (Math.Abs(plan.RecognizedThickness - detected.Thickness) > .01d)
+ diagnostics.Add(new(SheetMetalDiagnosticCodes.RecognitionAssertionInvalid, SheetMetalDiagnosticSeverity.Error,
+ $"Asserted thickness {plan.RecognizedThickness:G12} mm contradicts measured thickness {detected.Thickness:G12} mm."));
+ if (!detected.Regions.Any(x => x.StableId == plan.RootRegionId && x.Kind == SheetRegionKind.Planar))
+ diagnostics.Add(new(SheetMetalDiagnosticCodes.RecognitionAssertionInvalid, SheetMetalDiagnosticSeverity.Error,
+ $"Asserted root '{plan.RootRegionId}' is not a recovered planar region."));
+ var decisionIds = new HashSet<string>(StringComparer.Ordinal);
+ var accepted = new List<RecognizedBend>();
+ foreach (var decision in plan.Bends.OrderBy(x => x.BendId, StringComparer.Ordinal))
+ {
+ if (!decisionIds.Add(decision.BendId))
+ {
+ diagnostics.Add(new(SheetMetalDiagnosticCodes.RecognitionAssertionInvalid, SheetMetalDiagnosticSeverity.Error,
+ $"Recognition plan contains duplicate bend decision '{decision.BendId}'."));
+ continue;
+ }
+ var candidate = detected.Bends.FirstOrDefault(x => x.SourceBendId == decision.BendId);
+ if (candidate is null)
+ {
+ diagnostics.Add(new(SheetMetalDiagnosticCodes.RecognitionAssertionInvalid, SheetMetalDiagnosticSeverity.Error,
+ $"Asserted bend '{decision.BendId}' has no machine-detected cylindrical support."));
+ continue;
+ }
+ if (decision.Status == RecognizedBendStatus.Recognized && !IsGeometricallyStrong(candidate.Geometry, detected.DetectedPart))
+ diagnostics.Add(new(SheetMetalDiagnosticCodes.RecognitionAssertionInvalid, SheetMetalDiagnosticSeverity.Error,
+ $"Bend '{decision.BendId}' cannot be accepted: cylindrical support, bounded angle, radius, or two-region adjacency is inconsistent.", candidate.Geometry.Source.FaceIds));
+ accepted.Add(candidate with
+ {
+ Name = string.IsNullOrWhiteSpace(decision.Name) ? candidate.Name : decision.Name.Trim(),
+ Status = decision.Status,
+ Authority = plan.Authority
+ });
+ }
+ foreach (var candidate in detected.Bends.Where(x => !decisionIds.Contains(x.SourceBendId)))
+ accepted.Add(candidate);
+ var recognized = accepted.Where(x => x.Status == RecognizedBendStatus.Recognized).ToArray();
+ if (recognized.Length == 0)
+ diagnostics.Add(new(SheetMetalDiagnosticCodes.RecognitionPlanIncomplete, SheetMetalDiagnosticSeverity.Error,
+ "Source unfolding requires at least one explicitly recognized bend."));
+ ValidateGraph(plan.RootRegionId, recognized, detected.Regions, diagnostics);
+ var valid = diagnostics.All(x => x.Severity != SheetMetalDiagnosticSeverity.Error);
+ return new(valid, valid ? detected with { RootRegionId = plan.RootRegionId, Bends = accepted.OrderBy(x => x.SourceBendId, StringComparer.Ordinal).ToArray(), Diagnostics = detected.Diagnostics.Concat(diagnostics).ToArray() } : null, diagnostics);
+ }
+
+ private static void ValidateGraph(string root, IReadOnlyList<RecognizedBend> bends, IReadOnlyList<SheetRegionIr> regions, ICollection<SheetMetalDiagnostic> diagnostics)
+ {
+ var planar = regions.Where(x => x.Kind == SheetRegionKind.Planar).Select(x => x.StableId).ToHashSet(StringComparer.Ordinal);
+ var reached = new HashSet<string>(StringComparer.Ordinal) { root }; var edges = 0; var queue = new Queue<string>(); queue.Enqueue(root);
+ while (queue.Count > 0)
+ {
+ var current = queue.Dequeue();
+ foreach (var bend in bends.Where(x => x.Geometry.AdjacentRegionA == current || x.Geometry.AdjacentRegionB == current))
+ {
+ var next = bend.Geometry.AdjacentRegionA == current ? bend.Geometry.AdjacentRegionB : bend.Geometry.AdjacentRegionA;
+ edges++;
+ if (reached.Add(next)) queue.Enqueue(next);
+ }
+ }
+ if (edges / 2 >= reached.Count)
+ diagnostics.Add(new(SheetMetalDiagnosticCodes.RegionGraphCycle, SheetMetalDiagnosticSeverity.Error,
+ "Recognized bend graph contains a cycle; one unambiguous unfold transform per region cannot be established."));
+ var admittedRegions = bends.SelectMany(x => new[] { x.Geometry.AdjacentRegionA, x.Geometry.AdjacentRegionB }).Append(root).ToHashSet(StringComparer.Ordinal);
+ var missing = admittedRegions.Where(x => planar.Contains(x) && !reached.Contains(x)).Order(StringComparer.Ordinal).ToArray();
+ if (missing.Length > 0)
+ diagnostics.Add(new(SheetMetalDiagnosticCodes.DisconnectedGraph, SheetMetalDiagnosticSeverity.Error,
+ $"Recognized bend graph is disconnected from root '{root}': {string.Join(", ", missing)}."));
+ }
+
+ private static bool IsGeometricallyStrong(SheetBendIr bend, SheetMetalPartIr part) =>
+ bend.Source.FaceIds.Count >= 2 && bend.InsideRadius >= 0d && bend.Thickness > 0d &&
+ double.IsFinite(bend.BendAngleRadians) && bend.BendAngleRadians > 1e-6 && bend.BendAngleRadians < Math.PI * 2d - 1e-6 &&
+ bend.AxisDirection.TryNormalize(out _) && bend.AdjacentRegionA != bend.AdjacentRegionB &&
+ part.Regions.Any(x => x.StableId == bend.AdjacentRegionA && x.Kind == SheetRegionKind.Planar) &&
+ part.Regions.Any(x => x.StableId == bend.AdjacentRegionB && x.Kind == SheetRegionKind.Planar) &&
+ part.Regions.Any(x => x.Kind == SheetRegionKind.CylindricalBend && x.Source.FaceIds.SequenceEqual(bend.Source.FaceIds));
+
+ private static string DefaultName(SheetMetalPartIr part, SheetBendIr bend, int index)
+ {
+ if (bend.AdjacentRegionA == part.BaseRegionId || bend.AdjacentRegionB == part.BaseRegionId)
+ {
+ var other = bend.AdjacentRegionA == part.BaseRegionId ? bend.AdjacentRegionB : bend.AdjacentRegionA;
+ var suffix = other.Split('-').LastOrDefault() ?? (index + 1).ToString("D2", CultureInfo.InvariantCulture);
+ return $"BaseFlangeBend{suffix}";
+ }
+ return $"RecoveredBend{index + 1:D2}";
+ }
+}
diff --git a/Aetheris.SheetMetal/RecoveredFlatComparer.cs b/Aetheris.SheetMetal/RecoveredFlatComparer.cs
new file mode 100644
index 00000000..618f7cfc
--- /dev/null
+++ b/Aetheris.SheetMetal/RecoveredFlatComparer.cs
@@ -0,0 +1,75 @@
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.SheetMetal;
+
+public sealed record RecoveredFlatComparisonReport(
+ SheetMetalComparisonStatus Status,
+ SheetResidualStatistics SourceToNative,
+ SheetResidualStatistics NativeToSource,
+ double WidthResidual,
+ double HeightResidual,
+ int CutCountDelta,
+ int BendLineCountDelta,
+ IReadOnlyList<string> LocalizedDifferences);
+
+public static class RecoveredFlatComparer
+{
+ public static RecoveredFlatComparisonReport Compare(RecoveredFlatReference source, SheetMetalFlatPatternIr native,
+ double tolerance = .1d)
+ {
+ ArgumentNullException.ThrowIfNull(source); ArgumentNullException.ThrowIfNull(native);
+ var sourcePoints = Points(source.OuterAndInnerContours, source.Regions.SelectMany(x => x.Boundary));
+ var nativePoints = Points(native.ExactBlankContour, native.Boundary);
+ var sourceOrigin = Origin(sourcePoints); var nativeOrigin = Origin(nativePoints);
+ sourcePoints = Translate(sourcePoints, sourceOrigin); nativePoints = Translate(nativePoints, nativeOrigin);
+ var sourceToNative = Stats(sourcePoints.Select(x => Nearest(x, nativePoints)));
+ var nativeToSource = Stats(nativePoints.Select(x => Nearest(x, sourcePoints)));
+ var width = Math.Abs((source.Bounds?.Width ?? Extent(sourcePoints, true)) - (native.Bounds?.Width ?? Extent(nativePoints, true)));
+ var height = Math.Abs((source.Bounds?.Height ?? Extent(sourcePoints, false)) - (native.Bounds?.Height ?? Extent(nativePoints, false)));
+ var cuts = native.CutLoops.Count - source.InnerContours.Count;
+ var bends = native.BendLines.Count - source.BendLines.Count;
+ var differences = new List<string>();
+ if (width > tolerance) differences.Add($"Outer width differs by {width:G6} mm.");
+ if (height > tolerance) differences.Add($"Outer height differs by {height:G6} mm.");
+ if (sourceToNative.P95 > tolerance) differences.Add($"Source outer contour has unmatched detail (p95 {sourceToNative.P95:G6} mm, max {sourceToNative.Maximum:G6} mm).");
+ if (nativeToSource.P95 > tolerance) differences.Add($"Native outer contour has unmatched/shifted detail (p95 {nativeToSource.P95:G6} mm, max {nativeToSource.Maximum:G6} mm).");
+ if (cuts != 0) differences.Add($"Cut inventory differs: source {source.InnerContours.Count}, native {native.CutLoops.Count}.");
+ if (bends != 0) differences.Add($"Bend-line inventory differs: source {source.BendLines.Count}, native {native.BendLines.Count}.");
+ foreach (var region in source.Regions.Where(x => x.Kind == SheetRegionKind.Planar))
+ {
+ var local = Translate(region.Boundary, sourceOrigin).Select(x => Nearest(x, nativePoints)).DefaultIfEmpty(double.PositiveInfinity).Max();
+ if (local > tolerance) differences.Add($"{region.SourceRegionId}.Outer has local residual {local:G6} mm.");
+ }
+ var status = source.Status == FlatPatternStatus.Valid && native.Status is FlatPatternStatus.Valid or FlatPatternStatus.Partial &&
+ width <= tolerance && height <= tolerance && sourceToNative.P95 <= tolerance && nativeToSource.P95 <= tolerance && cuts == 0 && bends == 0
+ ? SheetMetalComparisonStatus.Pass : SheetMetalComparisonStatus.NeedsReview;
+ return new(status, sourceToNative, nativeToSource, width, height, cuts, bends, differences);
+ }
+
+ private static IReadOnlyList<SheetPoint2> Points(PlanarContour2? contour, IEnumerable<SheetPoint2> fallback)
+ {
+ if (contour is null) return fallback.ToArray();
+ return contour.OuterLoop.Segments.SelectMany(x => x.Geometry switch
+ {
+ LineArcLineSegment2D line => Enumerable.Range(0, 5).Select(i => new SheetPoint2(line.Start.X + (line.End.X - line.Start.X) * i / 4d, line.Start.Y + (line.End.Y - line.Start.Y) * i / 4d)),
+ LineArcCircularArc2D arc => Enumerable.Range(0, Math.Max(4, (int)Math.Ceiling(Math.Abs(arc.SweepAngleRadians) / (Math.PI / 36d)))).Select(i =>
+ {
+ var count = Math.Max(4, (int)Math.Ceiling(Math.Abs(arc.SweepAngleRadians) / (Math.PI / 36d))); var a = arc.StartAngleRadians + arc.SweepAngleRadians * i / (count - 1d);
+ return new SheetPoint2(arc.Center.X + arc.Radius * Math.Cos(a), arc.Center.Y + arc.Radius * Math.Sin(a));
+ }),
+ LineArcFullCircle2D circle => Enumerable.Range(0, 72).Select(i => new SheetPoint2(circle.Center.X + circle.Radius * Math.Cos(Math.PI * 2d * i / 72d), circle.Center.Y + circle.Radius * Math.Sin(Math.PI * 2d * i / 72d))),
+ _ => []
+ }).ToArray();
+ }
+
+ private static SheetPoint2 Origin(IReadOnlyList<SheetPoint2> points) => points.Count == 0 ? default : new(points.Min(x => x.X), points.Min(x => x.Y));
+ private static IReadOnlyList<SheetPoint2> Translate(IReadOnlyList<SheetPoint2> points,SheetPoint2 origin) => points.Select(x => new SheetPoint2(x.X-origin.X,x.Y-origin.Y)).ToArray();
+ private static double Extent(IReadOnlyList<SheetPoint2> p, bool x) => p.Count == 0 ? 0d : x ? p.Max(q => q.X) - p.Min(q => q.X) : p.Max(q => q.Y) - p.Min(q => q.Y);
+ private static double Nearest(SheetPoint2 p, IReadOnlyList<SheetPoint2> q) => q.Count == 0 ? double.PositiveInfinity : q.Min(x => Math.Sqrt((p.X - x.X) * (p.X - x.X) + (p.Y - x.Y) * (p.Y - x.Y)));
+ private static SheetResidualStatistics Stats(IEnumerable<double> values)
+ {
+ var v = values.Where(double.IsFinite).Order().ToArray();
+ return v.Length == 0 ? new(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, 0) :
+ new(Math.Sqrt(v.Average(x => x * x)), v[(int)Math.Ceiling(.95d * v.Length) - 1], v[^1], v.Length);
+ }
+}
diff --git a/Aetheris.SheetMetal/RecoveredSourceFlattener.cs b/Aetheris.SheetMetal/RecoveredSourceFlattener.cs
new file mode 100644
index 00000000..b22c9147
--- /dev/null
+++ b/Aetheris.SheetMetal/RecoveredSourceFlattener.cs
@@ -0,0 +1,303 @@
+using System.Diagnostics;
+using Aetheris.Kernel.Core.Brep;
+using Aetheris.Kernel.Core.Geometry;
+using Aetheris.Kernel.Core.Math;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.SheetMetal;
+
+/// <summary>
+/// Unfolds the imported body's geometric mid-surface from an explicitly validated bend
+/// set. This is a forensic recovery reference, not an authored manufacturing flat.
+/// </summary>
+public static class RecoveredSourceFlattener
+{
+ private const double Tolerance = 1e-7;
+
+ public static RecoveredFlatReference Flatten(RecognizedSheetMetalModel detected, SheetMetalRecognitionPlan plan)
+ {
+ ArgumentNullException.ThrowIfNull(detected); ArgumentNullException.ThrowIfNull(plan);
+ var graphClock = Stopwatch.StartNew();
+ var validation = RecognizedSheetMetalRecovery.ValidatePlan(detected, plan);
+ graphClock.Stop();
+ if (!validation.IsValid || validation.Model is null)
+ return Failed(detected, plan, validation.Diagnostics, graphClock.Elapsed);
+ var model = validation.Model;
+ var accepted = model.Bends.Where(x => x.Status == RecognizedBendStatus.Recognized).Select(x => x.Geometry).ToArray();
+ var referencePolicy = plan.ReferenceKind switch
+ {
+ RecoveredFlatReferenceKind.GeometricMidSurface => new SheetMetalFlattenPolicy(.5d),
+ _ => model.DetectedPart.FlatPatternPolicy
+ };
+ var part = model.DetectedPart with
+ {
+ BaseRegionId = plan.RootRegionId,
+ Bends = accepted,
+ FlatPatternPolicy = referencePolicy,
+ RecognitionStatus = SheetMetalRecognitionStatus.Complete
+ };
+
+ var unfoldClock = Stopwatch.StartNew();
+ var geometric = SheetMetalFlattener.Flatten(part, referencePolicy);
+ unfoldClock.Stop();
+ var diagnostics = validation.Diagnostics.Concat(geometric.Diagnostics).ToList();
+ var mappings = geometric.SourceToFlatMappings.ToDictionary(x => x.SourceRegionId, StringComparer.Ordinal);
+ var exactRegions = new List<FlatRegion2D>();
+ var provenance = new List<RecoveredFlatSegmentProvenance>();
+ foreach (var region in geometric.Regions2D.OrderBy(x => x.StableId, StringComparer.Ordinal))
+ {
+ if (region.Kind != SheetRegionKind.Planar || !mappings.TryGetValue(region.SourceRegionId, out var mapping))
+ {
+ exactRegions.Add(region);
+ continue;
+ }
+ var source = model.Regions.Single(x => x.StableId == region.SourceRegionId);
+ var exact = ExtractRegionOuter(model.SourceBody, source, mapping, diagnostics, provenance);
+ exactRegions.Add(region with
+ {
+ ExactContour = exact ?? region.ExactContour,
+ Boundary = exact is null ? region.Boundary : Vertices(exact),
+ MappingKind = exact is null ? region.MappingKind : "exact source BRep line/arc loop through geometric mid-surface unfold transform"
+ });
+ }
+
+ var exactCuts = geometric.CutLoops.Select(cut =>
+ {
+ if (!mappings.TryGetValue(cut.SourceRegionId, out var mapping)) return cut;
+ var feature = model.Cuts.First(x => x.StableId == cut.FeatureId);
+ var exact = ExtractFeature(model.SourceBody, feature, mapping, diagnostics, provenance);
+ return exact is null ? cut : cut with { ExactContour = exact, Boundary = Vertices(exact) };
+ }).ToArray();
+
+ var stitchClock = Stopwatch.StartNew();
+ var stitched = Stitch(model, exactRegions, exactCuts, diagnostics, out var recoveryStitch);
+ stitchClock.Stop();
+ var allPoints = exactRegions.SelectMany(x => x.Boundary).Concat(exactCuts.SelectMany(x => x.Boundary)).ToArray();
+ var bounds = allPoints.Length == 0 ? null : new FlatPatternBounds(allPoints.Min(x => x.X), allPoints.Min(x => x.Y), allPoints.Max(x => x.X), allPoints.Max(x => x.Y));
+ var status = stitched is null || geometric.Status is FlatPatternStatus.Unsupported or FlatPatternStatus.Overlapping
+ ? geometric.Status == FlatPatternStatus.Overlapping ? FlatPatternStatus.Overlapping : FlatPatternStatus.Partial
+ : FlatPatternStatus.Valid;
+ var hashBasis = string.Join('|', plan.DeterministicHash, status, stitched?.Provenance ?? "no-stitched-contour",
+ string.Join(';', exactRegions.Select(x => $"{x.StableId}:{ContourSignature(x.ExactContour)}")),
+ string.Join(';', exactCuts.Select(x => $"{x.FeatureId}:{ContourSignature(x.ExactContour)}")),
+ geometric.DeterministicHash);
+ var hash = SheetMetalRecognizer.StableHash(hashBasis);
+ return new($"recovered-flat-{hash[..16]}", plan.ReferenceKind, plan.RootRegionId, "XY", stitched,
+ exactRegions, exactCuts, geometric.BendLines, geometric.SourceToFlatMappings, provenance.OrderBy(x => x.FlatSegmentId, StringComparer.Ordinal).ToArray(),
+ plan, bounds, status, diagnostics, recoveryStitch.Acceptance, recoveryStitch.Repairs, recoveryStitch.Summary,
+ hash, graphClock.Elapsed, unfoldClock.Elapsed, stitchClock.Elapsed);
+ }
+
+ public static SheetMetalFlatPatternIr ToFlatPattern(RecoveredFlatReference reference) => new(
+ reference.StableId, reference.Status, reference.Regions, reference.BendLines, reference.InnerContours,
+ reference.RegionMap, reference.OuterAndInnerContours is null ? reference.Regions.SelectMany(x => x.Boundary).ToArray() : Vertices(reference.OuterAndInnerContours),
+ reference.Bounds,
+ reference.ReferenceKind == RecoveredFlatReferenceKind.GeometricMidSurface ? new(.5d) : new(reference.BendLines.FirstOrDefault()?.KFactor ?? .5d),
+ [], reference.Diagnostics, reference.DeterministicHash, reference.OuterAndInnerContours);
+
+ private static PlanarContour2? ExtractRegionOuter(BrepBody body, SheetRegionIr region, SourceToFlatMapping mapping,
+ ICollection<SheetMetalDiagnostic> diagnostics, ICollection<RecoveredFlatSegmentProvenance> provenance)
+ {
+ foreach (var faceId in region.Source.FaceIds.Order())
+ {
+ var face = body.Topology.GetFace(new(faceId));
+ var loopId = face.LoopIds.FirstOrDefault();
+ if (loopId == default) continue;
+ var loop = ExtractLoop(body, loopId, region.StableId, region.Source.FaceIds, mapping, true, diagnostics, provenance);
+ if (loop is not null)
+ return new($"source-{region.StableId}", "XY", loop, [], $"Imported STEP face {faceId} exact outer loop unfolded from geometric mid-surface");
+ }
+ diagnostics.Add(new(SheetMetalDiagnosticCodes.SourceContourUnsupported, SheetMetalDiagnosticSeverity.Warning,
+ $"No exact source outer loop could be extracted for '{region.StableId}'.", region.Source.FaceIds));
+ return null;
+ }
+
+ private static PlanarContour2? ExtractFeature(BrepBody body, SheetFeatureIr feature, SourceToFlatMapping mapping,
+ ICollection<SheetMetalDiagnostic> diagnostics, ICollection<RecoveredFlatSegmentProvenance> provenance)
+ {
+ var wanted = feature.Source.EdgeIds.ToHashSet();
+ foreach (var faceId in feature.Source.FaceIds.Order())
+ {
+ var face = body.Topology.GetFace(new(faceId));
+ foreach (var loopId in face.LoopIds.Skip(1))
+ {
+ var edges = body.GetCoedgeIds(loopId).Select(body.GetCoedgeEdgeId).Select(x => x.Value).ToArray();
+ if (!edges.Any(wanted.Contains)) continue;
+ var loop = ExtractLoop(body, loopId, feature.OwningRegionId, feature.Source.FaceIds, mapping, false, diagnostics, provenance);
+ if (loop is not null)
+ return new($"source-{feature.StableId}", "XY", loop with { StableId = $"source-{feature.StableId}.inner", IsOuter = true }, [],
+ $"Imported STEP inner loop for {feature.StableId}; retained as standalone cut contour");
+ }
+ }
+ return null;
+ }
+
+ private static PlanarContourLoop2? ExtractLoop(BrepBody body, Aetheris.Kernel.Core.Topology.LoopId loopId, string owner,
+ IReadOnlyList<int> faceIds, SourceToFlatMapping mapping, bool outer, ICollection<SheetMetalDiagnostic> diagnostics,
+ ICollection<RecoveredFlatSegmentProvenance> provenance)
+ {
+ var segments = new List<PlanarContourSegment2>();
+ foreach (var coedgeId in body.GetCoedgeIds(loopId))
+ {
+ var coedge = body.Topology.GetCoedge(coedgeId); var edge = body.Topology.GetEdge(coedge.EdgeId);
+ var startId = coedge.IsReversed ? edge.EndVertexId : edge.StartVertexId;
+ var endId = coedge.IsReversed ? edge.StartVertexId : edge.EndVertexId;
+ if (!body.TryGetVertexPoint(startId, out var start3) || !body.TryGetVertexPoint(endId, out var end3)) continue;
+ var start = Map(mapping, start3); var end = Map(mapping, end3);
+ var id = $"{owner}.source-e{edge.Id.Value:D4}";
+ LineArcProfileCurve2D geometry;
+ if (body.Bindings.TryGetEdgeBinding(edge.Id, out var binding) && body.Geometry.TryGetCurve(binding.CurveGeometryId, out var curve) && curve is not null && curve.Kind == CurveGeometryKind.Circle3 && curve.Circle3 is { } circle)
+ {
+ var center = Map(mapping, circle.Center);
+ if (startId == endId && binding.TrimInterval is { } full && Math.Abs(full.End - full.Start) >= Math.PI * 2d - 1e-6)
+ {
+ if (!outer)
+ {
+ var p0 = new ProfileSegmentProvenance(id + ".0", owner, $"STEP-edge-{edge.Id.Value}", "imported full circle split into two exact semicircles for bounded arrangement", "XY");
+ var p1 = p0 with { StableId = id + ".1" };
+ segments.Add(new(id + ".0", new LineArcCircularArc2D((center.X, center.Y), circle.Radius, 0d, Math.PI), p0));
+ segments.Add(new(id + ".1", new LineArcCircularArc2D((center.X, center.Y), circle.Radius, Math.PI, Math.PI), p1));
+ provenance.Add(new(id + ".0", owner, faceIds, [edge.Id.Value], "source BRep full circle -> exact recovered semicircle 1"));
+ provenance.Add(new(id + ".1", owner, faceIds, [edge.Id.Value], "source BRep full circle -> exact recovered semicircle 2"));
+ continue;
+ }
+ geometry = new LineArcFullCircle2D((center.X, center.Y), circle.Radius);
+ }
+ else
+ {
+ var startAngle = Math.Atan2(start.Y - center.Y, start.X - center.X);
+ var positive = Math.Atan2(end.Y - center.Y, end.X - center.X) - startAngle;
+ while (positive <= 0d) positive += Math.PI * 2d;
+ var negative = positive - Math.PI * 2d;
+ var sourceMid = binding.TrimInterval is { } trim
+ ? circle.Evaluate((trim.Start + trim.End) / 2d)
+ : circle.Evaluate(0d);
+ var mid = Map(mapping, sourceMid);
+ if (coedge.IsReversed && binding.TrimInterval is { } reverseTrim)
+ mid = Map(mapping, circle.Evaluate((reverseTrim.End + reverseTrim.Start) / 2d));
+ var sweep = Distance(Point(center, circle.Radius, startAngle + positive / 2d), mid) <= Distance(Point(center, circle.Radius, startAngle + negative / 2d), mid) ? positive : negative;
+ geometry = new LineArcCircularArc2D((center.X, center.Y), circle.Radius, startAngle, sweep);
+ }
+ }
+ else
+ {
+ geometry = new LineArcLineSegment2D((start.X, start.Y), (end.X, end.Y));
+ if (body.Bindings.TryGetEdgeBinding(edge.Id, out var unsupportedBinding) && body.Geometry.TryGetCurve(unsupportedBinding.CurveGeometryId, out var unsupportedCurve) && unsupportedCurve?.Kind is not CurveGeometryKind.Line3)
+ diagnostics.Add(new(SheetMetalDiagnosticCodes.SourceContourUnsupported, SheetMetalDiagnosticSeverity.Warning,
+ $"Source edge {edge.Id.Value} on '{owner}' is {unsupportedCurve?.Kind}; its exact endpoints are retained as a bounded line fallback.", faceIds));
+ }
+ var p = new ProfileSegmentProvenance(id, owner, $"STEP-edge-{edge.Id.Value}", "imported BRep edge unfolded through recognized region transform", "XY");
+ segments.Add(new(id, geometry, p));
+ provenance.Add(new(id, owner, faceIds, [edge.Id.Value], "source BRep edge -> region mid-surface -> recovered flat contour"));
+ }
+ if (segments.Count == 0) return null;
+ // Every extracted contour is standalone authority at this stage. Feature
+ // loops become clockwise only when attached as holes to the stitched blank.
+ var normalized = NormalizeWinding(segments, true);
+ return new($"{owner}.source-loop-{loopId.Value:D4}", outer, normalized);
+ }
+
+ private static PlanarContour2? Stitch(RecognizedSheetMetalModel model, IReadOnlyList<FlatRegion2D> regions,
+ IReadOnlyList<FlatCutLoop> cuts, ICollection<SheetMetalDiagnostic> diagnostics, out RecoveryContourStitchResult recovery)
+ {
+ recovery = new(null, RecoveredContourAcceptance.Failed, [], new(0, 0, 0, 0, 0, 0d, "none", []), []);
+ if (regions.Any(x => x.ExactContour is null) || cuts.Any(x => x.ExactContour is null)) return null;
+ var bySource = regions.ToDictionary(x => x.SourceRegionId, StringComparer.Ordinal);
+ var ordered = new List<FlatRegion2D>(); var seen = new HashSet<string>(StringComparer.Ordinal); var queue = new Queue<string>();
+ void Add(string sourceId) { if (bySource.TryGetValue(sourceId, out var region) && seen.Add(region.StableId)) ordered.Add(region); }
+ Add(model.RootRegionId); queue.Enqueue(model.RootRegionId);
+ var admitted = model.Bends.Where(x => x.Status == RecognizedBendStatus.Recognized).OrderBy(x => x.SourceBendId, StringComparer.Ordinal).ToArray();
+ var reached = new HashSet<string>(StringComparer.Ordinal) { model.RootRegionId };
+ while (queue.Count > 0)
+ {
+ var current = queue.Dequeue();
+ foreach (var bend in admitted.Where(x => x.Geometry.AdjacentRegionA == current || x.Geometry.AdjacentRegionB == current))
+ {
+ Add(bend.SourceBendId);
+ var neighbor = bend.Geometry.AdjacentRegionA == current ? bend.Geometry.AdjacentRegionB : bend.Geometry.AdjacentRegionA;
+ if (reached.Add(neighbor)) { Add(neighbor); queue.Enqueue(neighbor); }
+ }
+ }
+ foreach (var region in regions.OrderBy(x => x.StableId, StringComparer.Ordinal)) if (seen.Add(region.StableId)) ordered.Add(region);
+ var operations = ordered.Select((x, i) => new PrismaticProfileOperation(
+ x.StableId, i == 0 ? PrismaticProfileIntent.Base : PrismaticProfileIntent.Add, x.StableId, 0, 1,
+ "recognized imported material region", x.SourceRegionId)).ToArray();
+ var profiles = regions.ToDictionary(x => x.StableId, x => PlanarContourKernel.ToResolvedProfile(x.ExactContour!, x.StableId), StringComparer.Ordinal);
+ var composed = ProfileArrangementBuilder.Compose("XY", operations, profiles, $"recovered-source-flat:{model.StableId}");
+ PlanarContour2? contour;
+ if (composed.Region is null)
+ {
+ foreach (var item in composed.Arrangement.Diagnostics)
+ diagnostics.Add(new(SheetMetalDiagnosticCodes.UnfoldCrack, SheetMetalDiagnosticSeverity.Information, $"Strict arrangement boundary: {item}"));
+ recovery = RecoveryContourStitcher.Stitch(composed.Arrangement, $"recovered-source-flat-{model.StableId}");
+ foreach (var item in recovery.Diagnostics)
+ diagnostics.Add(new(SheetMetalDiagnosticCodes.UnfoldCrack, SheetMetalDiagnosticSeverity.Warning, $"Recovery stitch: {item}"));
+ contour = recovery.Contour;
+ }
+ else
+ {
+ var profile = new ResolvedProfile2D($"recovered-source-flat-{model.StableId}", "XY", [composed.Region.Outer.Loops.Single()]);
+ contour = PlanarContourKernel.FromResolvedProfile(profile, "source-derived geometric mid-surface reference");
+ recovery = new(contour, RecoveredContourAcceptance.Exact, [],
+ new(composed.Arrangement.RetainedBoundaryFragmentCount, composed.Arrangement.IntersectionVertices.Count, 0, 1, 1, 0d, "strict-arrangement", []), []);
+ }
+ if (contour is null) return null;
+ // Cut ownership and closed-loop topology are already source facts. Attach the
+ // exact loops after material stitching so circle seam vertices are not mistaken
+ // for zero-width material ligaments by the material-union arrangement.
+ contour = contour with { InnerLoops = cuts.OrderBy(x => x.FeatureId, StringComparer.Ordinal)
+ .Select(x => ReverseLoop(x.ExactContour!.OuterLoop with { StableId = $"{x.FeatureId}.inner", IsOuter = false })).ToArray() };
+ var validation = PlanarContourKernel.Validate(contour);
+ foreach (var item in validation.Diagnostics)
+ diagnostics.Add(new(SheetMetalDiagnosticCodes.UnfoldCrack, item.Severity == PlanarContourDiagnosticSeverity.Error ? SheetMetalDiagnosticSeverity.Warning : SheetMetalDiagnosticSeverity.Information,
+ $"Recovered stitched contour: {item.Code}: {item.Message}"));
+ return validation.IsValid ? contour : null;
+ }
+
+ private static IReadOnlyList<PlanarContourSegment2> NormalizeWinding(IReadOnlyList<PlanarContourSegment2> segments, bool outer)
+ {
+ var area = Sample(segments).Select((p, i) => (p, q: Sample(segments)[(i + 1) % Sample(segments).Count])).Sum(x => x.p.X * x.q.Y - x.q.X * x.p.Y) / 2d;
+ return outer == (area > 0d) ? segments : Reverse(segments);
+ }
+
+ private static PlanarContourLoop2 ReverseLoop(PlanarContourLoop2 loop) => loop with { Segments = Reverse(loop.Segments) };
+ private static IReadOnlyList<PlanarContourSegment2> Reverse(IReadOnlyList<PlanarContourSegment2> segments) => segments.Reverse().Select(x => x with { Geometry = x.Geometry switch
+ {
+ LineArcLineSegment2D line => new LineArcLineSegment2D(line.End, line.Start),
+ LineArcCircularArc2D arc => arc with { StartAngleRadians = arc.StartAngleRadians + arc.SweepAngleRadians, SweepAngleRadians = -arc.SweepAngleRadians },
+ LineArcFullCircle2D circle => circle,
+ _ => x.Geometry
+ }}).ToArray();
+
+ private static IReadOnlyList<SheetPoint2> Sample(IReadOnlyList<PlanarContourSegment2> segments) => segments.SelectMany(x => x.Geometry switch
+ {
+ LineArcLineSegment2D line => [new SheetPoint2(line.Start.X, line.Start.Y)],
+ LineArcCircularArc2D arc => Enumerable.Range(0, Math.Max(2, (int)Math.Ceiling(Math.Abs(arc.SweepAngleRadians) / (Math.PI / 12d)))).Select(i =>
+ {
+ var a = arc.StartAngleRadians + arc.SweepAngleRadians * i / Math.Max(2, (int)Math.Ceiling(Math.Abs(arc.SweepAngleRadians) / (Math.PI / 12d)));
+ return new SheetPoint2(arc.Center.X + arc.Radius * Math.Cos(a), arc.Center.Y + arc.Radius * Math.Sin(a));
+ }),
+ LineArcFullCircle2D circle => Enumerable.Range(0, 48).Select(i => Point(new(circle.Center.X, circle.Center.Y), circle.Radius, Math.PI * 2d * i / 48d)),
+ _ => []
+ }).ToArray();
+
+ private static IReadOnlyList<SheetPoint2> Vertices(PlanarContour2 contour) => Sample(contour.OuterLoop.Segments);
+ private static string ContourSignature(PlanarContour2? contour) => contour is null ? "none" : string.Join(',', contour.Loops.SelectMany(x => x.Segments).Select(x => $"{x.StableId}:{x.Geometry}"));
+ private static SheetPoint2 Map(SourceToFlatMapping m, Point3D p)
+ {
+ var d = p - m.PlaneOrigin;
+ return Add(m.FlatOrigin, Add(Scale(m.FlatU, d.Dot(m.SourceU)), Scale(m.FlatV, d.Dot(m.SourceV))));
+ }
+ private static SheetPoint2 Point(SheetPoint2 center, double radius, double angle) => new(center.X + radius * Math.Cos(angle), center.Y + radius * Math.Sin(angle));
+ private static double Distance(SheetPoint2 a, SheetPoint2 b) => Math.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y));
+ private static SheetPoint2 Add(SheetPoint2 a, SheetPoint2 b) => new(a.X + b.X, a.Y + b.Y);
+ private static SheetPoint2 Scale(SheetPoint2 a, double s) => new(a.X * s, a.Y * s);
+
+ private static RecoveredFlatReference Failed(RecognizedSheetMetalModel model, SheetMetalRecognitionPlan plan,
+ IReadOnlyList<SheetMetalDiagnostic> diagnostics, TimeSpan graphTime)
+ {
+ var hash = SheetMetalRecognizer.StableHash(plan.DeterministicHash + "|invalid");
+ return new($"recovered-flat-{hash[..16]}", plan.ReferenceKind, plan.RootRegionId, "XY", null, [], [], [], [], [], plan,
+ null, FlatPatternStatus.Unsupported, diagnostics, RecoveredContourAcceptance.Failed, [], null, hash, graphTime, TimeSpan.Zero, TimeSpan.Zero);
+ }
+}
diff --git a/Aetheris.SheetMetal/RecoveryContourStitcher.cs b/Aetheris.SheetMetal/RecoveryContourStitcher.cs
new file mode 100644
index 00000000..84cd3a65
--- /dev/null
+++ b/Aetheris.SheetMetal/RecoveryContourStitcher.cs
@@ -0,0 +1,328 @@
+using System.Diagnostics;
+using Aetheris.Kernel.Core.Judgment;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.SheetMetal;
+
+public enum RecoveryJunctionKind
+{
+ ExactEndpointMatch,
+ WithinToleranceEndpointMatch,
+ PointTangentContinuation,
+ TangentContinuation,
+ AngularContinuation,
+ Ambiguous,
+ Rejected
+}
+
+public enum RecoveryRepairConfidence { Exact, Strong, Heuristic, Ambiguous }
+public enum RecoveredContourAcceptance { Exact, Recovered, RecoveredWithRepairs, NeedsReview, Failed }
+public sealed record RecoveryPoint2(double X, double Y);
+
+public sealed record RecoveryJunctionRepair(
+ string JunctionId,
+ RecoveryJunctionKind Kind,
+ RecoveryRepairConfidence Confidence,
+ RecoveryPoint2 CanonicalPoint,
+ IReadOnlyList<RecoveryPoint2> OriginalEndpoints,
+ double MaximumDisplacement,
+ IReadOnlyList<string> SourceSegmentIds,
+ IReadOnlyList<string> SourceRegionIds,
+ string Action,
+ string Evidence);
+
+public sealed record RecoveryStitchSummary(
+ int RetainedFragmentCount,
+ int JunctionCount,
+ int AmbiguousJunctionCount,
+ int CandidateInterpretationCount,
+ int AdmissibleInterpretationCount,
+ double MaximumEndpointDisplacement,
+ string SelectedInterpretation,
+ IReadOnlyList<string> Rejections,
+ double EndpointClusteringMilliseconds = 0d,
+ double CandidateSelectionMilliseconds = 0d,
+ double ContourValidationMilliseconds = 0d);
+
+public sealed record RecoveryContourStitchResult(
+ PlanarContour2? Contour,
+ RecoveredContourAcceptance Acceptance,
+ IReadOnlyList<RecoveryJunctionRepair> Repairs,
+ RecoveryStitchSummary Summary,
+ IReadOnlyList<string> Diagnostics);
+
+/// <summary>
+/// Recovery-only graph repair over material-classified arrangement fragments. It does
+/// not alter the general profile arrangement kernel and never performs a global Boolean.
+/// </summary>
+public static class RecoveryContourStitcher
+{
+ public const double ExactEndpointTolerance = 1e-7;
+ public const double JunctionTolerance = 0.02;
+ public const double MaximumRepairDisplacement = 0.05;
+ private const int MaximumInterpretations = 256;
+
+ public static RecoveryContourStitchResult Stitch(ProfileArrangement2D arrangement, string stableId)
+ {
+ ArgumentNullException.ThrowIfNull(arrangement);
+ var retained = arrangement.AtomicFragments.Where(x => x.Retained).OrderBy(x => x.StableId, StringComparer.Ordinal).ToArray();
+ var collapsed = retained.Where(IsMicroClosure).ToArray();
+ var fragments = retained.Except(collapsed).ToArray();
+ if (fragments.Length == 0) return Failed("No retained material boundary fragments were available.");
+
+ var clusterClock=Stopwatch.StartNew();
+ var endpoints = fragments.SelectMany(x => new[]
+ {
+ new Endpoint(x, true, Ends(x.Geometry).Start),
+ new Endpoint(x, false, Ends(x.Geometry).End)
+ }).OrderBy(x => x.Fragment.StableId, StringComparer.Ordinal).ThenBy(x => x.IsStart ? 0 : 1).ToArray();
+ var clusters = Cluster(endpoints);
+ clusterClock.Stop();
+ if (clusters.Any(x => x.MaximumDisplacement > MaximumRepairDisplacement))
+ return Failed("A recovery junction exceeded the maximum local displacement.", clusters.Count);
+
+ var nodeByEndpoint = clusters.SelectMany((cluster, index) => cluster.Endpoints.Select(x => (x, index)))
+ .ToDictionary(x => EndpointKey(x.x), x => x.index, StringComparer.Ordinal);
+ var incoming = new Dictionary<int, ArrangementFragment2D[]>();
+ var outgoing = new Dictionary<int, ArrangementFragment2D[]>();
+ for (var i = 0; i < clusters.Count; i++)
+ {
+ incoming[i] = clusters[i].Endpoints.Where(x => !x.IsStart).Select(x => x.Fragment).ToArray();
+ outgoing[i] = clusters[i].Endpoints.Where(x => x.IsStart).Select(x => x.Fragment).ToArray();
+ if (incoming[i].Length != outgoing[i].Length || incoming[i].Length is < 1 or > 2)
+ return Failed($"Junction {i} has unsupported incidence {incoming[i].Length}-in/{outgoing[i].Length}-out.", clusters.Count);
+ }
+
+ var ambiguousNodes = Enumerable.Range(0, clusters.Count).Where(i => incoming[i].Length == 2).ToArray();
+ var interpretationCount = 1 << ambiguousNodes.Length;
+ if (ambiguousNodes.Length >= 31 || interpretationCount > MaximumInterpretations)
+ return Failed($"The bounded recovery cap was exceeded ({ambiguousNodes.Length} ambiguous junctions).", clusters.Count);
+
+ var candidateClock=Stopwatch.StartNew();var candidates = new List<Interpretation>();
+ for (var mask = 0; mask < interpretationCount; mask++)
+ {
+ var next = new Dictionary<string, string>(StringComparer.Ordinal);
+ var score = 0d;
+ for (var node = 0; node < clusters.Count; node++)
+ {
+ var ins = incoming[node]; var outs = outgoing[node];
+ if (ins.Length == 1) { next[ins[0].StableId] = outs[0].StableId; score += PairScore(ins[0], outs[0]); continue; }
+ var bit = Array.IndexOf(ambiguousNodes, node);
+ var crossed = ((mask >> bit) & 1) != 0;
+ next[ins[0].StableId] = outs[crossed ? 1 : 0].StableId;
+ next[ins[1].StableId] = outs[crossed ? 0 : 1].StableId;
+ score += PairScore(ins[0], outs[crossed ? 1 : 0]) + PairScore(ins[1], outs[crossed ? 0 : 1]);
+ }
+ var loops = Walk(fragments, next);
+ var validation = ValidateInterpretation(loops, fragments.Length, clusters, nodeByEndpoint);
+ candidates.Add(new($"pairing-{mask:D3}", mask, loops, validation.IsAdmissible, score, validation.Reason));
+ }
+
+ var engine = new JudgmentEngine<IReadOnlyList<Interpretation>>();
+ var judgmentCandidates = candidates.Select(x => new JudgmentCandidate<IReadOnlyList<Interpretation>>(
+ x.Name, _ => x.IsAdmissible, _ => x.Score, _ => x.RejectionReason)).ToArray();
+ var judgment = engine.Evaluate(candidates, judgmentCandidates);
+ candidateClock.Stop();
+ if (!judgment.IsSuccess)
+ return new(null, RecoveredContourAcceptance.Failed, [],
+ new(fragments.Length, clusters.Count, ambiguousNodes.Length, interpretationCount, 0,
+ clusters.Max(x => x.MaximumDisplacement), "none", judgment.Rejections.Select(x => $"{x.CandidateName}: {x.Reason}").ToArray()),
+ ["No bounded topology/provenance interpretation produced one valid material loop."]);
+
+ var selected = candidates.Single(x => x.Name == judgment.Selection!.Value.Candidate.Name);
+ var loop = selected.Loops.Single();
+ var repairedGeometry = loop.Select(fragment => Snap(fragment.Geometry,
+ clusters[nodeByEndpoint[EndpointKey(new(fragment, true, Ends(fragment.Geometry).Start))]].Canonical,
+ clusters[nodeByEndpoint[EndpointKey(new(fragment, false, Ends(fragment.Geometry).End))]].Canonical)).ToArray();
+ var segments = loop.Select((fragment, index) => new PlanarContourSegment2(
+ $"{fragment.Source.Provenance.StableId}.recovery.{index:D4}", repairedGeometry[index],
+ fragment.Source.Provenance with { StableId = $"{fragment.Source.Provenance.StableId}.recovery.{index:D4}", Derivation = $"recovery-stitch:{fragment.StableId}:{fragment.FromParameter:R}..{fragment.ToParameter:R}" })).ToArray();
+ var contour = new PlanarContour2(stableId, arrangement.Frame,
+ new($"{stableId}.outer", true, segments), [], "topology-guided recovered source boundary");
+ var validationClock=Stopwatch.StartNew();var contourValidation = PlanarContourKernel.Validate(contour);validationClock.Stop();
+ if (!contourValidation.IsValid)
+ return new(null, RecoveredContourAcceptance.Failed, [],
+ new(fragments.Length, clusters.Count, ambiguousNodes.Length, interpretationCount, candidates.Count(x => x.IsAdmissible), clusters.Max(x => x.MaximumDisplacement), selected.Name,
+ candidates.Where(x => !x.IsAdmissible).Select(x => $"{x.Name}: {x.RejectionReason}").ToArray()),
+ contourValidation.Diagnostics.Select(x => $"{x.Code}: {x.Message}").ToArray());
+
+ var repairs = ambiguousNodes.Select(node => Repair(node, clusters[node], incoming[node], outgoing[node], selected.Mask, ambiguousNodes)).ToArray();
+ var collapsedRepairs = collapsed.Select((fragment, index) =>
+ {
+ var point=Ends(fragment.Geometry).Start;var key=VertexBucketKey(point);var incident=retained.Where(x=>VertexBucketKey(Ends(x.Geometry).Start)==key||VertexBucketKey(Ends(x.Geometry).End)==key).ToArray();
+ return new RecoveryJunctionRepair(
+ $"junction-micro-closure-{index:D4}", RecoveryJunctionKind.PointTangentContinuation, RecoveryRepairConfidence.Strong,
+ new(point.X, point.Y), incident.SelectMany(x=>new[]{Ends(x.Geometry).Start,Ends(x.Geometry).End}).Where(x=>VertexBucketKey(x)==key).Select(x=>new RecoveryPoint2(x.X,x.Y)).ToArray(),
+ Length(fragment.Geometry), incident.Select(x=>x.Source.Segment).Distinct().Order().ToArray(), incident.Select(x=>x.Source.Profile).Distinct().Order().ToArray(),
+ "collapse bounded single-fragment micro-closure and continue through its tangent junction",
+ $"retained analytic split remnant length {Length(fragment.Geometry):G12} mm and area {Math.Abs(Area([fragment])):G12} mm^2; incident directions {string.Join(", ",incident.Select(DirectionEvidence))}; source provenance retained" );
+ }).ToArray();
+ var collapsedKeys = collapsed.SelectMany(x => new[] { VertexBucketKey(Ends(x.Geometry).Start), VertexBucketKey(Ends(x.Geometry).End) }).ToHashSet(StringComparer.Ordinal);
+ var displaced = clusters.Where(x => x.MaximumDisplacement > ExactEndpointTolerance && !collapsedKeys.Contains(VertexBucketKey(x.Canonical))).Select((cluster, index) => new RecoveryJunctionRepair(
+ $"junction-snap-{index:D4}", RecoveryJunctionKind.WithinToleranceEndpointMatch, RecoveryRepairConfidence.Strong,
+ new(cluster.Canonical.X, cluster.Canonical.Y), cluster.Endpoints.Select(x=>new RecoveryPoint2(x.Point.X,x.Point.Y)).ToArray(), cluster.MaximumDisplacement, cluster.Endpoints.Select(x => x.Fragment.Source.Segment).Distinct().Order().ToArray(),
+ cluster.Endpoints.Select(x => x.Fragment.Source.Profile).Distinct().Order().ToArray(), "snap bounded endpoints to a source-supported canonical point",
+ $"maximum displacement {cluster.MaximumDisplacement:G12} mm <= {JunctionTolerance:G12} mm recovery tolerance")).ToArray();
+ var allRepairs = collapsedRepairs.Concat(repairs).Concat(displaced).OrderBy(x => x.JunctionId, StringComparer.Ordinal).ToArray();
+ var acceptance = allRepairs.Length == 0 ? RecoveredContourAcceptance.Recovered : RecoveredContourAcceptance.RecoveredWithRepairs;
+ return new(contour, acceptance, allRepairs,
+ new(retained.Length, clusters.Count, ambiguousNodes.Length + collapsed.Length, interpretationCount, candidates.Count(x => x.IsAdmissible), Math.Max(clusters.Max(x => x.MaximumDisplacement), collapsed.DefaultIfEmpty().Max(x => x is null ? 0d : Length(x.Geometry))), selected.Name,
+ candidates.Where(x => !x.IsAdmissible).Select(x => $"{x.Name}: {x.RejectionReason}").ToArray(),clusterClock.Elapsed.TotalMilliseconds,candidateClock.Elapsed.TotalMilliseconds,validationClock.Elapsed.TotalMilliseconds), []);
+ }
+
+ private static RecoveryJunctionRepair Repair(int node, JunctionCluster cluster, ArrangementFragment2D[] incoming, ArrangementFragment2D[] outgoing, int mask, int[] ambiguousNodes)
+ {
+ var bit = Array.IndexOf(ambiguousNodes, node); var crossed = ((mask >> bit) & 1) != 0;
+ var pairs = new[] { (incoming[0], outgoing[crossed ? 1 : 0]), (incoming[1], outgoing[crossed ? 0 : 1]) };
+ var tangent = pairs.All(x => TangentAlignment(x.Item1.Geometry, x.Item2.Geometry) >= .999999);
+ return new($"junction-{node:D4}", tangent ? RecoveryJunctionKind.PointTangentContinuation : RecoveryJunctionKind.AngularContinuation,
+ tangent ? RecoveryRepairConfidence.Strong : RecoveryRepairConfidence.Heuristic, new(cluster.Canonical.X, cluster.Canonical.Y), cluster.Endpoints.Select(x=>new RecoveryPoint2(x.Point.X,x.Point.Y)).ToArray(), cluster.MaximumDisplacement,
+ cluster.Endpoints.Select(x => x.Fragment.Source.Segment).Distinct().Order().ToArray(), cluster.Endpoints.Select(x => x.Fragment.Source.Profile).Distinct().Order().ToArray(),
+ $"resolve 2-in/2-out angular order with {pairs[0].Item1.Source.Segment}->{pairs[0].Item2.Source.Segment} and {pairs[1].Item1.Source.Segment}->{pairs[1].Item2.Source.Segment}",
+ $"bounded global interpretation {mask}; one simple material loop; provenance/tangent utility {pairs.Sum(x => PairScore(x.Item1, x.Item2)):G12}");
+ }
+
+ private static (bool IsAdmissible, string Reason) ValidateInterpretation(IReadOnlyList<IReadOnlyList<ArrangementFragment2D>> loops, int fragmentCount,
+ IReadOnlyList<JunctionCluster> clusters, IReadOnlyDictionary<string,int> nodeByEndpoint)
+ {
+ if (loops.Sum(x => x.Count) != fragmentCount) return (false, "not every retained fragment was consumed exactly once");
+ if (loops.Count != 1) return (false, $"produced {loops.Count} closed loops [{string.Join(", ", loops.Select(x => $"{Area(x):G12}/{x.Count}seg"))}] instead of one source blank outer loop");
+ var segments=loops[0].Select((fragment,index)=>new PlanarContourSegment2($"candidate-{index:D4}",Snap(fragment.Geometry,
+ clusters[nodeByEndpoint[EndpointKey(new(fragment,true,Ends(fragment.Geometry).Start))]].Canonical,
+ clusters[nodeByEndpoint[EndpointKey(new(fragment,false,Ends(fragment.Geometry).End))]].Canonical),fragment.Source.Provenance with{StableId=$"candidate-{index:D4}"})).ToArray();
+ var validation=PlanarContourKernel.Validate(new("candidate","XY",new("candidate.outer",true,segments),[],"recovery candidate"));
+ return validation.IsValid?(true,"strictly valid canonical contour"):(false,string.Join("; ",validation.Diagnostics.Select(x=>x.Code).Distinct()));
+ }
+
+ private static IReadOnlyList<IReadOnlyList<ArrangementFragment2D>> Walk(ArrangementFragment2D[] fragments, IReadOnlyDictionary<string, string> next)
+ {
+ var byId = fragments.ToDictionary(x => x.StableId, StringComparer.Ordinal); var used = new HashSet<string>(StringComparer.Ordinal); var loops = new List<IReadOnlyList<ArrangementFragment2D>>();
+ foreach (var seed in fragments)
+ {
+ if (used.Contains(seed.StableId)) continue;
+ var chain = new List<ArrangementFragment2D>(); var current = seed;
+ for (var guard = 0; guard <= fragments.Length; guard++)
+ {
+ if (!used.Add(current.StableId)) break;
+ chain.Add(current);
+ if (!next.TryGetValue(current.StableId, out var nextId) || !byId.TryGetValue(nextId, out current!)) break;
+ if (current.StableId == seed.StableId) break;
+ }
+ loops.Add(chain);
+ }
+ return loops;
+ }
+
+ private static List<JunctionCluster> Cluster(IReadOnlyList<Endpoint> endpoints)
+ {
+ static string StrictKey(Endpoint x)
+ {
+ return VertexBucketKey(x.Point);
+ }
+ var clusters = endpoints.GroupBy(StrictKey, StringComparer.Ordinal)
+ .OrderBy(x => x.Key, StringComparer.Ordinal).Select(x => x.ToList()).ToList();
+ // Preserve all balanced strict nodes. The recovery tolerance may only close a
+ // complementary end/start gap owned by the same imported source profile.
+ for (var i = 0; i < clusters.Count; i++)
+ {
+ if (Balanced(clusters[i])) continue;
+ var matches = Enumerable.Range(i + 1, clusters.Count - i - 1)
+ .Where(j => !Balanced(clusters[j]) && Complementary(clusters[i], clusters[j]))
+ .Select(j => (Index: j, Distance: clusters[i].Min(a => clusters[j].Min(b => Distance(a.Point, b.Point)))))
+ .Where(x => x.Distance <= JunctionTolerance).OrderBy(x => x.Distance).ThenBy(x => x.Index).ToArray();
+ if (matches.Length == 0) continue;
+ var match = matches[0];
+ clusters[i].AddRange(clusters[match.Index]); clusters.RemoveAt(match.Index); i--;
+ }
+ return clusters.Select(x =>
+ {
+ // Prefer an analytic arc endpoint: lines can be snapped to it without moving circular support.
+ var canonical = x.OrderByDescending(y => y.Fragment.Geometry is LineArcCircularArc2D).ThenBy(y => y.Fragment.StableId, StringComparer.Ordinal).ThenBy(y => y.IsStart ? 0 : 1).First().Point;
+ return new JunctionCluster(x, canonical, x.Max(y => Distance(y.Point, canonical)));
+ }).ToList();
+ }
+
+ private static bool Balanced(IReadOnlyList<Endpoint> cluster) => cluster.Count(x => x.IsStart) == cluster.Count(x => !x.IsStart);
+ private static bool Complementary(IReadOnlyList<Endpoint> a, IReadOnlyList<Endpoint> b) =>
+ a.Concat(b).Select(x => x.Fragment.Source.Profile).Distinct(StringComparer.Ordinal).Count() == 1 &&
+ a.Count(x => x.IsStart) + b.Count(x => x.IsStart) == a.Count(x => !x.IsStart) + b.Count(x => !x.IsStart);
+
+ private static double PairScore(ArrangementFragment2D incoming, ArrangementFragment2D outgoing) =>
+ (incoming.Source.Profile == outgoing.Source.Profile ? 100d : 0d) +
+ (incoming.Source.Operation == outgoing.Source.Operation ? 25d : 0d) + 10d * TangentAlignment(incoming.Geometry, outgoing.Geometry);
+
+ private static bool IsMicroClosure(ArrangementFragment2D fragment) =>
+ VertexBucketKey(Ends(fragment.Geometry).Start) == VertexBucketKey(Ends(fragment.Geometry).End) && Length(fragment.Geometry) <= JunctionTolerance;
+
+ private static string VertexBucketKey((double X, double Y) point)
+ {
+ const double strictVertexBucket = 1e-5;
+ static double Bucket(double value) { var rounded = Math.Round(value / strictVertexBucket); return rounded == 0d ? 0d : rounded; }
+ return $"{Bucket(point.X):F0},{Bucket(point.Y):F0}";
+ }
+
+ private static double Length(LineArcProfileCurve2D curve) => curve switch
+ {
+ LineArcLineSegment2D line => Distance(line.Start, line.End),
+ LineArcCircularArc2D arc => Math.Abs(arc.Radius * arc.SweepAngleRadians),
+ _ => double.PositiveInfinity
+ };
+
+ private static double Area(IReadOnlyList<ArrangementFragment2D> loop) => loop.Sum(x => x.Geometry switch
+ {
+ LineArcLineSegment2D line => line.Start.X * line.End.Y - line.End.X * line.Start.Y,
+ LineArcCircularArc2D arc => ArcArea(arc),
+ _ => 0d
+ }) / 2d;
+ private static double ArcArea(LineArcCircularArc2D arc)
+ {
+ var a = arc.StartAngleRadians; var b = a + arc.SweepAngleRadians;
+ return arc.Center.X * arc.Radius * (Math.Sin(b) - Math.Sin(a)) - arc.Center.Y * arc.Radius * (Math.Cos(b) - Math.Cos(a)) + arc.Radius * arc.Radius * (b - a);
+ }
+
+ private static double TangentAlignment(LineArcProfileCurve2D incoming, LineArcProfileCurve2D outgoing)
+ {
+ var a = Tangent(incoming, false); var b = Tangent(outgoing, true); var al = Math.Sqrt(a.X * a.X + a.Y * a.Y); var bl = Math.Sqrt(b.X * b.X + b.Y * b.Y);
+ return al <= ExactEndpointTolerance || bl <= ExactEndpointTolerance ? -1d : (a.X * b.X + a.Y * b.Y) / (al * bl);
+ }
+ private static string DirectionEvidence(ArrangementFragment2D fragment)
+ {
+ var a=Tangent(fragment.Geometry,true);var b=Tangent(fragment.Geometry,false);
+ return $"{fragment.Source.Segment}:start=({a.X:G6},{a.Y:G6}),end=({b.X:G6},{b.Y:G6})";
+ }
+
+ private static LineArcProfileCurve2D Snap(LineArcProfileCurve2D geometry, (double X, double Y) start, (double X, double Y) end) => geometry switch
+ {
+ LineArcLineSegment2D => new LineArcLineSegment2D(start, end),
+ LineArcCircularArc2D arc => new LineArcCircularArc2D(arc.Center, arc.Radius, Math.Atan2(start.Y - arc.Center.Y, start.X - arc.Center.X), ArcSweep(arc, start, end)),
+ _ => geometry
+ };
+
+ private static double ArcSweep(LineArcCircularArc2D original, (double X, double Y) start, (double X, double Y) end)
+ {
+ var a = Math.Atan2(start.Y - original.Center.Y, start.X - original.Center.X); var b = Math.Atan2(end.Y - original.Center.Y, end.X - original.Center.X); var sweep = b - a;
+ if (original.SweepAngleRadians >= 0d) while (sweep <= 0d) sweep += 2d * Math.PI; else while (sweep >= 0d) sweep -= 2d * Math.PI;
+ return sweep;
+ }
+
+ private static ((double X, double Y) Start, (double X, double Y) End) Ends(LineArcProfileCurve2D curve) => curve switch
+ {
+ LineArcLineSegment2D line => (line.Start, line.End),
+ LineArcCircularArc2D arc => (At(arc, 0d), At(arc, 1d)),
+ _ => throw new NotSupportedException("Recovery stitching supports bounded lines and circular arcs.")
+ };
+ private static (double X, double Y) At(LineArcCircularArc2D arc, double t) => (arc.Center.X + arc.Radius * Math.Cos(arc.StartAngleRadians + arc.SweepAngleRadians * t), arc.Center.Y + arc.Radius * Math.Sin(arc.StartAngleRadians + arc.SweepAngleRadians * t));
+ private static (double X, double Y) Tangent(LineArcProfileCurve2D curve, bool atStart) => curve switch
+ {
+ LineArcLineSegment2D line => (line.End.X - line.Start.X, line.End.Y - line.Start.Y),
+ LineArcCircularArc2D arc => (-Math.Sin(arc.StartAngleRadians + (atStart ? 0d : arc.SweepAngleRadians)) * Math.Sign(arc.SweepAngleRadians), Math.Cos(arc.StartAngleRadians + (atStart ? 0d : arc.SweepAngleRadians)) * Math.Sign(arc.SweepAngleRadians)),
+ _ => (0d, 0d)
+ };
+ private static double Distance((double X, double Y) a, (double X, double Y) b) => Math.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y));
+ private static string EndpointKey(Endpoint endpoint) => $"{endpoint.Fragment.StableId}:{(endpoint.IsStart ? 's' : 'e')}";
+ private static RecoveryContourStitchResult Failed(string message, int junctionCount = 0) => new(null, RecoveredContourAcceptance.Failed, [], new(0, junctionCount, 0, 0, 0, 0d, "none", [message]), [message]);
+
+ private sealed record Endpoint(ArrangementFragment2D Fragment, bool IsStart, (double X, double Y) Point);
+ private sealed record JunctionCluster(IReadOnlyList<Endpoint> Endpoints, (double X, double Y) Canonical, double MaximumDisplacement);
+ private sealed record Interpretation(string Name, int Mask, IReadOnlyList<IReadOnlyList<ArrangementFragment2D>> Loops, bool IsAdmissible, double Score, string RejectionReason);
+}
diff --git a/Aetheris.SheetMetal/SheetMetalIr.cs b/Aetheris.SheetMetal/SheetMetalIr.cs
index f2049617..ab70d7ea 100644
--- a/Aetheris.SheetMetal/SheetMetalIr.cs
+++ b/Aetheris.SheetMetal/SheetMetalIr.cs
@@ -6,6 +6,8 @@ using Aetheris.Surfacing;
namespace Aetheris.SheetMetal;
public enum SheetMetalRecognitionStatus { Complete, Partial, Ambiguous, Unsupported }
+public enum RecognizedBendStatus { Candidate, Recognized, Rejected, Ambiguous }
+public enum RecoveredFlatReferenceKind { GeometricMidSurface, ManufacturingNeutralSurface }
public enum SheetRegionKind { Planar, CylindricalBend, Developable, Unsupported }
public enum SheetBendDirection { Up, Down, Unknown }
public enum SheetFeatureKind { CircularHole, ProfileHole, Slot, Cutout, Unsupported }
@@ -42,11 +44,19 @@ public static class SheetMetalDiagnosticCodes
public const string FormedBodyInvalid = "sheetmetal-formed-body-invalid";
public const string ExactBlankContour = "sheetmetal-exact-blank-contour";
public const string FlangeBelowMinimum = "sheetmetal-flange-below-minimum";
+ public const string RecognitionAssertionInvalid = "sheetmetal-recognition-assertion-invalid";
+ public const string RecognitionPlanIncomplete = "sheetmetal-recognition-plan-incomplete";
+ public const string RegionGraphCycle = "sheetmetal-region-graph-cycle";
+ public const string UnfoldCrack = "sheetmetal-unfold-crack";
+ public const string UnfoldDuplicateBoundary = "sheetmetal-unfold-duplicate-boundary";
+ public const string SourceContourUnsupported = "sheetmetal-source-contour-unsupported";
public static IReadOnlyList<string> All { get; } =
[NonConstantThickness, UnpairedFaces, NonDevelopable, AmbiguousBendAxis, UnsupportedBendTopology,
InconsistentBendRadius, DisconnectedGraph, FlatOverlap, FeatureMappingFailure, InvalidRadius,
DuplicateCut, BendLineOutsideMaterial, ZeroWidthSliver, DuplicateFlange, ImpossibleTopology,
- InvalidRelief, CutCrossesBend, FormedBodyInvalid, ExactBlankContour, FlangeBelowMinimum];
+ InvalidRelief, CutCrossesBend, FormedBodyInvalid, ExactBlankContour, FlangeBelowMinimum,
+ RecognitionAssertionInvalid, RecognitionPlanIncomplete, RegionGraphCycle, UnfoldCrack,
+ UnfoldDuplicateBoundary, SourceContourUnsupported];
}
public sealed record SheetMetalDiagnostic(
diff --git a/Aetheris.SheetMetal/SheetMetalSemanticLayout.cs b/Aetheris.SheetMetal/SheetMetalSemanticLayout.cs
index 99b7ad33..4aae2a30 100644
--- a/Aetheris.SheetMetal/SheetMetalSemanticLayout.cs
+++ b/Aetheris.SheetMetal/SheetMetalSemanticLayout.cs
@@ -97,6 +97,7 @@ internal static class SheetMetalSemanticLayoutParser
steppedNotches.Add(new(Path(block),match.Groups["region"].Value,match.Groups["edge"].Value,center,width,depth,shoulder,outerChamfer,innerChamfer,side));
}
+
foreach(var block in CornerBlocks(source,structs))
{
var owner=Regex.Match(block.Name,@"^(?<region>[A-Za-z_][A-Za-z0-9_]*)\.(?<corner>RootStart|RootEnd|OuterStart|OuterEnd)$",Rx);
diff --git a/docs/language/semantic-profile-corner-composition-m3.md b/docs/language/semantic-profile-corner-composition-m3.md
index 2db02ece..2d731cc1 100644
--- a/docs/language/semantic-profile-corner-composition-m3.md
+++ b/docs/language/semantic-profile-corner-composition-m3.md
@@ -92,7 +92,12 @@ RearWall 0.96/0.96/0.96 mm, LeftWall 1.78/2.13/2.13 mm,
FrontMountingFlange 0.95/0.95/0.95 mm, and RearMountingFlange
0.95/0.95/0.95 mm RMS/p95/max. RightWall remains 64.78/115.48/115.48 mm in
that deliberately coarse vertex-only audit because its persistent interior
-edge program is still missing.
+edge program is still missing. The later recognized-import recovery M1 source
+unfold confirms the geometry behind this statement but corrects its design
+interpretation: the wall is an ordinary outer carrier with two 63.5 mm local
+cutback runs, two 15.24 mm diagonal transitions, two R12.7 outer corners, and
+the existing partial service-flange attachment. It does not justify a general
+persistent edge-program language.
One measured run reported parse 27.6 ms, semantic resolve 17.3 ms, formed lower
75.1 ms, exact authored-flat lower 62.6 ms, and flatten 8.8 ms (about 191 ms
diff --git a/docs/modules/sheet-metal.md b/docs/modules/sheet-metal.md
index 4312038a..a8bdf53b 100644
--- a/docs/modules/sheet-metal.md
+++ b/docs/modules/sheet-metal.md
@@ -90,6 +90,8 @@ Canonical M4 dogfood is [`m4-psu-enclosure.firmament`](../../fixtures/FirmamentV
The [M8 CTC-03 evidence bundle](sheetmetal/artifacts/m8/README.md) records full opening recovery, semantic-layout authoring, independent regeneration, comparison, PMI evidence, generalization, timings, and the remaining outer-contour blocker.
+The [recognized-import recovery M1 report](sheetmetal/artifacts/recovery-m1/README.md) separates detected bend candidates from accepted recognition authority and adds direct imported-body geometric mid-surface unfolding. Its CTC-03 run preserves exact per-region line/arc contours, all 17 source openings, seven bend lines, and source edge ancestry before any native reconstruction. Exact single-loop stitching remains partial at three source point-tangent junctions and is reported as such.
+
## Bounded capability verdict
M4 can generate production-like exact blanks for common line/arc brackets, channels, open/miter trays, nested lips, cuts, and individual rectangular/round relief cases without generic BRep Boolean. It is not yet commercial sheet-metal parity: the largest blocker is robust simultaneous multi-corner relief/seam resolution—including exact formed curved relief walls and hostile historical trim reconstruction—without arrangement ambiguity.
diff --git a/docs/modules/sheetmetal/artifacts/recovery-m1/README.md b/docs/modules/sheetmetal/artifacts/recovery-m1/README.md
new file mode 100644
index 00000000..54af6750
--- /dev/null
+++ b/docs/modules/sheetmetal/artifacts/recovery-m1/README.md
@@ -0,0 +1,219 @@
+# Recognized imported Sheet Metal recovery M1
+
+> Superseded for contour-stitch status by Recovery M2: CTC-03 now has one valid
+> recovered outer contour after three explicit recovery-only point-tangent
+> micro-closure repairs. The M1 metrics below remain the historical baseline.
+
+## Verdict
+
+**Meaningful progression.** Aetheris can now distinguish machine bend
+candidates from accepted bend authority, validate an engineer/LLM recognition
+plan against the imported BRep, and unfold only the accepted bends directly
+from imported geometry. CTC-03 produces exact source-derived line/arc contours
+for every planar region, 17 exact opening contours, seven bend lines, and 118
+source-edge provenance links. It does not yet produce one validated global
+`PlanarContour2`: the bounded arrangement rejects three point-tangent junctions
+in the hostile blank, so the source reference correctly remains `Partial`.
+
+This is a recovery reference, not manufacturing authority and not a claim of
+complete CTC-03 reconstruction.
+
+## Existing recovery audit
+
+Before this change, `SheetMetalRecognizer` already recovered:
+
+- dominant constant thickness from tolerance-bounded opposing plane/cylinder
+ pairs through `JudgmentEngine`;
+- planar mid-surface regions and paired cylindrical bend regions;
+- bend axes, angles, inside radii, directions, two-region adjacency, source
+ face/edge bindings, and evidence;
+- CTC-03's 8 planar regions, 7 bend regions, 15 circular holes, and 2 slots;
+- a deterministic graph traversal and K-factor manufacturing flat.
+
+The old imported flat treated every recovered cylinder adjacency as authority,
+used polygon vertices for source regions, and exposed a convex hull as the
+imported boundary. It therefore could not answer what the source free edges
+actually looked like.
+
+## Architecture and implemented types
+
+```text
+STEP / imported BRep
+ -> SheetMetalRecognizer (detected facts)
+ -> RecognizedSheetMetalModel
+ RecognizedBend: Candidate | Recognized | Rejected | Ambiguous
+ -> SheetMetalRecognitionPlan (explicit root, reference, decisions, names)
+ -> ValidatePlan (cylinder, radius, angle, adjacency, connectivity, cycle)
+ -> RecoveredSourceFlattener
+ -> RecoveredFlatReference
+ exact per-region contours + exact cuts + bend lines + ancestry
+ -> RecoveredFlatComparer
+ -> native Firmament flat
+```
+
+The public records are in `RecognizedSheetMetalModel.cs`; unfolding is in
+`RecoveredSourceFlattener.cs`; comparison is in `RecoveredFlatComparer.cs`.
+`SheetMetalPartIr` remains authored/native IR. The recognized model is an
+interpretation of immutable source geometry.
+
+## Recognition authority and human/LLM assertion
+
+Detection emits all seven CTC bends as `Candidate`. The automatic plan changes
+only candidates with complete paired cylindrical support, a finite bounded
+angle, nonnegative radius, and exactly two recovered planar neighbors to
+`Recognized`. Source unfolding consumes only that recognized subset.
+
+The test suite renames one accepted assertion to `FrontWallBend` with authority
+`engineer/LLM assertion checked against imported geometry`; the compiler
+accepts it while preserving the raw bend ID and face pair. A second test
+asserts an invented bend and receives
+`sheetmetal-recognition-assertion-invalid` because no detected cylindrical
+support exists.
+
+## CTC-03 bend evidence
+
+All values below are measured source facts; tolerance is 0.01 mm linear and
+0.001 rad angular.
+
+| source bend | axis | angle | inside R | adjacent regions | status |
+|---|---|---:|---:|---|---|
+| `bend-c-0005-0024` | X at Y=440.9948, Z=8.25754 | 90° | 6.35 | 0061-0066 ↔ 0088-0089 | Recognized |
+| `bend-c-0006-0009` | X at Y=43.47972, Z=8.25754 | 90° | 6.35 | 0062-0063 ↔ 0096-0097 | Recognized |
+| `bend-c-0046-0050` | Y at X=14.60754, Z=113.56594 | 45° | 6.35 | 0109-0111 ↔ 0118-0119 | Recognized |
+| `bend-c-0057-0070` | Y at X=0, Z=84.45754 | 90° | 6.35 | 0065-0069 ↔ 0118-0119 | Recognized |
+| `bend-c-0058-0064` | X at Y=58.08726, Z=69.85 | 90° | 6.35 | 0062-0063 ↔ 0065-0069 | Recognized |
+| `bend-c-0059-0068` | Y at X=-241.3, Z=84.45754 | 90° | 6.35 | 0065-0069 ↔ 0102-0104 | Recognized |
+| `bend-c-0060-0067` | X at Y=426.38726, Z=69.85 | 90° | 6.35 | 0061-0066 ↔ 0065-0069 | Recognized |
+
+Each has paired coaxial cylinder faces, exact source adjacency, and confidence
+1.0 under this bounded recognizer.
+
+## Source unfolding semantics
+
+The explicit root is `region-p-0065-0069`, the dominant deck. Plane-to-flat
+maps are propagated across the recognized region/bend graph. M1 uses the
+**geometric mid-surface**: planar source loops are projected to paired-face
+midplanes and cylindrical strips use `inside radius + 0.5 * thickness`. This
+is geometric unrolling of the formed reference surface.
+
+It is not a shop flat and makes no material/K-factor claim. A manufacturing
+flat uses authored neutral-axis policy `inside radius + K * thickness`. They
+coincide only when K=0.5; the artifact records `GeometricMidSurface` explicitly
+so incompatible conventions cannot be compared silently.
+
+## Recovered CTC flat and right-wall diagnosis
+
+Generated working artifacts:
+
+- `artifacts/sheetmetal-recovery-m1/ctc03/recognition-plan.json`
+- `artifacts/sheetmetal-recovery-m1/ctc03/recovered-flat.json`
+- `artifacts/sheetmetal-recovery-m1/ctc03/recovered-flat.svg`
+
+Observed bounds are 404.754237721 × 625.305580354 mm. Inventory is 15
+unfolded material regions (8 planar plus 7 bend strips), 17 exact inner loops,
+7 bend lines, and 118 source ancestry entries. All planar free edges retain
+native lines/arcs; circular holes remain analytic semicircle pairs and slots
+retain line/arc capsules.
+
+The actual right-wall source region is no longer ambiguous. In recovered-flat
+coordinates it has:
+
+- R12.7 outer transitions at both wall ends;
+- a baseline outer carrier at X=352.445;
+- two diagonal 15.24 × 15.24 transitions into recessed X=337.205 runs;
+- two 63.5 mm recessed runs adjacent to the service attachment;
+- a 127 mm service-bend span at X=349.804;
+- the existing partial angled service flange and rounded service tab.
+
+The earlier geometric observation of multiple levels was real, but a
+*persistent multi-level edge-program abstraction* would still be
+overcomplicated. The flat explains the part as an ordinary wall profile, two
+local cutbacks, two rounded end corners, and a partial flange attachment.
+Existing `EdgeProfile`, `CornerProfile`, and partial-flange concepts should be
+extended/exposed for those ordinary operations before inventing a general edge
+program. The current Sheet Metal semantic-layout adapter cannot express the
+asymmetric one-chamfer cutbacks or a circular `CornerProfile`, so the canonical
+native source is not patched with a misleading symmetric approximation.
+
+## Flat comparison and reconstruction status
+
+Against `docs/modules/sheetmetal/artifacts/m8/ctc03-final.firmament`, direct
+comparison reports:
+
+| metric | recovered source ↔ current native |
+|---|---:|
+| width residual | 0.002447 mm |
+| height residual | 0.007820 mm |
+| source→native RMS / p95 / max | 4.069438 / 7.836135 / 16.027648 mm |
+| native→source RMS / p95 / max | 12.500820 / 17.316571 / 156.843630 mm |
+| cuts | 17 ↔ 17 |
+| bend lines | 7 ↔ 7 |
+| status | NeedsReview |
+
+Because the one-loop material stitch remains partial, these residuals sample
+the retained region boundary set and are diagnostic, not final tooling-parity
+numbers. Profile-M3's historical stitched-native contour was 2.191367 mm RMS,
+4.7752 mm p95/max against the old recovered polygon reference. The two reports
+measure different source authorities and must not be presented as a strict
+before/after improvement.
+
+No native refold claim is made in M1: flat parity has not been achieved, so the
+workflow correctly stops before attributing remaining formed residuals to bend
+direction or reference-surface convention. Existing formed Profile-M3 values
+remain 8.500190/12.478269/52.816066 mm source→native and
+3.607855/8.940881/12.735724 mm native→source.
+
+## Generic fixture, performance, and determinism
+
+`NonCtcUChannel_StepOnlyRoundTripRecognizesAndUnfoldsWithoutNativeConstructionAuthority`
+exports the normal `simple-u-channel.firmament` formed body to AP242, discards
+native construction authority, reimports the dumb STEP BRep, recognizes its
+two bends, validates an explicit plan, and source-unfolds exact planar loops.
+This proves the mechanism is not keyed to CTC IDs.
+
+The generic imported U-channel produces a validated 12-segment outer contour,
+two exact circular inner loops, two bend lines, `Valid` status, and hash
+`f540958c2d8b4929aa4c88fc3c6500c759297a4dddebac2d5b11d3383250a2ee`.
+Two CTC runs produce recovered reference hash
+`9ca0a211b6ec2868fbf3bfdfccd1382dfc80d364554e062f214c46547d51bbde`.
+One observed run measured graph validation 2.7 ms, unfold 23.5 ms, and contour
+stitch 21.8 ms, excluding STEP import/recognition.
+
+## CLI workflow
+
+```text
+aetheris sheetmetal recognize part.step --plan recognition-plan.json --json
+aetheris sheetmetal recover-flat part.step --recognition-plan recognition-plan.json --out-dir recovered --json
+aetheris sheetmetal compare-flat recovered/recovered-flat.json native.firmament --json
+```
+
+`recovered-flat.json` stores the absolute source path and recognition plan so
+comparison reimports and revalidates source geometry rather than trusting a
+stale forensic dump.
+
+## LLM friction and architecture verdict
+
+Source flattening materially improves reverse engineering even in its partial
+state. Rounded wall ends, the two diagonal cutbacks, their exact spans, and the
+service attachment's three X levels are immediately visible as 2D analytic
+curves. Those relationships were difficult to distinguish from occlusion and
+thickness caps in formed views.
+
+Aetheris can now recognize a set of Sheet Metal bends on an imported dumb STEP
+and flatten the imported geometry directly without first reconstructing the
+part in native Firmament. It can use that reference for flat-first comparison,
+reuse recognized bend values, and later refold native construction. CTC proves
+that this target is substantially better for an engineer/LLM, while also
+showing why status must remain `Partial` today.
+
+The single largest blocker to a robust FeatureWorks-like workflow is exact,
+topology-guided global blank stitching at legitimate point-tangent/corner
+junctions. The current bounded arrangement correctly rejects three such CTC
+junctions instead of hulling or silently choosing angular order. Resolving
+those from the recognized region graph—while preserving line/arc ancestry—is
+the next blocker; arbitrary vendor naming or a new Profile language is not.
+
+Code quality is an acceptable localized prototype: model/authority separation
+and diagnostics are clean; source-loop extraction and CLI artifact projection
+are intentionally compact and need consolidation after the topology contract
+converges.
diff --git a/docs/modules/sheetmetal/artifacts/recovery-m2/README.md b/docs/modules/sheetmetal/artifacts/recovery-m2/README.md
new file mode 100644
index 00000000..404f3941
--- /dev/null
+++ b/docs/modules/sheetmetal/artifacts/recovery-m2/README.md
@@ -0,0 +1,173 @@
+# Sheet Metal Recovery M2 — topology-guided source-flat stitching
+
+## Verdict
+
+M2 is **meaningful progression**. CTC-03 now produces a valid, single analytic
+source blank with all 17 openings and seven bend lines. Native CTC remains
+`NeedsReview`: an attempted ordinary edge-fragment reconstruction proved that
+the current authored adapter conflates the right-wall free-edge carrier with
+the partial child-flange attachment edge. Those source edges are offset by
+2.6416 mm, and the R12.7 end transitions consume both adjacent edges. Keeping
+the approximation disconnected the native blank, so it was removed.
+
+## Recovery firewall and data flow
+
+```text
+strict imported line/arc regions
+ -> strict material classification and analytic splitting
+ -> recovery-only retained-fragment graph
+ -> strict-key nodes (1e-5 mm import bucket)
+ -> same-source complementary dangling repair (0.02 mm maximum policy)
+ -> bounded micro-closure removal / pairing candidates
+ -> one connected, non-self-intersecting PlanarContour2
+```
+
+`RecoveryContourStitcher` is called only when the strict
+`ProfileArrangementBuilder` rejects a recovered-source composition. Native
+Firmament compilation, authored Profiles, and `PlanarContourKernel` tolerances
+are unchanged. The recovered contour is validated by the strict kernel after
+repair.
+
+## CTC junction diagnosis
+
+All three failures were analytic split remnants at a point tangency, not
+missing engineering spans. The old arrangement saw each remnant as an extra
+incoming and outgoing edge and rejected 2-in/2-out angular order.
+
+| junction | source segments | recovered point (mm) | remnant length (mm) | relation and new action |
+|---|---|---:|---:|---|
+| J0 | `region-p-0088-0089.source-e0049`, `e0052` | (177.800000001, -97.237930176) | 0.000003020708 | line/arc point tangent; collapse the one-fragment micro-closure and continue |
+| J1 | `region-p-0088-0089.source-e0052`, `e0055` | (63.499998007, -97.237930176) | 0.000001992971 | complementary line/arc point tangent; same bounded repair |
+| J2 | `region-p-0109-0111.source-e0326`, `e0334` | (348.831502633, 130.962397483) | 0.000002517547 | R12.7 arc/line point tangent; same bounded repair |
+
+The corresponding micro-loop areas are 0.000146864, 0.000096896, and
+0.000439100 mm². Each repair is `PointTangentContinuation`, confidence
+`Strong`, and retains the original endpoint list, tangent evidence, source
+segment IDs, region IDs, canonical point, and displacement.
+
+Implemented taxonomy is `ExactEndpointMatch`,
+`WithinToleranceEndpointMatch`, `PointTangentContinuation`,
+`TangentContinuation`, `AngularContinuation`, `Ambiguous`, and `Rejected`.
+Geometric relation is recorded separately from the repair action.
+
+## Tolerance and acceptance policy
+
+- Exact analytic/native contour validation: 1e-7 mm (unchanged).
+- Imported topology vertex bucket: 1e-5 mm, matching strict arrangement graph
+ identity and signed-zero normalization.
+- Recovery junction tolerance: 0.02 mm.
+- Absolute recovery repair ceiling: 0.05 mm.
+
+The wider tolerance can only combine complementary dangling endpoints from the
+same source profile. Already balanced nodes are never proximity-merged, and
+cross-region proximity alone is never authority. Acceptance requires one
+all-fragment closed traversal followed by strict winding, endpoint, and
+self-intersection validation. Missing spans or displacement over the ceiling
+remain failures.
+
+`JudgmentEngine` is **partially applicable**. Deterministic micro-closure and
+single-candidate reductions do not need scoring. When a remaining recovery
+node has two legal incoming/outgoing pairings, the stitcher enumerates only
+that bounded topology choice (maximum 256 global combinations), applies hard
+single-blank/all-fragment constraints, then scores source-profile continuity,
+source-operation continuity, and tangent preservation. It does not enumerate
+arbitrary contour topology.
+
+## Accepted CTC source flat
+
+| property | result |
+|---|---:|
+| status | `Valid` / `RecoveredWithRepairs` |
+| outer loops / segments | 1 / 81 |
+| inner loops | 17 (15 circles, 2 slots) |
+| bend lines | 7 |
+| logical repaired junctions / unresolved | 3 / 0 |
+| bounds | 404.754237721 × 625.305580354 mm |
+| deterministic hash | `63d207b9c54fe569c38c63bd2a65d5024929b31b115f5926007fd3f7797eb541` |
+
+Artifacts are generated under `artifacts/sheetmetal-recovery-m2/ctc03`:
+`recovered-flat.json`, `recovered-flat.svg`, `recognition-plan.json`,
+`recover-report.json`, `compare-flat.json`, and `compare-formed.json`.
+
+One observed run measured 2.97 ms endpoint clustering, 1.95 ms bounded
+selection, 10.48 ms strict contour validation, and 50.03 ms total stitching.
+Timings are observational and excluded from the hash.
+
+## Right-wall proof and native blocker
+
+The accepted source planar region proves this ordered profile:
+
+1. R12.7 end transition;
+2. 25.89022 mm baseline run;
+3. 15.24 × 15.24 diagonal into a 15.24 mm recess;
+4. 63.5 mm recessed run;
+5. vertical return to the shallow service attachment level;
+6. 127 mm service span, offset 2.6416 mm from the outer baseline;
+7. mirrored 63.5 mm recess and 15.24 mm diagonal;
+8. 29.69514 mm baseline run and the second R12.7 end transition.
+
+No persistent edge-state machine is justified. The clean native abstraction is
+an ordinary analytic right-wall profile plus a separately addressable inset
+attachment path for the partial flange. The present authored lowering exposes
+only `RightWall.Outer` for both roles and its region-boundary adapter is
+line-only. A trial compound-recess fragment made the service flange an island;
+it was reverted rather than hiding the contradiction with fuzzy union.
+
+Consequently native source remains source-independent and unchanged. There are
+no STEP paths, recovered topology IDs, or inline recovered polygons in
+`ctc03-final.firmament`.
+
+## Comparison evidence
+
+The new accepted global contour changes the comparison authority. It should not
+be presented as a like-for-like improvement to M1's per-region fallback.
+
+| direct flat metric | M1 partial-region reference | M2 valid global reference |
+|---|---:|---:|
+| source -> native RMS / p95 / max (mm) | 4.069438 / 7.836135 / 16.027648 | 4.413550 / 9.554765 / 17.448908 |
+| native -> source RMS / p95 / max (mm) | 12.500820 / 17.316571 / 156.843630 | 3.769455 / 8.898990 / 14.341517 |
+| width / height residual (mm) | 0.002447 / 0.007820 | 0.002447 / 0.007820 |
+| cuts / bend-line delta | 0 / 0 | 0 / 0 |
+
+The major reverse-direction outlier disappears because M2 compares one real
+outer boundary rather than a union of all region boundaries. Source-to-native
+does not yet improve; the native right-wall profile remains the blocker.
+
+No refold update is claimed. With native source unchanged, formed parity remains
+8.500190 / 12.478269 / 52.816066 mm source-to-native RMS/p95/max and
+3.607855 / 8.940881 / 12.735724 mm native-to-source. All 17 opening comparisons
+and seven bends remain preserved.
+
+## Generic robustness
+
+`RecoveredContourStitchingM2Tests` includes:
+
+- a same-source square with a 1e-6 mm endpoint gap, recovered by one explicit
+ `WithinToleranceEndpointMatch` without global merging;
+- two same-center/radius complementary semicircles, retained as distinct
+ analytic domains rather than tessellated or deduplicated;
+- an exported dumb U-channel STEP with signed-zero numeric spelling, reimported,
+ recognized, and recovered without access to native construction authority.
+
+## Workflow and remaining friction
+
+```text
+aetheris sheetmetal recognize part.step --out plan.json
+aetheris sheetmetal recover-flat part.step --plan plan.json --out-dir recovered
+# inspect recovered-flat.svg and compact repair evidence
+aetheris sheetmetal compare-flat recovered/recovered-flat.json native.firmament
+# only after flat parity: refold and compare formed geometry
+```
+
+The flat is now trustworthy enough to read the right wall as ordinary 2D
+engineering geometry rather than infer it from formed faces. The unavoidable
+friction is no longer recovery: it is a missing strict authored distinction
+between a free-edge profile carrier and an inset child-flange attachment path,
+plus analytic round-corner propagation through the formed-region adapter.
+
+The recovery implementation is an acceptable bounded prototype: isolated,
+deterministic, diagnostic-rich, and intentionally not generalized into a
+Boolean engine. The largest remaining blocker for arbitrary vendor Sheet Metal
+STEP is reliable recognition/topology evidence when the source has genuinely
+missing edges, non-developable patches, or multi-blank material—not micron-scale
+endpoint noise.