Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add syntax-based piping frontend and source-mapped diagnostics
Yuechen Lid20df8ed268f
diff --git a/Aetheris.CLI.Tests/PipingAdmissionCliTests.cs b/Aetheris.CLI.Tests/PipingAdmissionCliTests.csnew file mode 100644index 00000000..5c6b36a9--- /dev/null+++ b/Aetheris.CLI.Tests/PipingAdmissionCliTests.cs@@ -0,0 +1,73 @@+using System.Text.Json;++namespace Aetheris.CLI.Tests;++public sealed class PipingAdmissionCliTests+{+ [Fact]+ public void LowercaseConnectionStyleIsBoundAndGeometryMatchesCanonical()+ {+ var path = Path.Combine(Root(), "fixtures/Regression/FrontendX2/piping-field-casing.firmament");+ var stdout = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["inspect", path, "--json"], stdout, new StringWriter()));+ using var json = JsonDocument.Parse(stdout.ToString());+ var piping = json.RootElement.GetProperty("piping");+ Assert.All(piping.GetProperty("ports").EnumerateArray(), port => Assert.Equal("Weld", port.GetProperty("connectionType").GetString()));+ stdout = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["validate", path, "--json"], stdout, new StringWriter()));+ using var validation = JsonDocument.Parse(stdout.ToString());+ var report = validation.RootElement.GetProperty("firmamentV2Validation");+ Assert.Equal("Built", report.GetProperty("validationLevel").GetString());+ Assert.Equal("UnifiedPiping", report.GetProperty("parserRoute").GetString());+ var source = File.ReadAllText(path);+ var nominal = File.ReadAllText(Path.Combine(Root(), "fixtures/Canonical/Piping/pipe-segment.firmament"));+ Assert.Equal(Kernel.Firmament.FirmamentBuildAndExport.CompileSource(nominal).Value.StepText,+ Kernel.Firmament.FirmamentBuildAndExport.CompileSource(source).Value.StepText);+ }++ [Theory]+ [InlineData("", "firmament-v2-canonical-field-unknown", 6)]+ [InlineData("schema WireForm\n", "firmament-schema-mismatch", 1)]+ public void ValidateInspectAndBuildAgreeAndPreserveStructuredLocations(string prefix, string code, int line)+ {+ var directory = Path.Combine(Root(), "artifacts/local/tests/piping-admission", Guid.NewGuid().ToString("N"));+ Directory.CreateDirectory(directory);+ var source = Path.Combine(directory, "invalid.firmament"); var output = Path.Combine(directory, "invalid.step");+ File.WriteAllText(source, prefix + File.ReadAllText(Path.Combine(Root(), "fixtures/Invalid/Piping/unknown-port-field.firmament")));+ try+ {+ foreach (var operation in new[] { "validate", "inspect", "build" })+ {+ var stdout = new StringWriter(); var stderr = new StringWriter();+ var args = operation == "build" ? new[] { operation, source, "--out", output, "--json" } : [operation, source, "--json"];+ Assert.NotEqual(0, CliRunner.Run(args, stdout, stderr));+ using var json = JsonDocument.Parse(stdout.ToString());+ var result = operation == "validate" ? json.RootElement.GetProperty("firmamentV2Validation") : json.RootElement;+ var diagnostic = Assert.Single(result.GetProperty("diagnostics").EnumerateArray(), d => d.GetProperty("code").GetString()!.Split(':')[0] == code);+ Assert.Equal(line, diagnostic.GetProperty("line").GetInt32());+ Assert.Equal(Path.GetFullPath(source), Path.GetFullPath(diagnostic.GetProperty("sourceFile").GetString()!));+ Assert.NotEmpty(diagnostic.GetProperty("message").GetString()!);+ if (prefix.Length == 0)+ {+ var authored = File.ReadAllText(source);+ var start = authored.IndexOf("unexpectedIntent:", StringComparison.Ordinal);+ Assert.Equal(start, diagnostic.GetProperty("sourceSpan").GetProperty("start").GetInt32());+ Assert.Equal(start - authored.LastIndexOf('\n', start), diagnostic.GetProperty("column").GetInt32());+ }+ Assert.False(File.Exists(output));+ }+ var textError = new StringWriter();+ Assert.NotEqual(0, CliRunner.Run(["validate", source], new StringWriter(), textError));+ Assert.Contains(code, textError.ToString());+ Assert.Contains(prefix.Length == 0 ? $":{line}:" : $"({line},", textError.ToString());+ }+ finally { File.Delete(source); Directory.Delete(directory); }+ }++ private static string Root()+ {+ var d = new DirectoryInfo(AppContext.BaseDirectory);+ while (d is not null && !File.Exists(Path.Combine(d.FullName, "Aetheris.slnx"))) d = d.Parent;+ return d?.FullName ?? throw new DirectoryNotFoundException();+ }+}diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex 4241c0fe..b99d1f30 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -1452,9 +1452,7 @@ Model CanonicalPanel {var frontend = FirmamentFrontendSchemas.Select(source);if (!frontend.IsSuccess){- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "inspect", success = false, input = fullPath, diagnostics = frontend.Diagnostics }, JsonOptions));- else foreach (var diagnostic in frontend.Diagnostics) stderr.WriteLine("error: " + diagnostic);- return 1;+ return WriteFrontendRejection(frontend, source, fullPath, "inspect", json, stdout, stderr);}source = frontend.Source;if (SheetMetalFirmament.LooksLikeSheetMetal(source))@@ -1488,9 +1486,9 @@ Model CanonicalPanel {if (PipingAuthoring.IsPipingSource(source)){var piping = PipingAuthoring.Compile(source, fullPath);- if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "inspect", success = piping.IsSuccess, input = fullPath, domain = "Piping", piping = piping.Report, diagnostics = piping.Diagnostics }, JsonOptions));+ if (json) stdout.WriteLine(JsonSerializer.Serialize(new { command = "inspect", success = piping.IsSuccess, input = fullPath, domain = "Piping", piping = piping.Report, diagnostics = piping.KernelDiagnostics().Select(d => FirmamentBuildAdmissionValidation.Present(d, fullPath, source)).ToArray() }, JsonOptions));else if (piping.IsSuccess && piping.Report is { } pipingReport) stdout.WriteLine($"Piping system {pipingReport.PipingSystem}: {pipingReport.Connections.Count} connections, {pipingReport.Routes.Count} routes, {pipingReport.PipeSegments.Count} pipe segments, {pipingReport.Fittings.Count} fittings, {pipingReport.Nozzles.Count} equipment nozzles, {pipingReport.Mates.Count} endpoint mates");- else foreach (var diagnostic in piping.Diagnostics) stderr.WriteLine($"error: {diagnostic}");+ else foreach (var diagnostic in piping.KernelDiagnostics().Select(d => FirmamentBuildAdmissionValidation.Present(d, fullPath, source))) stderr.WriteLine($"{diagnostic.SourceFile}:{diagnostic.Line}:{diagnostic.Column}: {diagnostic.Severity} {diagnostic.Code}: {diagnostic.Message}");return piping.IsSuccess ? 0 : 1;}if (StructuralAuthoring.IsStructuralSource(source))@@ -2437,9 +2435,13 @@ Model CanonicalPanel {if (PipingAuthoring.IsPipingSource(validationSource)){var piping = PipingAuthoring.Compile(validationSource, Path.GetFullPath(sourcePath));- var payload = new { source = sourcePath, status = piping.IsSuccess ? "valid" : "invalid", domain = "Piping", summary = new { fatalDiagnosticCount = piping.Diagnostics.Count, warningDiagnosticCount = 0, connections = piping.Report?.Connections.Count ?? 0, routes = piping.Report?.Routes.Count ?? 0 }, diagnostics = piping.Diagnostics };+ var payload = new { source = sourcePath, status = piping.IsSuccess ? "valid" : "invalid", domain = "Piping", validationLevel = piping.IsSuccess ? "Built" : "BuildRejected", parserRoute = "UnifiedPiping", summary = new { fatalDiagnosticCount = piping.Diagnostics.Count, warningDiagnosticCount = 0, connections = piping.Report?.Connections.Count ?? 0, routes = piping.Report?.Routes.Count ?? 0 }, diagnostics = piping.KernelDiagnostics().Select(d => FirmamentBuildAdmissionValidation.Present(d, Path.GetFullPath(sourcePath), validationSource)).ToArray() };if (json) stdout.WriteLine(JsonSerializer.Serialize(new { firmamentV2Validation = payload }, JsonOptions));- else stdout.WriteLine($"Firmament V2 Piping validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");+ else+ {+ stdout.WriteLine($"Firmament V2 Piping validation: {payload.status} ({payload.summary.fatalDiagnosticCount} fatal, 0 warning)");+ foreach (var d in payload.diagnostics) stderr.WriteLine($"{d.SourceFile}:{d.Line}:{d.Column}: {d.Severity} {d.Code}: {d.Message}");+ }return piping.IsSuccess ? 0 : 1;}if (StructuralAuthoring.IsStructuralSource(validationSource))diff --git a/Aetheris.Kernel.Core/Diagnostics/KernelDiagnostic.cs b/Aetheris.Kernel.Core/Diagnostics/KernelDiagnostic.csindex 3e23feb7..40a26d62 100644--- a/Aetheris.Kernel.Core/Diagnostics/KernelDiagnostic.cs+++ b/Aetheris.Kernel.Core/Diagnostics/KernelDiagnostic.cs@@ -9,6 +9,12 @@ public sealed record KernelDiagnostic(/// <summary>Offsets in the producing stage's source. Presentation must map/// expanded source to the authored document before displaying a location.</summary>public KernelDiagnosticSourceSpan? SourceSpan { get; init; }+ /// <summary>An already mapped span in the authored input. Unlike SourceSpan,+ /// presentation must not remap this through a different frontend's expansion.</summary>+ public KernelDiagnosticSourceSpan? OriginalSourceSpan { get; init; }}-public sealed record KernelDiagnosticSourceSpan(int Start, int Length);+public sealed record KernelDiagnosticSourceSpan(int Start, int Length)+{+ public string? LocationNote { get; init; }+}diff --git a/Aetheris.Kernel.Firmament.Tests/PipingAstAdmissionTests.cs b/Aetheris.Kernel.Firmament.Tests/PipingAstAdmissionTests.csnew file mode 100644index 00000000..a5ae4700--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/PipingAstAdmissionTests.cs@@ -0,0 +1,161 @@+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;+using Aetheris.Kernel.Firmament.Piping;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class PipingAstAdmissionTests+{+ [Theory]+ [InlineData("pipe-segment")]+ [InlineData("elbow90")]+ [InlineData("explicit-route")]+ [InlineData("route-around-keepout")]+ [InlineData("autorouted-connection")]+ [InlineData("local-reroute")]+ [InlineData("pump-skid")]+ [InlineData("tee")]+ public void PreferredAndCompatibilityFieldsPreserveExactGeometryAndSemantics(string name)+ {+ var legacy = File.ReadAllText(Path.Combine(Root(), "fixtures/Compatibility/FirmamentV2/Piping", name + ".firmament"));+ var modern = File.ReadAllText(Path.Combine(Root(), "fixtures/Canonical/Piping", name + ".firmament"));+ var a = PipingAuthoring.Compile(legacy); var b = PipingAuthoring.Compile(modern);+ Assert.True(a.IsSuccess, string.Join('\n', a.Diagnostics));+ Assert.True(b.IsSuccess, string.Join('\n', b.Diagnostics));+ Assert.Equal(a.StepText, b.StepText);+ Assert.Equal(a.Report!.Ports, b.Report!.Ports);+ Assert.Equal(a.Report.Equipment, b.Report.Equipment);+ Assert.Equal(a.Report.Assembly.Definitions, b.Report.Assembly.Definitions);+ Assert.Equal(PipingAuthoring.RoutingJson(a.Report), PipingAuthoring.RoutingJson(b.Report));+ Assert.Equal(PipingAuthoring.BomJson(a.Report), PipingAuthoring.BomJson(b.Report));+ Assert.Equal(PipingAuthoring.CutListJson(a.Report), PipingAuthoring.CutListJson(b.Report));+ Assert.Equal(a.Report.Bounds, b.Report.Bounds);+ Assert.Equal(modern, FirmamentSourceSpelling.Prefer(modern));+ Assert.Equal(modern.ReplaceLineEndings("\n"), FirmamentSourceSpelling.Prefer(legacy).ReplaceLineEndings("\n"));+ }++ [Theory]+ [InlineData("PipePolicy", "pipe-segment")]+ [InlineData("Port", "pipe-segment")]+ [InlineData("Connection", "pipe-segment")]+ [InlineData("Route", "pipe-segment")]+ [InlineData("PipingSystem", "pipe-segment")]+ [InlineData("Model", "pipe-segment")]+ [InlineData("Equipment", "pump-skid")]+ [InlineData("KeepOut", "pump-skid")]+ [InlineData("RouteSpace", "pump-skid")]+ [InlineData("RouteRequest", "pump-skid")]+ [InlineData("LocalReroute", "local-reroute")]+ public void EveryOwnedScopeRejectsUnknownFieldsAtTheirActualLocation(string owner, string file)+ {+ var source = File.ReadAllText(Path.Combine(Root(), "fixtures/Canonical/Piping", file + ".firmament"));+ var node = FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document).First(d => d.Type.Name.Text == owner);+ var insertion = node.Body!.ContentSpan.Start;+ var invalid = source.Insert(insertion, "\n unexpectedIntent: Weld;\n");+ var result = PipingAuthoring.Compile(invalid);+ Assert.False(result.IsSuccess); Assert.Null(result.StepText); Assert.Null(result.Report);+ var diagnostic = Assert.Single(result.FrontendDiagnostics, d => d.Code == FirmamentV2Parser.CanonicalFieldUnknown);+ Assert.Equal(invalid.IndexOf("unexpectedIntent", StringComparison.Ordinal), diagnostic.SourceSpan!.Start);+ Assert.Contains("unexpectedIntent", diagnostic.Message);+ }++ [Theory]+ [InlineData("provenance: Explicit", "provenance: Explcit")]+ [InlineData("connectionType: Weld", "connectionType: weld")]+ [InlineData("connectionType: Weld", "connectionType: 2")]+ [InlineData("connectionType: Weld", "connectionType: Weld; ConnectionType: Flange")]+ [InlineData("connectionType: Weld", "connectionType: Weld; nozzleLength: nope")]+ [InlineData("connectionType: Weld", "connectionType: Weld; nozzleLength: -1mm")]+ [InlineData("service: \"CoolingWater\"", "service: \"CoolingWater\"; reducer: yes")]+ [InlineData("bendRadius: 50mm", "bendRadius: 0mm")]+ [InlineData("bendRadius: 50mm", "bendRadius: 50mm; lockedSegments: [0, bad]")]+ [InlineData("bendRadius: 50mm", "bendRadius: 50mm; lockedSegments: [99]")]+ [InlineData("direction: [1,0,0]", "direction: [1mm,0mm,0mm]")]+ [InlineData("outerDiameter: 25mm", "outerDiameter: 25deg")]+ [InlineData("Port Inlet {", "Port Inlet on XZ {")]+ [InlineData("Port Inlet {", "Port Inlet { Fillet corners { radius: 2mm; }")]+ [InlineData("PipingSystem SegmentWitness {", "PipingSystem SegmentWitness { Fillet corners { radius: 2mm; }")]+ public void AuthoredOptionalIntentCannotBeDefaultedOrOmitted(string before, string after)+ {+ var source = Segment(); Assert.Contains(before, source);+ var result = PipingAuthoring.Compile(source.Replace(before, after, StringComparison.Ordinal));+ Assert.False(result.IsSuccess); Assert.Null(result.StepText); Assert.NotEmpty(result.Diagnostics);+ }++ [Fact]+ public void DuplicateNamesAndMisnestedPortsRejectWithoutOwnerExceptions()+ {+ var source = Segment();+ var duplicate = PipingAuthoring.Compile(source.Replace("Port Outlet", "Port Inlet", StringComparison.Ordinal));+ Assert.False(duplicate.IsSuccess); Assert.Null(duplicate.StepText);+ var nested = PipingAuthoring.Compile(source.Replace("Port Inlet {", "Port Inlet { Port Extra { position: [1mm,2mm,3mm]; }", StringComparison.Ordinal));+ Assert.False(nested.IsSuccess); Assert.Null(nested.StepText);+ }++ [Fact]+ public void CommentsAndStringsCannotSelectPipingFrontend()+ {+ Assert.False(PipingAuthoring.IsPipingSource("// PipingSystem Imaginary { }\nModel Plate { units: mm }"));+ Assert.False(PipingAuthoring.IsPipingSource("Record Info { text: String } Static info: Info { text: \"PipingSystem Imaginary { }\"; }"));+ }++ [Fact]+ public void HistoricalOmittedUnitsAndBareLengthsPreserveGeometry()+ {+ var source = Segment();+ var legacy = source.Replace("units: mm", "", StringComparison.Ordinal).Replace("mm", "", StringComparison.Ordinal);+ var baseline = PipingAuthoring.Compile(source); var admitted = PipingAuthoring.Compile(legacy);+ Assert.True(admitted.IsSuccess, string.Join('\n', admitted.Diagnostics));+ Assert.Equal(baseline.StepText, admitted.StepText);+ var wrongUnit = PipingAuthoring.Compile(source.Replace("units: mm", "units: m", StringComparison.Ordinal));+ Assert.False(wrongUnit.IsSuccess); Assert.Null(wrongUnit.StepText);+ }++ [Fact]+ public void ProposalOnlyCompilationRejectsWithoutEmptyGeometryExceptions()+ {+ var source = Segment();+ var route = FirmamentSyntaxTraversal.Declarations(FirmamentSyntaxParser.Parse(source).Document).Single(d => d.Type.Name.Text == "Route");+ source = source.Remove(route.Span.Start, route.Span.Length).Insert(route.Span.Start, "RouteRequest Candidate { connection: Run; }");+ var result = PipingAuthoring.Compile(source);+ Assert.False(result.IsSuccess); Assert.Null(result.StepText);+ Assert.Contains(result.Diagnostics, d => d.StartsWith("piping-route-required", StringComparison.Ordinal));+ }++ [Theory]+ [InlineData("Standard.NoSuchModule", "Tee")]+ [InlineData("Standard.Piping", "NoSuchProduct")]+ public void CatalogueBindingsRequireAUsedResolvedExport(string module, string product)+ {+ var source = $"Use {module}\nLet Product = {module}.{product}\n" + Segment();+ var result = PipingAuthoring.Compile(source);+ Assert.False(result.IsSuccess); Assert.Null(result.StepText);+ Assert.Contains(result.FrontendDiagnostics, d => d.SourceSpan is not null && d.Message.Contains(module, StringComparison.Ordinal));+ }++ [Fact]+ public void SharedRecordBindingConsumesDimensionsAndRejectsSchemaBypass()+ {+ const string data = """+ Record PipeStock { od: Length; wall: Length; }+ Static stock: PipeStock { od: 25mm; wall: 2mm; }++ """;+ var source = data + Segment().Replace("outerDiameter: 25mm", "outerDiameter: stock.od", StringComparison.Ordinal)+ .Replace("wallThickness: 2mm", "wallThickness: stock.wall", StringComparison.Ordinal);+ var bound = PipingAuthoring.Compile(source);+ Assert.True(bound.IsSuccess, string.Join('\n', bound.Diagnostics));+ Assert.Equal(PipingAuthoring.Compile(Segment()).StepText, bound.StepText);+ var invalid = PipingAuthoring.Compile(source.Replace("wall: 2mm", "wall: 2mm; unexpectedIntent: 3mm", StringComparison.Ordinal));+ Assert.False(invalid.IsSuccess); Assert.Null(invalid.StepText);+ Assert.NotEmpty(invalid.FrontendDiagnostics);+ }++ private static string Segment() => File.ReadAllText(Path.Combine(Root(), "fixtures/Canonical/Piping/pipe-segment.firmament"));+ private static string Root()+ {+ var d = new DirectoryInfo(AppContext.BaseDirectory);+ while (d is not null && !File.Exists(Path.Combine(d.FullName, "Aetheris.slnx"))) d = d.Parent;+ return d?.FullName ?? throw new DirectoryNotFoundException();+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 75d27036..ca4f6d9b 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -41,7 +41,7 @@ public static class FirmamentBuildAndExportArgumentException.ThrowIfNullOrWhiteSpace(sourcePath);var fullSourcePath = Path.GetFullPath(sourcePath);- var sourceText = NormalizeLf(File.ReadAllText(fullSourcePath, Encoding.UTF8));+ var sourceText = File.ReadAllText(fullSourcePath, Encoding.UTF8);var frontend = FirmamentFrontendSchemas.Select(sourceText);if (!frontend.IsSuccess) return KernelResult<FirmamentBuildAndExportResult>.Failure(frontend.LocatedDiagnostics.Select(d => SchemaDiagnostic(d.Code + ": " + d.Message)).ToArray());sourceText = frontend.Source;@@ -49,8 +49,7 @@ public static class FirmamentBuildAndExport{var piping = PipingAuthoring.Compile(sourceText, fullSourcePath);if (!piping.IsSuccess || piping.StepText is null || piping.Report is null)- return KernelResult<FirmamentBuildAndExportResult>.Failure(piping.Diagnostics.Select(message => new Kernel.Core.Diagnostics.KernelDiagnostic(- Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "Piping.X3")).ToArray());+ return KernelResult<FirmamentBuildAndExportResult>.Failure(piping.KernelDiagnostics());var pipingOutputPath = string.IsNullOrWhiteSpace(outputPath) ? ResolveDefaultOutputPath(fullSourcePath) : Path.GetFullPath(outputPath);Directory.CreateDirectory(Path.GetDirectoryName(pipingOutputPath)!);File.WriteAllText(pipingOutputPath, piping.StepText, new UTF8Encoding(false));@@ -63,6 +62,7 @@ public static class FirmamentBuildAndExportreturn KernelResult<FirmamentBuildAndExportResult>.Success(new(fullSourcePath, pipingOutputPath,new(piping.StepText, "piping-system:" + report.PipingSystem, -1, "Assembly", "PipingSystem", Piping: report)));}+ sourceText = NormalizeLf(sourceText);if (StructuralAuthoring.IsStructuralSource(sourceText)){var structural = StructuralAuthoring.Compile(sourceText, fullSourcePath);@@ -125,7 +125,7 @@ public static class FirmamentBuildAndExportstring? sourceDirectory = null){ArgumentNullException.ThrowIfNull(sourceText);- var normalized = NormalizeLf(sourceText);+ var normalized = sourceText;var frontend = FirmamentFrontendSchemas.Select(normalized);if (!frontend.IsSuccess) return KernelResult<FirmamentStepExportResult>.Failure(frontend.LocatedDiagnostics.Select(d => SchemaDiagnostic(d.Code + ": " + d.Message)).ToArray());normalized = frontend.Source;@@ -134,9 +134,9 @@ public static class FirmamentBuildAndExportvar piping = PipingAuthoring.Compile(normalized, sourceDirectory ?? "memory");return piping.IsSuccess && piping.StepText is not null && piping.Report is not null? KernelResult<FirmamentStepExportResult>.Success(new(piping.StepText, "piping-system:" + piping.Report.PipingSystem, -1, "Assembly", "PipingSystem", Piping: piping.Report))- : KernelResult<FirmamentStepExportResult>.Failure(piping.Diagnostics.Select(message => new Kernel.Core.Diagnostics.KernelDiagnostic(- Kernel.Core.Diagnostics.KernelDiagnosticCode.ValidationFailed, Kernel.Core.Diagnostics.KernelDiagnosticSeverity.Error, message, "Piping.X3")).ToArray());+ : KernelResult<FirmamentStepExportResult>.Failure(piping.KernelDiagnostics());}+ normalized = NormalizeLf(normalized);if (StructuralAuthoring.IsStructuralSource(normalized)){var structural = StructuralAuthoring.Compile(normalized, sourceDirectory ?? "memory");diff --git a/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs b/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.csindex 4e3498d5..f0e74a5e 100644--- a/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs+++ b/Aetheris.Kernel.Firmament/FirmamentFrontendSchema.cs@@ -6,7 +6,7 @@ namespace Aetheris.Kernel.Firmament;/// <summary>Program-level selection of an existing Firmament frontend. This is deliberately/// not a second parser or semantic IR: it only makes the current parser boundary explicit.</summary>-public enum FirmamentFrontendSchema { Mechanical, WireForm, Sweep, SectionChain, Garment }+public enum FirmamentFrontendSchema { Mechanical, WireForm, Sweep, SectionChain, Garment, Piping }public sealed record FirmamentFrontendSelection(FirmamentFrontendSchema? Schema, string Source, IReadOnlyList<string> Diagnostics){@@ -22,7 +22,7 @@ public sealed record FirmamentFrontendSelection(FirmamentFrontendSchema? Schema,public static class FirmamentFrontendSchemas{- public static readonly IReadOnlyList<string> Names = ["Mechanical", "WireForm", "Sweep", "SectionChain", "Garment"];+ public static readonly IReadOnlyList<string> Names = ["Mechanical", "WireForm", "Sweep", "SectionChain", "Garment", "Piping"];public static FirmamentFrontendSelection Select(string source){@@ -88,6 +88,7 @@ public static class FirmamentFrontendSchemas}private static FirmamentFrontendSchema? DetectDistinctFrontend(string source) =>+ Piping.PipingAuthoring.IsPipingSource(source) ? FirmamentFrontendSchema.Piping :Garment.GarmentAuthoring.HasRoot(source) ? FirmamentFrontendSchema.Garment :WireFormAuthoring.IsWireFormSource(source) ? FirmamentFrontendSchema.WireForm :CircularSweepAuthoring.IsSweepSource(source) ? FirmamentFrontendSchema.Sweep :diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.csindex 41680e5c..84fe673e 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs@@ -34,6 +34,10 @@ public static class FirmamentBuildAdmissionValidation? diagnostic.Message[..separator]: diagnostic.Message.All(character => char.IsLetterOrDigit(character) || character is '-' or '_' or '.')? diagnostic.Message : diagnostic.Code.ToString();+ if (diagnostic.OriginalSourceSpan is { } authored)+ return Locate(new(code, diagnostic.Severity switch+ { KernelDiagnosticSeverity.Error => "error", KernelDiagnosticSeverity.Warning => "warning", _ => "info" }, diagnostic.Message)+ { SourceSpan = new(authored.Start, authored.Length), LocationNote = authored.LocationNote, Source = diagnostic.Source, Stage = diagnostic.Source }, source, sourceFile);if (source is not null){var parsed = FirmamentV2Parser.Parse(source);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.csindex 9285b8d9..3dac6004 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSourceSpelling.cs@@ -48,6 +48,12 @@ public static class FirmamentSourceSpellingif (SemanticSymmetryAuthoring.FieldsFor(declaration).FirstOrDefault(name => FirmamentSyntaxFields.SameField(field.Name.Text, name)) is { } canonical)symmetryFields[field.Name.Span.Start] = canonical;}+ // Use the piping owner's vocabulary, scoped to its actual system children.+ foreach (var system in FirmamentV2Parser.MechanicalDeclarations(syntax.Statements).Where(d => d.Type.Name.Text == "PipingSystem"))+ foreach (var child in system.Body?.Statements.OfType<DeclarationSyntax>() ?? [])+ foreach (var field in child.Body?.Statements.OfType<FieldSyntax>() ?? [])+ if (Piping.PipingAuthoring.FieldsFor(child).FirstOrDefault(name => FirmamentSyntaxFields.SameField(field.Name.Text, name)) is { } canonical)+ symmetryFields[field.Name.Span.Start] = canonical;var aliasPositions = tokens.Any(t => t.Text is "As" or "as") ? FirmamentSyntaxTraversal.Expressions(FirmamentSyntaxParser.Parse(source).Document).OfType<AliasSyntax>()diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentStandardLibraryResolver.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentStandardLibraryResolver.csindex c8a6692e..a5bc7114 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentStandardLibraryResolver.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentStandardLibraryResolver.cs@@ -42,6 +42,11 @@ public static class FirmamentStandardLibraryResolvernew("Standard.Piping", "PumpSkid", "PumpSkidTemplate", "PumpSkidPolicy", "StandardPumpSkid"),];+ internal static bool IsModule(string module) => Exports.Any(e => e.Module == module);+ private static Export? FindExport(string module, string symbol) => Exports.FirstOrDefault(e => e.Module == module+ && (e.PublicName == symbol || e.RecordName == symbol || e.StaticName == symbol));+ internal static bool IsExport(string module, string symbol) => FindExport(module, symbol) is not null;+public static FirmamentLibraryResolution? Resolve(string source, out IReadOnlyList<string> diagnostics){ArgumentNullException.ThrowIfNull(source);@@ -75,8 +80,7 @@ public static class FirmamentStandardLibraryResolvererrors.Add($"{MissingUse}:{module}:{reference}");continue;}- var export = Exports.FirstOrDefault(item => item.Module == module- && (item.PublicName == symbol || item.RecordName == symbol || item.StaticName == symbol));+ var export = FindExport(module, symbol);if (export is null){errors.Add($"{UnknownDeclaration}:{reference}");diff --git a/Aetheris.Kernel.Firmament/Piping/PipingAuthoring.cs b/Aetheris.Kernel.Firmament/Piping/PipingAuthoring.csindex be1948ff..fd923098 100644--- a/Aetheris.Kernel.Firmament/Piping/PipingAuthoring.cs+++ b/Aetheris.Kernel.Firmament/Piping/PipingAuthoring.cs@@ -1,8 +1,8 @@-using System.Globalization;using System.Security.Cryptography;using System.Text;using System.Text.Json;-using System.Text.RegularExpressions;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;using Aetheris.Kernel.Core.Brep;using Aetheris.Kernel.Core.Brep.Verification;using Aetheris.Kernel.Core.Geometry;@@ -13,16 +13,20 @@ using Aetheris.Kernel.StandardLibrary.Materials;namespace Aetheris.Kernel.Firmament.Piping;/// <summary>Bounded X3 semantic piping front end for explicit and accepted orthogonal routes.</summary>-public static class PipingAuthoring+public static partial class PipingAuthoring{private const double Tol=1e-7;- public static bool IsPipingSource(string source)=>Regex.IsMatch(source,@"\bPipingSystem\s+[A-Za-z_]\w*\s*\{",RegexOptions.CultureInvariant);+ public static bool IsPipingSource(string source) => source.Contains("PipingSystem", StringComparison.Ordinal)+ && FirmamentV2Parser.MechanicalDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements)+ .Any(d => d.Type.Name.Text == "PipingSystem");public static PipingCompilationResult Compile(string source,string sourceIdentity="memory"){var diagnostics=new List<string>();var parseClock=System.Diagnostics.Stopwatch.StartNew();- var parsed=Parse(source,sourceIdentity,diagnostics);parseClock.Stop();- if(parsed is null||diagnostics.Count>0)return new(false,null,null,diagnostics);+ var located = new List<FirmamentV2ValidationDiagnostic>();+ var parsed=Parse(source,sourceIdentity,diagnostics,located);parseClock.Stop();+ if(parsed is null||diagnostics.Count>0)return new(false,null,null,diagnostics)+ { FrontendDiagnostics = located.Select(d => d with { SourceFile = sourceIdentity, IsOriginalSource = true }).ToArray() };ValidateNozzleContracts(parsed,diagnostics);if(diagnostics.Count>0)return new(false,null,null,diagnostics);var obstacleClock=System.Diagnostics.Stopwatch.StartNew();var obstacles=parsed.KeepOuts;obstacleClock.Stop();@@ -47,6 +51,7 @@ public static class PipingAuthoring}routeClock.Stop();ValidateRoutes(routes,parsed,diagnostics);+ if (routes.Count == 0) diagnostics.Add("piping-route-required: Declare an explicit Route or accept a RouteRequest with acceptAs before compiling engineering geometry.");if(diagnostics.Count>0)return new(false,null,null,diagnostics);var simplifyClock=System.Diagnostics.Stopwatch.StartNew();@@ -143,24 +148,6 @@ public static class PipingAuthoringprivate sealed record Parsed(string Name,IReadOnlyList<PipePolicyIr> Policies,IReadOnlyList<PipingEquipmentIr> Equipment,IReadOnlyList<PipingPortInterfaceIr> Ports,IReadOnlyList<PipingConnectionIr> Connections,IReadOnlyList<KeepOutIr> KeepOuts,IReadOnlyList<RouteIr> Routes,IReadOnlyList<AcceptedRequest> Requests,IReadOnlyList<RerouteSpec> Reroutes,double DefaultClearance);private sealed record AcceptedRequest(RouteRequestIr Request,string AcceptAs);private sealed record RerouteSpec(string Name,string Route,int FromAnchor,int ToAnchor,IReadOnlyList<string>Avoid,double Clearance);- private readonly record struct Block(string Name,string Body);-- private static Parsed? Parse(string source,string sourceIdentity,List<string>d)- {- var systems=Blocks(source,"PipingSystem");if(systems.Count!=1){d.Add("piping-system-cardinality: exactly one PipingSystem is required");return null;}var system=systems[0];- var defaultClear=Blocks(source,"RouteSpace").Select(x=>Length(Field(x.Body,"Clearance",false),25,d,"route-space:"+x.Name)).FirstOrDefault();if(defaultClear==0)defaultClear=25;- var policies=new List<PipePolicyIr>();foreach(var b in Blocks(source,"PipePolicy")){var od=Length(Field(b.Body,"OuterDiameter"),0,d,b.Name);var wall=Length(Field(b.Body,"WallThickness"),0,d,b.Name);var material=Field(b.Body,"Material").Trim('"');if(od<=0||wall<=0)d.Add($"piping-pipe-policy-positive:{b.Name}");if(2*wall>=od)d.Add($"piping-pipe-wall-too-thick:{b.Name}");var resolved=new MaterialResolver().Resolve(material);if(!resolved.IsSuccess)d.Add($"piping-material-unresolved:{b.Name}:{material}");policies.Add(new($"standard:piping:pipe:{Q(od)}:{Q(wall)}:{material}",b.Name,od,wall,material));}Duplicates(policies.Select(x=>x.Name),"pipe-policy",d);- var keepouts=new List<KeepOutIr>();foreach(var b in Blocks(source,"KeepOut")){var min=Point(Field(b.Body,"Min"),d,"keepout:"+b.Name);var max=Point(Field(b.Body,"Max"),d,"keepout:"+b.Name);if(max.X<=min.X||max.Y<=min.Y||max.Z<=min.Z)d.Add($"piping-keepout-invalid-bounds:{b.Name}");keepouts.Add(new($"concept:keepout:{b.Name}",b.Name,min,max,Field(b.Body,"Concept",false) is var c&&c.Length>0?c:"KeepOut"));}Duplicates(keepouts.Select(x=>x.Name),"keepout",d);- var equipment=new List<PipingEquipmentIr>();foreach(var b in Blocks(source,"Equipment")){var keepOut=Field(b.Body,"KeepOut");if(!keepouts.Any(x=>x.Name==keepOut))d.Add($"piping-equipment-unknown-keepout:{b.Name}:{keepOut}");equipment.Add(new($"equipment:{b.Name}",b.Name,keepOut));}Duplicates(equipment.Select(x=>x.Name),"equipment",d);- var ports=new List<PipingPortInterfaceIr>();foreach(var b in Blocks(source,"Port")){var policy=Field(b.Body,"PipePolicy");if(!policies.Any(x=>x.Name==policy))d.Add($"piping-port-unknown-policy:{b.Name}:{policy}");var position=Point(Field(b.Body,"Position"),d,"port:"+b.Name);var direction=Vector(Field(b.Body,"Direction"),d,"port:"+b.Name);if(!Axis(direction))d.Add($"piping-port-direction-nonorthogonal:{b.Name}");if(!Enum.TryParse<PipingConnectionType>(Field(b.Body,"ConnectionType",false) is var ct&&ct.Length>0?ct:"Generic",out var type))d.Add($"piping-port-connection-type-unsupported:{b.Name}");var owner=Field(b.Body,"Equipment",false);var nozzleLength=Length(Field(b.Body,"NozzleLength",false),0,d,"port:"+b.Name);string? ownerKeepOut=null;if(owner.Length>0){var e=equipment.SingleOrDefault(x=>x.Name==owner);if(e is null)d.Add($"piping-port-unknown-equipment:{b.Name}:{owner}");else ownerKeepOut=e.KeepOut;if(nozzleLength<=0)d.Add($"piping-nozzle-length-invalid:{b.Name}");}else if(nozzleLength>0)d.Add($"piping-nozzle-owner-required:{b.Name}");ports.Add(new($"interface:port:{b.Name}",b.Name,position,direction,policy,type,$"datum-frame:port:{b.Name}",owner.Length>0?owner:null,ownerKeepOut,nozzleLength));}Duplicates(ports.Select(x=>x.Name),"port",d);- var connections=new List<PipingConnectionIr>();foreach(var b in Blocks(source,"Connection")){var from=Field(b.Body,"From");var to=Field(b.Body,"To");var policy=Field(b.Body,"PipePolicy");var fp=ports.SingleOrDefault(x=>x.Name==from);var tp=ports.SingleOrDefault(x=>x.Name==to);if(fp is null||tp is null){d.Add($"piping-connection-unknown-port:{b.Name}");continue;}if(!policies.Any(x=>x.Name==policy)){d.Add($"piping-connection-unknown-policy:{b.Name}:{policy}");continue;}var reducer=fp.PipePolicy!=tp.PipePolicy;var adapter=fp.ConnectionType!=tp.ConnectionType;if(reducer&&!Bool(Field(b.Body,"Reducer",false)))d.Add($"piping-incompatible-port:{b.Name}: different pipe policies require Reducer: true");if(adapter&&!Bool(Field(b.Body,"Adapter",false)))d.Add($"piping-incompatible-port:{b.Name}: connection styles require Adapter: true");connections.Add(new($"connection:{b.Name}",b.Name,from,to,policy,Field(b.Body,"Service",false).Trim('"') is var s&&s.Length>0?s:null,reducer,adapter));}Duplicates(connections.Select(x=>x.Name),"connection",d);- var routes=new List<RouteIr>();foreach(var b in Blocks(source,"Route")){var connection=connections.SingleOrDefault(x=>x.Name==Field(b.Body,"Connection"));if(connection is null){d.Add($"piping-route-unknown-connection:{b.Name}");continue;}var points=Points(Field(b.Body,"Through"),d,"route:"+b.Name);var from=ports.Single(x=>x.Name==connection.FromPort);var to=ports.Single(x=>x.Name==connection.ToPort);if(points.Count==0||!Near(points[0],from.Position)||!Near(points[^1],to.Position))d.Add($"piping-route-endpoints-mismatch:{b.Name}");var anchors=points.Select((p,i)=>new RouteAnchorIr($"route:{b.Name}:anchor:{i}",i,p,i==0||i==points.Count-1?RouteAnchorKind.Endpoint:RouteAnchorKind.HardWaypoint)).ToArray();var locks=Ints(Field(b.Body,"LockedSegments",false));var provenance=Enum.TryParse<RouteProvenance>(Field(b.Body,"Provenance",false),out var pv)?pv:RouteProvenance.Explicit;var bend=Length(Field(b.Body,"BendRadius",false),Math.Max(50,policies.Single(x=>x.Name==connection.PipePolicy).OuterDiameterMm*2),d,b.Name);routes.Add(OrthogonalAutoRouter.BuildRoute(b.Name,connection.Name,from.StableId,to.StableId,anchors,bend,provenance,sourceIdentity,locks));}- var provisional=new Parsed(system.Name,policies,equipment,ports,connections,keepouts,routes,[],[],defaultClear);- var requests=new List<AcceptedRequest>();foreach(var b in Blocks(source,"RouteRequest")){var connection=connections.SingleOrDefault(x=>x.Name==Field(b.Body,"Connection"));if(connection is null){d.Add($"piping-route-request-unknown-connection:{b.Name}");continue;}var clearance=Length(Field(b.Body,"Clearance",false),defaultClear,d,b.Name);var bend=Length(Field(b.Body,"BendRadius",false),Math.Max(50,policies.Single(x=>x.Name==connection.PipePolicy).OuterDiameterMm*2),d,b.Name);var req=RequestFor(connection,provisional,b.Name,clearance) with{HardWaypoints=Points(Field(b.Body,"HardWaypoints",false),d,"request:"+b.Name),BendRadiusMm=bend};requests.Add(new(req,Field(b.Body,"AcceptAs",false)));}- var reroutes=new List<RerouteSpec>();foreach(var b in Blocks(source,"LocalReroute")){if(!int.TryParse(Field(b.Body,"FromAnchor"),out var from)||!int.TryParse(Field(b.Body,"ToAnchor"),out var to)){d.Add($"piping-local-reroute-anchor-invalid:{b.Name}");continue;}reroutes.Add(new(b.Name,Field(b.Body,"Route"),from,to,Names(Field(b.Body,"Avoid",false)),Length(Field(b.Body,"Clearance",false),defaultClear,d,b.Name)));}- return provisional with{Requests=requests,Reroutes=reroutes};- }-private static RouteRequestIr RequestFor(PipingConnectionIr c,Parsed p,string name,double clearance)=>new($"route-request:{name}",name,c.Name,p.Ports.Single(x=>x.Name==c.FromPort),p.Ports.Single(x=>x.Name==c.ToPort),p.Policies.Single(x=>x.Name==c.PipePolicy),p.KeepOuts,clearance,[]);private static void ValidateNozzleContracts(Parsed p,List<string>d){@@ -205,16 +192,6 @@ public static class PipingAuthoringprivate static IReadOnlyList<PipeCutListEntry> BuildCutList(IReadOnlyList<PipePolicyIr>p,IReadOnlyList<PipeSegmentComponentIr>s)=>s.GroupBy(x=>new{x.PipePolicy,x.Material,Length=Q(x.CutLengthMm)}).Select((g,i)=>{var policy=p.Single(x=>x.StableId==g.Key.PipePolicy);return new PipeCutListEntry($"pipe-cut-group:{i+1}",g.Key.PipePolicy,policy.OuterDiameterMm,policy.WallThicknessMm,g.Key.Material,g.First().CutLengthMm,g.Count(),g.Select(x=>x.StableId).Order().ToArray());}).OrderBy(x=>x.PipePolicy).ThenBy(x=>x.CutLengthMm).ToArray();private static IEnumerable<Point3D> BodyPoints(BrepBody b)=>b.Topology.Vertices.Select(v=>b.TryGetVertexPoint(v.Id,out var p)?p:default);private static bool IsEnclosed(BrepBody b)=>b.ShellRepresentation is not null&&b.Topology.Edges.All(e=>{var uses=b.Topology.Coedges.Count(c=>c.EdgeId==e.Id);return uses>=2&&uses%2==0;});- private static IReadOnlyList<Block> Blocks(string source,string keyword){var result=new List<Block>();foreach(Match m in Regex.Matches(source,$@"\b{keyword}\s+(?<n>[A-Za-z_]\w*)\s*\{{",RegexOptions.CultureInvariant)){var open=m.Index+m.Length-1;var close=Matching(source,open);if(close>open)result.Add(new(m.Groups["n"].Value,source[(open+1)..close]));}return result;}- private static int Matching(string s,int open){var depth=0;for(var i=open;i<s.Length;i++){if(s[i]=='{')depth++;else if(s[i]=='}'&&--depth==0)return i;}return-1;}- private static string Field(string body,string name,bool required=true){var m=Regex.Match(body,$@"\b{Regex.Escape(name)}\s*:\s*(?<v>[^;]+);",RegexOptions.CultureInvariant);return m.Success?m.Groups["v"].Value.Trim():required?"":"";}- private static double Length(string value,double fallback,List<string>d,string owner){if(string.IsNullOrWhiteSpace(value))return fallback;var n=value.Replace("mm","",StringComparison.Ordinal).Trim();if(double.TryParse(n,NumberStyles.Float,CultureInfo.InvariantCulture,out var x)&&double.IsFinite(x))return x;d.Add($"piping-length-invalid:{owner}:{value}");return fallback;}- private static Point3D Point(string value,List<string>d,string owner){var v=Vector(value,d,owner);return new(v.X,v.Y,v.Z);}- private static Vector3D Vector(string value,List<string>d,string owner){var parts=value.Trim().Trim('[',']').Split(',',StringSplitOptions.TrimEntries|StringSplitOptions.RemoveEmptyEntries);if(parts.Length!=3){d.Add($"piping-vector-invalid:{owner}:{value}");return default;}var values=parts.Select(x=>Length(x,0,d,owner)).ToArray();return new(values[0],values[1],values[2]);}- private static IReadOnlyList<Point3D> Points(string value,List<string>d,string owner)=>Regex.Matches(value??"",@"\[(?<p>[^\[\]]+)\]").Select(m=>Point(m.Groups["p"].Value,d,owner)).ToArray();- private static IReadOnlyList<int> Ints(string v)=>v.Trim().Trim('[',']').Split(',',StringSplitOptions.TrimEntries|StringSplitOptions.RemoveEmptyEntries).Select(x=>int.TryParse(x,out var n)?n:-1).Where(x=>x>=0).ToArray();- private static IReadOnlyList<string> Names(string v)=>v.Trim().Trim('[',']').Split(',',StringSplitOptions.TrimEntries|StringSplitOptions.RemoveEmptyEntries).Select(x=>x.Trim('"')).ToArray();- private static bool Bool(string v)=>string.Equals(v,"true",StringComparison.OrdinalIgnoreCase);private static bool Axis(Vector3D v)=>new[]{Math.Abs(v.X)>Tol,Math.Abs(v.Y)>Tol,Math.Abs(v.Z)>Tol}.Count(x=>x)==1;private static bool Parallel(Vector3D a,Vector3D b)=>a.Cross(b).Length<=Tol;private static double Dot(Vector3D a,Vector3D b)=>a.Dot(b);diff --git a/Aetheris.Kernel.Firmament/Piping/PipingModels.cs b/Aetheris.Kernel.Firmament/Piping/PipingModels.csindex f670e78a..0781b426 100644--- a/Aetheris.Kernel.Firmament/Piping/PipingModels.cs+++ b/Aetheris.Kernel.Firmament/Piping/PipingModels.cs@@ -115,4 +115,21 @@ public sealed record PipingCompilationResult(bool IsSuccess, string? StepText, PipingReport? Report, IReadOnlyList<string> Diagnostics,IReadOnlyList<PipeSegmentComponentIr>? RealizedSegments = null,IReadOnlyList<PipingFittingComponentIr>? RealizedFittings = null,- IReadOnlyList<EquipmentNozzleComponentIr>? RealizedNozzles = null);+ IReadOnlyList<EquipmentNozzleComponentIr>? RealizedNozzles = null)+{+ public IReadOnlyList<FirmamentV2.FirmamentV2ValidationDiagnostic> FrontendDiagnostics { get; init; } = [];++ public IReadOnlyList<Core.Diagnostics.KernelDiagnostic> KernelDiagnostics()+ {+ var spans = FrontendDiagnostics.GroupBy(d => d.Code.Split(':')[0])+ .ToDictionary(g => g.Key, g => new Queue<FirmamentV2.FirmamentV2ValidationDiagnostic>(g));+ return Diagnostics.Select(message =>+ {+ var code = message.Split(':')[0];+ var located = spans.TryGetValue(code, out var pending) && pending.Count > 0 ? pending.Dequeue() : null;+ return new Core.Diagnostics.KernelDiagnostic(Core.Diagnostics.KernelDiagnosticCode.ValidationFailed,+ Core.Diagnostics.KernelDiagnosticSeverity.Error, located is null ? message : code + ": " + located.Message, "Firmament.Piping")+ { OriginalSourceSpan = located?.SourceSpan is { } span ? new(span.Start, span.Length) { LocationNote = located.LocationNote } : null };+ }).ToArray();+ }+}diff --git a/Aetheris.Kernel.Firmament/Piping/PipingSyntaxBinding.cs b/Aetheris.Kernel.Firmament/Piping/PipingSyntaxBinding.csnew file mode 100644index 00000000..9a302052--- /dev/null+++ b/Aetheris.Kernel.Firmament/Piping/PipingSyntaxBinding.cs@@ -0,0 +1,352 @@+using Aetheris.Kernel.Core.Math;+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++namespace Aetheris.Kernel.Firmament.Piping;++public static partial class PipingAuthoring+{+ private enum RouteSpaceField { Clearance }+ private enum PipePolicyField { OuterDiameter, WallThickness, Material }+ private enum KeepOutField { Min, Max, Concept }+ private enum EquipmentField { KeepOut }+ private enum PortField { PipePolicy, Position, Direction, ConnectionType, Equipment, NozzleLength }+ private enum ConnectionField { From, To, PipePolicy, Service, Reducer, Adapter }+ private enum RouteField { Connection, Through, LockedSegments, Provenance, BendRadius }+ private enum RouteRequestField { Connection, Clearance, BendRadius, HardWaypoints, AcceptAs }+ private enum LocalRerouteField { Route, FromAnchor, ToAnchor, Avoid, Clearance }+ internal static IReadOnlyList<string> FieldsFor(DeclarationSyntax declaration) => declaration.Type.Name.Text switch+ {+ "RouteSpace" => Enum.GetNames<RouteSpaceField>(),+ "PipePolicy" => Enum.GetNames<PipePolicyField>(),+ "KeepOut" => Enum.GetNames<KeepOutField>(),+ "Equipment" => Enum.GetNames<EquipmentField>(),+ "Port" => Enum.GetNames<PortField>(),+ "Connection" => Enum.GetNames<ConnectionField>(),+ "Route" => Enum.GetNames<RouteField>(),+ "RouteRequest" => Enum.GetNames<RouteRequestField>(),+ "LocalReroute" => Enum.GetNames<LocalRerouteField>(),+ _ => []+ };++ // The AST owns statement boundaries. Only direct children of PipingSystem+ // enter this binder; a declaration inside a Port cannot become a system peer.+ private static Parsed? Parse(string source, string sourceIdentity, List<string> errors,+ List<FirmamentV2ValidationDiagnostic> located)+ {+ var frontend = FirmamentFrontendSchemas.Select(source);+ errors.AddRange(frontend.Diagnostics);+ located.AddRange(frontend.LocatedDiagnostics);+ if (!frontend.IsSuccess) return null;+ var binding = new FirmamentDomainBinding(frontend.Source, sourceIdentity, "PipingSystem", new HashSet<string>(StringComparer.Ordinal));+ located.AddRange(binding.Diagnostics);+ errors.AddRange(binding.Diagnostics.Where(d => d.Severity is "error" or "fatal").Select(d => d.Code + ": " + d.Message));+ if (errors.Count != 0) return null;++ var systems = new List<DeclarationSyntax>();+ var imports = new HashSet<string>(StringComparer.Ordinal);+ foreach (var use in binding.Document.Statements.OfType<DirectiveSyntax>().Where(d => d.Kind == DirectiveKind.Use))+ {+ var module = FirmamentSyntaxValues.Reference(use.Value);+ if (module is not null && FirmamentStandardLibraryResolver.IsModule(module)) imports.Add(module);+ else Unknown(use, $"Standard library module '{module}' (not found in the shipped catalogue)");+ }+ Visit(binding.Document.Statements);+ if (systems.Count != 1)+ errors.Add("piping-system-cardinality: exactly one PipingSystem is required");+ if (errors.Count != 0) return null;+ var system = systems[0];+ var children = system.Body?.Statements.OfType<DeclarationSyntax>().ToArray() ?? [];+ var systemFields = new PipingFields(system with { Body = system.Body is null ? null : system.Body with+ { Statements = system.Body.Statements.Where(s => s is not DeclarationSyntax).ToArray() } }, errors, located, binding);+ systemFields.Complete();+ var owned = new Dictionary<string, List<PipingFields>>(StringComparer.Ordinal);+ foreach (var child in children)+ {+ if (child.Type.Name.Text is not ("PipePolicy" or "KeepOut" or "Equipment" or "Port" or "Connection"+ or "RouteSpace" or "Route" or "RouteRequest" or "LocalReroute"))+ {+ Unknown(child, "PipingSystem");+ continue;+ }+ if (!owned.TryGetValue(child.Type.Name.Text, out var entries)) owned[child.Type.Name.Text] = entries = [];+ entries.Add(new(child, errors, located, binding));+ }+ IEnumerable<PipingFields> Of(string type) => owned.GetValueOrDefault(type) ?? [];+ // Diagnose duplicate names before resolving with SingleOrDefault.+ foreach (var group in owned.Values)+ foreach (var duplicate in group.GroupBy(f => f.Name, StringComparer.Ordinal).Where(g => g.Count() > 1))+ {+ var kind = duplicate.First().Kind;+ var label = kind == "PipePolicy" ? "pipe-policy" : kind.ToLowerInvariant();+ errors.Add($"piping-duplicate-{label}:{duplicate.Key}");+ }+ if (errors.Count != 0) return null;++ var spaces = Of("RouteSpace").ToArray();+ if (spaces.Length > 1) errors.Add("piping-route-space-cardinality: at most one system default RouteSpace is supported");+ var defaultClearance = 25d;+ foreach (var f in spaces) { defaultClearance = f.Length(nameof(RouteSpaceField.Clearance), 25); f.Nonnegative(nameof(RouteSpaceField.Clearance), defaultClearance); f.Complete(); }++ var policies = new List<PipePolicyIr>();+ foreach (var f in Of("PipePolicy"))+ {+ var od = f.Length(nameof(PipePolicyField.OuterDiameter)); var wall = f.Length(nameof(PipePolicyField.WallThickness)); var material = f.Text(nameof(PipePolicyField.Material));+ if (od <= 0 || wall <= 0) errors.Add($"piping-pipe-policy-positive:{f.Name}");+ if (2 * wall >= od) errors.Add($"piping-pipe-wall-too-thick:{f.Name}");+ if (!new StandardLibrary.Materials.MaterialResolver().Resolve(material).IsSuccess)+ errors.Add($"piping-material-unresolved:{f.Name}:{material}");+ policies.Add(new($"standard:piping:pipe:{Q(od)}:{Q(wall)}:{material}", f.Name, od, wall, material));+ f.Complete();+ }+ if (policies.Count == 0) errors.Add("piping-pipe-policy-required: declare at least one PipePolicy");+ var keepouts = new List<KeepOutIr>();+ foreach (var f in Of("KeepOut"))+ {+ var min = f.Point(nameof(KeepOutField.Min)); var max = f.Point(nameof(KeepOutField.Max));+ var concept = f.Text(nameof(KeepOutField.Concept), "KeepOut");+ if (max.X <= min.X || max.Y <= min.Y || max.Z <= min.Z) errors.Add($"piping-keepout-invalid-bounds:{f.Name}");+ keepouts.Add(new($"concept:keepout:{f.Name}", f.Name, min, max, concept)); f.Complete();+ }+ var equipment = new List<PipingEquipmentIr>();+ foreach (var f in Of("Equipment"))+ {+ var keepout = f.Text(nameof(EquipmentField.KeepOut));+ if (!keepouts.Any(k => k.Name == keepout)) errors.Add($"piping-equipment-unknown-keepout:{f.Name}:{keepout}");+ equipment.Add(new($"equipment:{f.Name}", f.Name, keepout)); f.Complete();+ }+ var ports = new List<PipingPortInterfaceIr>();+ foreach (var f in Of("Port"))+ {+ var policy = f.Text(nameof(PortField.PipePolicy)); var position = f.Point(nameof(PortField.Position)); var direction = f.Vector(nameof(PortField.Direction), "");+ var type = f.Choice(nameof(PortField.ConnectionType), PipingConnectionType.Generic);+ var owner = f.Text(nameof(PortField.Equipment), ""); var nozzleLength = f.Length(nameof(PortField.NozzleLength), 0);+ if (!policies.Any(p => p.Name == policy)) errors.Add($"piping-port-unknown-policy:{f.Name}:{policy}");+ if (!Axis(direction)) errors.Add($"piping-port-direction-nonorthogonal:{f.Name}");+ string? ownerKeepout = null;+ if (owner.Length > 0)+ {+ var e = equipment.SingleOrDefault(e => e.Name == owner);+ if (e is null) errors.Add($"piping-port-unknown-equipment:{f.Name}:{owner}");+ else ownerKeepout = e.KeepOut;+ if (nozzleLength <= 0) errors.Add($"piping-nozzle-length-invalid:{f.Name}");+ }+ else if (nozzleLength != 0) errors.Add($"piping-nozzle-owner-required:{f.Name}");+ f.Nonnegative(nameof(PortField.NozzleLength), nozzleLength);+ ports.Add(new($"interface:port:{f.Name}", f.Name, position, direction, policy, type, $"datum-frame:port:{f.Name}",+ owner.Length > 0 ? owner : null, ownerKeepout, nozzleLength)); f.Complete();+ }+ var connections = new List<PipingConnectionIr>();+ foreach (var f in Of("Connection"))+ {+ var from = f.Text(nameof(ConnectionField.From)); var to = f.Text(nameof(ConnectionField.To)); var policy = f.Text(nameof(ConnectionField.PipePolicy));+ var service = f.Text(nameof(ConnectionField.Service), ""); var allowReducer = f.Boolean(nameof(ConnectionField.Reducer)); var allowAdapter = f.Boolean(nameof(ConnectionField.Adapter));+ f.Complete();+ var fp = ports.SingleOrDefault(p => p.Name == from); var tp = ports.SingleOrDefault(p => p.Name == to);+ if (fp is null || tp is null) { errors.Add($"piping-connection-unknown-port:{f.Name}"); continue; }+ if (!policies.Any(p => p.Name == policy)) { errors.Add($"piping-connection-unknown-policy:{f.Name}:{policy}"); continue; }+ var reducer = fp.PipePolicy != tp.PipePolicy; var adapter = fp.ConnectionType != tp.ConnectionType;+ if (reducer && !allowReducer) errors.Add($"piping-incompatible-port:{f.Name}: different pipe policies require reducer: true");+ if (adapter && !allowAdapter) errors.Add($"piping-incompatible-port:{f.Name}: connection styles require adapter: true");+ connections.Add(new($"connection:{f.Name}", f.Name, from, to, policy, service.Length > 0 ? service : null, reducer, adapter));+ }+ if (errors.Count != 0) return null;+ var routes = new List<RouteIr>();+ foreach (var f in Of("Route"))+ {+ var connectionName = f.Text(nameof(RouteField.Connection)); var points = f.Points(nameof(RouteField.Through));+ var locks = f.Integers(nameof(RouteField.LockedSegments)); var provenance = f.Choice(nameof(RouteField.Provenance), RouteProvenance.Explicit);+ var connection = connections.SingleOrDefault(c => c.Name == connectionName);+ var policy = policies.SingleOrDefault(p => p.Name == connection?.PipePolicy);+ var bend = f.Length(nameof(RouteField.BendRadius), Math.Max(50, (policy?.OuterDiameterMm ?? 25) * 2));+ f.Positive(nameof(RouteField.BendRadius), bend); f.Complete();+ if (connection is null) { errors.Add($"piping-route-unknown-connection:{f.Name}"); continue; }+ var from = ports.Single(p => p.Name == connection.FromPort); var to = ports.Single(p => p.Name == connection.ToPort);+ if (points.Count < 2 || !Near(points[0], from.Position) || !Near(points[^1], to.Position))+ errors.Add($"piping-route-endpoints-mismatch:{f.Name}");+ if (locks.Any(i => i >= points.Count - 1)) f.Invalid(nameof(RouteField.LockedSegments), "Use segment indices within this route.");+ if (errors.Count != 0) continue;+ var anchors = points.Select((p, i) => new RouteAnchorIr($"route:{f.Name}:anchor:{i}", i, p,+ i == 0 || i == points.Count - 1 ? RouteAnchorKind.Endpoint : RouteAnchorKind.HardWaypoint)).ToArray();+ routes.Add(OrthogonalAutoRouter.BuildRoute(f.Name, connection.Name, from.StableId, to.StableId, anchors, bend, provenance, sourceIdentity, locks));+ }+ var provisional = new Parsed(system.Name!.Text, policies, equipment, ports, connections, keepouts, routes, [], [], defaultClearance);+ var requests = new List<AcceptedRequest>();+ foreach (var f in Of("RouteRequest"))+ {+ var connectionName = f.Text(nameof(RouteRequestField.Connection)); var clearance = f.Length(nameof(RouteRequestField.Clearance), defaultClearance);+ var connection = connections.SingleOrDefault(c => c.Name == connectionName);+ var policy = policies.SingleOrDefault(p => p.Name == connection?.PipePolicy);+ var bend = f.Length(nameof(RouteRequestField.BendRadius), Math.Max(50, (policy?.OuterDiameterMm ?? 25) * 2));+ var waypoints = f.Points(nameof(RouteRequestField.HardWaypoints), optional: true); var acceptAs = f.Text(nameof(RouteRequestField.AcceptAs), "");+ f.Nonnegative(nameof(RouteRequestField.Clearance), clearance); f.Positive(nameof(RouteRequestField.BendRadius), bend); f.Complete();+ if (connection is null) { errors.Add($"piping-route-request-unknown-connection:{f.Name}"); continue; }+ requests.Add(new(RequestFor(connection, provisional, f.Name, clearance) with { HardWaypoints = waypoints, BendRadiusMm = bend }, acceptAs));+ }+ var reroutes = new List<RerouteSpec>();+ foreach (var f in Of("LocalReroute"))+ {+ var route = f.Text(nameof(LocalRerouteField.Route)); var from = f.Integer(nameof(LocalRerouteField.FromAnchor)); var to = f.Integer(nameof(LocalRerouteField.ToAnchor));+ var avoid = f.Names(nameof(LocalRerouteField.Avoid)); var clearance = f.Length(nameof(LocalRerouteField.Clearance), defaultClearance);+ f.Nonnegative(nameof(LocalRerouteField.Clearance), clearance); f.Complete();+ reroutes.Add(new(f.Name, route, from, to, avoid, clearance));+ }+ return provisional with { Requests = requests, Reroutes = reroutes };++ void Visit(IReadOnlyList<StatementSyntax> statements)+ {+ var bindings = new HashSet<string>(StringComparer.Ordinal);+ foreach (var statement in statements)+ {+ if (statement is DirectiveSyntax { Kind: DirectiveKind.Use } && ReferenceEquals(statements, binding.Document.Statements)) continue;+ if (statement is DeclarationSyntax data && binding.OwnsData(data)) continue;+ if (statement is DeclarationSyntax d && d.Type.Name.Text == "PipingSystem") { systems.Add(d); continue; }+ if (statement is DeclarationSyntax { Type.Name.Text: "Let", Initializer: { } value, Name: { } name } alias+ && alias.Body is null && alias.Parameters.Count == 0 && !alias.HasParameterList && alias.Modifiers.Count == 0+ && alias.Type.Arguments.Count == 0 && alias.Clauses.Count == 0 && alias.Annotation is null && alias.ResultType is null)+ {+ // A catalogue alias is compile-time data, not a material request.+ // Bind it against the existing shipped catalogue, never an allowlist+ // of fixture names or unconsumed declarations.+ var reference = FirmamentSyntaxValues.Reference(value) ?? "";+ var split = reference.LastIndexOf('.');+ if (split < 1 || !imports.Contains(reference[..split]) || !FirmamentStandardLibraryResolver.IsExport(reference[..split], reference[(split + 1)..]))+ Unknown(alias, $"Piping catalogue binding '{reference}' (requires a used, known Standard export)");+ if (!bindings.Add(name.Text)) Unknown(alias, "duplicate catalogue binding");+ continue;+ }+ if (statement is DeclarationSyntax wrapper && wrapper.Type.Name.Text is "Model" or "Struct")+ {+ var fields = new PipingFields(wrapper with { Body = wrapper.Body is null ? null : wrapper.Body with+ { Statements = wrapper.Body.Statements.Where(s => s is not DeclarationSyntax).ToArray() } }, errors, located, binding);+ // Piping's historical unitless document header means mm;+ // retain it while rejecting an explicitly conflicting unit.+ var units = fields.Text("Units", "mm");+ if (units != "mm") fields.Invalid("Units", "Piping models use millimetres (units: mm).");+ fields.Complete();+ Visit(wrapper.Body?.Statements.OfType<DeclarationSyntax>().Cast<StatementSyntax>().ToArray() ?? []);+ }+ else Unknown(statement, "Piping document");+ }+ }+ void Unknown(StatementSyntax statement, string context)+ {+ var name = (statement as DeclarationSyntax)?.Type.Name.Text ?? "statement";+ var code = $"{FirmamentV2Parser.CanonicalDeclarationUnknown}:{context}:{name}";+ errors.Add(code);+ located.Add(new(code.Split(':')[0], "error", $"Unsupported {name} in {context}.")+ { SourceFile = sourceIdentity, SourceSpan = binding.OriginalSpan(statement.Span), LocationNote = binding.IsExpanded ? "Location identifies the original enclosing declaration after compile-time expansion." : null, Stage = "Binding", Source = "Firmament.Piping" });+ }+ }++ private sealed class PipingFields(DeclarationSyntax declaration, List<string> errors, List<FirmamentV2ValidationDiagnostic> located, FirmamentDomainBinding binding)+ {+ private readonly List<string> fieldErrors = [];+ private FirmamentSyntaxFields? fields;+ private FirmamentSyntaxFields Fields => fields ??= new(declaration, fieldErrors, bind: binding.Nominal);+ public string Name => declaration.Name?.Text ?? "";+ public string Kind => declaration.Type.Name.Text;+ private ExpressionSyntax? Take(string name, bool required)+ {+ var value = Fields.Take(name);+ if (value is null && required) Invalid(name, $"Required field '{FirmamentSourceSpelling.PreferredField(name)}' is missing.");+ return value;+ }+ public string Text(string name, string? fallback = null)+ {+ var value = Take(name, fallback is null);+ if (value is null) return fallback ?? "";+ if (FirmamentSyntaxValues.Reference(value) is { Length: > 0 } text) return text;+ Invalid(name, "Expected a name or nonempty string."); return fallback ?? "";+ }+ public double Length(string name, double? fallback = null)+ {+ var value = Take(name, fallback is null);+ if (value is null) return fallback ?? 0;+ // Historical numeric lengths are millimetres. Directions are dimensionless.+ if (FirmamentSyntaxValues.TryMeasure(value, "mm", out var number, "mm") && double.IsFinite(number)) return number;+ Invalid(name, "Expected a finite length in mm."); return fallback ?? 0;+ }+ public Vector3D Vector(string name, string unit)+ {+ var value = Take(name, true);+ if (FirmamentSyntaxValues.Vector(value, unit, out var values, unit) && values.Length == 3 && values.All(double.IsFinite))+ return new(values[0], values[1], values[2]);+ if (value is not null) Invalid(name, unit.Length == 0 ? "Expected three dimensionless components." : "Expected three lengths in mm.");+ return default;+ }+ public Point3D Point(string name) { var v = Vector(name, "mm"); return new(v.X, v.Y, v.Z); }+ private IReadOnlyList<ExpressionSyntax> Items(string name, bool optional)+ {+ var value = Take(name, !optional);+ if (value is SequenceSyntax { Kind: SequenceKind.List } list && list.Items.All(i => i.Name is null && i.Default is null))+ return list.Items.Select(i => i.Value).ToArray();+ if (value is not null) Invalid(name, "Expected a list.");+ return [];+ }+ public IReadOnlyList<Point3D> Points(string name, bool optional = false)+ {+ var result = new List<Point3D>();+ foreach (var value in Items(name, optional))+ {+ if (FirmamentSyntaxValues.Vector(value, "mm", out var v, "mm") && v.Length == 3 && v.All(double.IsFinite)) result.Add(new(v[0], v[1], v[2]));+ else Invalid(name, "Each waypoint must contain three lengths in mm.");+ }+ return result;+ }+ public bool Boolean(string name)+ {+ var value = Take(name, false);+ if (value is null) return false;+ if (value is LiteralSyntax { Kind: LiteralKind.Boolean } literal) return literal.Raw == "true";+ Invalid(name, "Expected true or false."); return false;+ }+ public T Choice<T>(string name, T fallback) where T : struct, Enum+ {+ var value = Take(name, false);+ if (value is null) return fallback;+ var word = FirmamentSyntaxValues.Reference(value);+ if (word is not null && Enum.GetNames<T>().Contains(word, StringComparer.Ordinal) && Enum.TryParse<T>(word, out var choice)) return choice;+ Invalid(name, $"Expected one of {string.Join(", ", Enum.GetNames<T>())}."); return fallback;+ }+ private int Index(string name, ExpressionSyntax? value)+ {+ if (FirmamentSyntaxValues.TryMeasure(value, "", out var n) && double.IsFinite(n) && n >= 0 && n <= int.MaxValue && n == Math.Truncate(n)) return (int)n;+ if (value is not null) Invalid(name, "Expected a nonnegative integer index.");+ return -1;+ }+ public int Integer(string name) => Index(name, Take(name, true));+ public IReadOnlyList<int> Integers(string name) => Items(name, true).Select(v => Index(name, v)).ToArray();+ public IReadOnlyList<string> Names(string name) => Items(name, true).Select(v =>+ {+ var text = FirmamentSyntaxValues.Reference(v);+ if (text is not null) return text;+ Invalid(name, "Expected KeepOut names."); return "";+ }).ToArray();+ public void Nonnegative(string name, double value) { if (value < 0) Invalid(name, "Expected a nonnegative length."); }+ public void Positive(string name, double value) { if (value <= 0) Invalid(name, "Expected a positive length."); }+ public void Invalid(string name, string message)+ {+ var code = $"piping-field-value-invalid:{Kind}:{Name}:{name}";+ errors.Add(code + ": " + message);+ var field = declaration.Body?.Statements.OfType<FieldSyntax>().FirstOrDefault(f => FirmamentSyntaxFields.SameField(f.Name.Text, name));+ located.Add(new("piping-field-value-invalid", "error", $"{Kind} {Name}, field '{FirmamentSourceSpelling.PreferredField(name)}': {message}")+ { SourceSpan = binding.OriginalSpan(field?.Span ?? declaration.Span), LocationNote = binding.IsExpanded ? "Location identifies the original enclosing declaration after compile-time expansion." : null, Stage = "Binding", Source = "Firmament.Piping" });+ }+ public void Complete()+ {+ if (declaration.Name is null || declaration.Body is null || declaration.Type.Arguments.Count > 0 || declaration.Modifiers.Count > 0 || declaration.HasParameterList)+ fieldErrors.Add($"{FirmamentV2Parser.CanonicalDeclarationUnknown}:{Kind}:header");+ Fields.Complete();+ foreach (var code in fieldErrors)+ {+ errors.Add(code);+ var fieldName = code.Split(':').Last();+ var field = declaration.Body?.Statements.OfType<FieldSyntax>().FirstOrDefault(f => FirmamentSyntaxFields.SameField(f.Name.Text, fieldName));+ var child = declaration.Body?.Statements.OfType<DeclarationSyntax>().FirstOrDefault(d => d.Type.Name.Text == fieldName);+ located.Add(new(code.Split(':')[0], "error", FirmamentV2.FirmamentInterop.FirmamentV2DiagnosticAdapter.MessageFor(code))+ { SourceSpan = binding.OriginalSpan(field?.Name.Span ?? child?.Span ?? declaration.Span), LocationNote = binding.IsExpanded ? "Location identifies the original enclosing declaration after compile-time expansion." : null, Stage = "Binding", Source = "Firmament.Piping" });+ }+ }+ }+}diff --git a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.mdindex 52154634..24df23cb 100644--- a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md+++ b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md@@ -414,7 +414,7 @@ compiler-honesty failure. This does not close X2.| CORPUS-06: Inner-loop segment identity | Fixed source | Give inner segments explicit aliases; preserve 4160 mm3 intended volume. || CORPUS-07: SurfaceCoil supports | Separate semantic/capability prerequisite | Preserve centerline-only witnesses outside Canonical. Define nonmaterial analytic support binding before admitting support solids plus wire output; never erase material implicitly. || CORPUS-08: Fixture qualification levels | Applied | Qualify modules through real consumers; inspect gear interfaces; record missing garment bodies separately. Solver-invalid and DFM-warning specimens are not syntax failures. Preserve the now-valid Rect2 TraceLoop specimen and use an open Line2 for the actual negative. |-| CORPUS-09: Piping optional fields | Open, next AST owner migration | Both lowercase connectionType and unknown fields currently disappear; validate/build accept. Migrate Piping's existing construct/field ownership to shared AST consumption before its casing sweep. Two pending source witnesses are intentionally not counted as correct admission. |+| CORPUS-09: Piping optional fields | Fixed, Piping AST admission pass | Original reproduction: lowercase connectionType became Generic and unknown fields disappeared. Direct AST production owners now consume shared fields; aliases retain Weld, unknown/duplicate/malformed fields reject. The unchanged source specimens were promoted to accepted/invalid regressions. See [qualification](FIRMAMENT-PIPING-AST-ADMISSION-2026-10.md). || CORPUS-10: Legacy semantic-panel Pattern | Deferred identity reconciliation | Keep existing PanelLayout.MountingHoles[index] public paths. Decide explicit identity projection when migrating this Count/Pitch bundle to keyed Feature expansion; do not change IDs for presentation alone. || CORPUS-11: Embedded BodyState chains | Fixed ownership | Station-shaped SectionChain construction data belongs to the containing surfacing document. Ordinary Section/Loft and explicit schema guards retain their own rejection behavior; validate/build/inspect must select the same owner. |diff --git a/docs/development/FIRMAMENT-PIPING-AST-ADMISSION-2026-10.md b/docs/development/FIRMAMENT-PIPING-AST-ADMISSION-2026-10.mdnew file mode 100644index 00000000..778686db--- /dev/null+++ b/docs/development/FIRMAMENT-PIPING-AST-ADMISSION-2026-10.md@@ -0,0 +1,149 @@+# Piping AST admission — 2026-10-17++**Success for this pass.** The two original Piping honesty failures are closed,+production admission uses the unified AST, compatibility is qualified, and all+required local gates pass. This does not declare X2 complete.++## Scope and decisions++This follows the corpus modernization pass and closes its CORPUS-09 blocker.+Piping's existing production owner now binds the unified structural AST directly;+the regex block scanner and semicolon field reader have been removed. This is+production admission, not a shadow validator. The planner, geometry materializers,+STEP exporter, stable identities, BOM and cut-list algorithms are retained.++Use PascalCase constructs, camelCase fields and case-sensitive domain symbols.+Historical PascalCase field names remain compatibility aliases of the same shared+field reader. Owner field enums supply both binding names and formatter vocabulary;+the formatter has no independent Piping field schema. Unknown fields are rejected,+not normalized into accepted intent. No global text rewrite or new regex dispatch+was introduced.++One `PipingSystem` owns direct `PipePolicy`, `KeepOut`, `Equipment`, `Port`,+`Connection`, `RouteSpace`, `Route`, `RouteRequest` and `LocalReroute` children.+Nested declarations cannot leak into its sibling symbol tables. Each field owner+uses `FirmamentSyntaxFields` and closes its scope. Model/Struct wrappers close+their own scopes as well. A document with additional material operations rejects;+an unrelated operation is never omitted from a successful piping artifact.++Lengths retain the existing mm quantities/bare-mm-number convention. Historical+omitted document units mean mm; conflicting explicit units reject. Directions+are dimensionless. Required values must be present; absent optional values keep+the existing defaults. Invalid authored values, duplicate aliases, unknown enum+symbols, invalid indices and unsupported header placements reject. Multiple+RouteSpace defaults reject instead of selecting the first. Duplicate names are+diagnosed before symbol lookup can throw.++An explicitly authored zero system clearance now remains zero. The old reader+overwrote it with the 25 mm absent-field default. This is an intentional repair+of discarded intent, rather than a geometry-parity promise for that defective+spelling. The eight existing canonical sources do not exercise this old fallback.++`schema Piping` is optional and uses the existing schema selector. An explicitly+different domain rejects. Recognition uses AST declarations; comments or string+contents containing `PipingSystem` cannot claim the source.++The eighth canonical source, `tee.firmament`, binds Standard catalogue aliases+alongside an explicit straight route. The same existing catalogue now validates+its `Use` and `Let` references. Such references do not instantiate a tee. They are+not an exception allowing arbitrary statements to be skipped. Forge specializes+PumpSkid beside Record/Static configuration declarations. These+now use the existing shared domain value/expansion binder, including scoped field+lookup and schema checking. No Piping-specific scalar evaluator is introduced.++Normal compilation requires at least one explicit or accepted route. A proposal-+only source now rejects with `piping-route-required` instead of reaching empty+geometry reductions. A proposal can still coexist with other built routes.++## Original witnesses and current behavior++| Witness | Before | Repaired outcome |+| --- | --- | --- |+| `piping-field-casing.pending.firmament` | Validate/build succeeded but `connectionType: Weld` produced Generic ports. | Promoted unchanged to [accepted witness](../../fixtures/Regression/FrontendX2/piping-field-casing.firmament). Weld is bound on both ports; exact canonical STEP is retained. |+| `piping-field-unknown.pending.firmament` | Validate/build succeeded and `unexpectedIntent` disappeared. | Promoted unchanged to [invalid witness](../../fixtures/Invalid/Piping/unknown-port-field.firmament). Validate, inspect and build reject at line 6; no STEP is written. |+| Historical field spellings | Independent PascalCase field parsing. | Eight original sources retained byte-for-byte under [compatibility fixtures](../../fixtures/Compatibility/FirmamentV2/Piping); modern canonical sources use camelCase. |+| Explicit incompatible schema | The schema detector did not identify Piping as a distinct domain. | Mismatch rejects at the schema header before execution. |+| Inspect schema rejection | Bare diagnostic strings bypassed the common presentation contract. | Inspect uses the same structured rejection presenter as validate/build. |++The preserved pending-source comments describe the original bugs intentionally;+their regression status is recorded here and in the fixture README.++## Diagnostic contract++Raw diagnostic strings remain on `PipingCompilationResult.Diagnostics` for .NET+compatibility. `FrontendDiagnostics` retains code, severity, message and original+AST span. The kernel adapter carries already-mapped authored spans separately+from expanded-stage offsets, so presentation does not reparse them through an+unrelated mechanical frontend. Semantic/kernel failures without precise spans+retain the existing disclosed enclosing-document location.++Validate, inspect and build present structured diagnostic objects. Text includes+file, location, severity, code and explanation. Validation reports+`parserRoute: UnifiedPiping` and `validationLevel: Built` or `BuildRejected`;+`valid` means the normal binding/routing/materialization/export path succeeded+without writing output files. No static proof of arbitrary future construction+success is claimed.++## Qualification++All results are local. Raw outputs remain under ignored+`artifacts/local/piping-ast/`. `final-full.log` and `final-tests/` are the+successful final .NET gate; earlier attempt logs are retained separately.++| Check | Result | Evidence |+| --- | --- | --- |+| Release solution build | Passed, 0 errors; 30 existing warnings | `build.log` |+| Fast Core lane | 1,076 passed | `fast.log` |+| Full solution lane | 5,423 passed in 21 assemblies; 0 failures/skips | `final-full.log`, `final-tests/`, `test-summary.json` |+| Focused Piping admission/compatibility | 62 passed | `piping-tests.log` |+| CLI structured agreement/location | 3 passed, including exact original field offsets/columns | `cli-tests.log` |+| Real Forge PumpSkid protocol | Passed | `forge-tests.log` |+| Existing Piping STEP | 8/8 byte-identical before/after | `geometry-parity.json` |+| Routing/BOM/cut-list sidecars | 24/24 byte-identical | `geometry-parity.json` |+| Preserved originals | Eight canonical and two pending sources byte-identical | `preserved-source.json`, `text-checks.json` |+| Explicit zero clearance | Verified 7.5 mm physical clearance admits with authored zero; absent-field 25 mm default rejects | `clearance-zero.json`, `clearance-absent.json` |+| Complete canonical owner gate | Passed: 296 owner operations, 69 consumed modules, 4 expected external-body boundaries (369 sources) | `canonical/qualification.json` |+| Historical domain hash gate | 37/37 hashes and admissions matched | `domain-parity/comparison.json` |+| FrontendX4 authoring corpus | 32/32 passed; source/reference goldens unchanged | `x4.log` |+| Sheet profile/semantic CLI corpora | 26/26 and 29/29 passed; formed STEP / flat parity retained | `sheet-profile.log`, `sheet-semantic.log` |++The task-owned .NET/aetheris/test/compiler hosts all exited after qualification.+The cleanup script parses without errors; preview mode was exercised and no+deletion was executed. Modified/new text, relative Markdown links and+`git diff --check` pass. No remote CI or browser execution is claimed.++The code-quality review checked statement/field closure, shared schema ownership,+source-span provenance, severity, duplicate-name failure, V1 isolation and+validate/build reuse. No new error-code fatality table, rewrite parser, alternate+geometry path, or global mutable parser state was introduced. The existing+Piping planning/materialization algorithms are unchanged. Legacy Zig checks are+outside this pass because no Zig/compiler build infrastructure changed.++Reproduce with:++```powershell+dotnet build Aetheris.slnx -c Release -m:1 -nr:false -p:UseSharedCompilation=false --no-restore+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build --filter "Category!=SlowCorpus"+dotnet test Aetheris.slnx -c Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1+./scripts/Test-CanonicalFixtures.ps1 -NoBuild -OutputDirectory artifacts/local/piping-ast/canonical+./scripts/qualify-firmament-domain-frontend.ps1 -OutputDirectory artifacts/local/piping-ast/domain-parity+python fixtures/Regression/FrontendX4/run.py+```++## Cleanup and remaining work++[Clear-FirmamentCorpusIntermediates.ps1](../../scripts/Clear-FirmamentCorpusIntermediates.ps1)+previews seven explicitly listed old intermediate paths. `-Apply` is required for+deletion and `-Apply -WhatIf` previews the actual operations. It validates paths+inside the intended artifact directory and refuses junctions/symlinks in their+ancestry or contents. It retains final reports, baseline reports, qualification+outputs and source. Only preview mode was run during this pass; the user reviews+and executes deletion. Preview measured approximately 615 MiB of eligible data.++This completes the Piping admission pass, not all X2 work. Independent FEA and+surfacing readers still require their own AST ownership qualification. FEA's+`FirmamentAnalysisCompiler` still owns its regex Header/NestedAll/Scalar parsing;+its numerical and geometry lowering should remain intact when that reader is+migrated. Analytic SurfaceCoil support admission and public identity projection+for legacy sheet-layout Patterns retain the decisions in the earlier corpus+report. No kernel capability or Helios/browser qualification is claimed here.diff --git a/docs/development/FIRMAMENT-V2-CORPUS-MODERNIZATION-2026-10.md b/docs/development/FIRMAMENT-V2-CORPUS-MODERNIZATION-2026-10.mdindex 152fc200..f3d1274e 100644--- a/docs/development/FIRMAMENT-V2-CORPUS-MODERNIZATION-2026-10.md+++ b/docs/development/FIRMAMENT-V2-CORPUS-MODERNIZATION-2026-10.md@@ -1,5 +1,9 @@# Firmament V2 corpus modernization — 2026-10-17+Follow-up: the Piping defects recorded below were subsequently repaired by the+[Piping AST admission pass](FIRMAMENT-PIPING-AST-ADMISSION-2026-10.md). This report+retains the original reproduction and qualification snapshot.+## Result and scope**Meaningful progression.** The current cookbook has been mechanicallydiff --git a/docs/public/firmament/piping.md b/docs/public/firmament/piping.mdindex 250ac1df..51e0b285 100644--- a/docs/public/firmament/piping.md+++ b/docs/public/firmament/piping.md@@ -12,40 +12,40 @@ The router is a design assistant. `RouteProposal` is inspectable; acceptance cop## Ports and logical connections-Use the documented PascalCase piping properties in this guide. The corpus-modernization pass found that `connectionType: Weld` is currently ignored and-becomes Generic, and unknown optional Port fields can also be ignored. These are-open compiler defects, not admitted aliases. Their source specimens and the AST-owner migration prerequisite are recorded in the-[corpus report](../../development/FIRMAMENT-V2-CORPUS-MODERNIZATION-2026-10.md).+Piping uses PascalCase constructs, camelCase fields and preserved catalogue/enum+symbols. Historical PascalCase field aliases remain admitted through the same AST+binder: `connectionType: Weld` and `connectionType: Weld` mean exactly the same+thing. Unknown fields, duplicate aliases, nested foreign statements and unsupported+placement clauses reject with source-located errors. Optional defaults apply only+when a field is absent; malformed authored values never select the default.`Port` is the piping specialization of an Assembly Interface. It has stable identity, a position/DatumFrame, an outward axis direction, a `PipePolicy`, and a bounded connection style.```firmamentPipePolicy Pipe25 {- OuterDiameter: 25mm;- WallThickness: 2mm;- Material: "Standard.Materials.StainlessSteel.304_Annealed";+ outerDiameter: 25mm;+ wallThickness: 2mm;+ material: "Standard.Materials.StainlessSteel.304_Annealed";}Port PumpDischarge {- Position: [100mm,100mm,250mm];- Direction: [1,0,0];- PipePolicy: Pipe25;- ConnectionType: Flange;- Equipment: Pump;- NozzleLength: 50mm;+ position: [100mm,100mm,250mm];+ direction: [1,0,0];+ pipePolicy: Pipe25;+ connectionType: Flange;+ equipment: Pump;+ nozzleLength: 50mm;}Connection Supply {- From: PumpDischarge;- To: CoolerInlet;- PipePolicy: Pipe25;- Service: "CoolingSupply";+ from: PumpDischarge;+ to: CoolerInlet;+ pipePolicy: Pipe25;+ service: "CoolingSupply";}```-Connections exist before routes. Different port policies require `Reducer: true`; different connection styles require `Adapter: true`. X3 records those requirements but does not claim a standards database.+Connections exist before routes. Different port policies require `reducer: true`; different connection styles require `adapter: true`. X3 records those requirements but does not claim a standards database.-Direct `PipePolicy` declarations require all three fields: `OuterDiameter`, `WallThickness`, and `Material`; there are no implicit dimensional or material defaults. Both dimensions must be positive and twice the wall thickness must be less than the OD.+Direct `PipePolicy` declarations require all three fields: `outerDiameter`, `wallThickness`, and `material`; there are no implicit dimensional or material defaults. Both dimensions must be positive and twice the wall thickness must be less than the OD.## Equipment-owned nozzles and endpoint mates@@ -53,22 +53,22 @@ X3a associates a port with one equipment proxy and materializes the gap between```firmamentKeepOut PumpBody {- Min: [0mm,0mm,0mm];- Max: [50mm,300mm,350mm];- Concept: EquipmentProxy;+ min: [0mm,0mm,0mm];+ max: [50mm,300mm,350mm];+ concept: EquipmentProxy;}-Equipment Pump { KeepOut: PumpBody; }+Equipment Pump { keepOut: PumpBody; }Port PumpDischarge {- Position: [100mm,100mm,250mm];- Direction: [1,0,0];- PipePolicy: Pipe25;- ConnectionType: Flange;- Equipment: Pump;- NozzleLength: 50mm;+ position: [100mm,100mm,250mm];+ direction: [1,0,0];+ pipePolicy: Pipe25;+ connectionType: Flange;+ equipment: Pump;+ nozzleLength: 50mm;}```-`Position` is the pipe-side mating plane. The nozzle root is `Position - Direction × NozzleLength` and must lie exactly on the outward face of the equipment's KeepOut. The nozzle exposes `EquipmentMate` at its root and the stable port Interface as `PipeMate` at its tip. The first or last pipe segment exposes its own endpoint Interface at the same position with the opposite outward direction; `PipingMateIr` records that coincidence and opposition explicitly.+`position` is the pipe-side mating plane. The nozzle root is `position - direction × nozzleLength` and must lie exactly on the outward face of the equipment's KeepOut. The nozzle exposes `EquipmentMate` at its root and the stable port Interface as `PipeMate` at its tip. The first or last pipe segment exposes its own endpoint Interface at the same position with the opposite outward direction; `PipingMateIr` records that coincidence and opposition explicitly.The only clearance exemption is an inspectable `PipingKeepOutExemptionIr` scoped as `NozzleEnvelopeOnly` for that port's nozzle against that port's owning equipment KeepOut. It does not apply to the route, another port, another nozzle, or any foreign KeepOut. Thus a nozzle may touch its own equipment face while route and nozzle clearance remain fully enforced everywhere else.@@ -80,17 +80,17 @@ An explicit route is an ordered axis-aligned 3D path. The first run must follow```firmamentRoute SupplyRoute {- Connection: Supply;- Through: [[0mm,0mm,0mm],[300mm,0mm,0mm],[300mm,500mm,0mm]];- BendRadius: 50mm;- LockedSegments: [1];- Provenance: Explicit;+ connection: Supply;+ through: [[0mm,0mm,0mm],[300mm,0mm,0mm],[300mm,500mm,0mm]];+ bendRadius: 50mm;+ lockedSegments: [1];+ provenance: Explicit;}```Interior anchors become semantic 90-degree turns. Straight intervals lower to hollow `PipeSegment` components using the declared OD and wall. Each turn lowers to a hollow analytic-torus `Standard.Piping.Elbow90` occurrence with named `Inlet` and `Outlet` Interfaces. Pipe segments stop at elbow tangent points; cut length is therefore distinct from corner-to-corner route length.-For the admitted 90-degree route, a segment's cut length is its corner-to-corner interval minus one `BendRadius` for each adjacent interior turn: one radius at an end interval and two on an interval between two elbows. Validation rejects routes whose anchor spacing cannot accommodate those tangent setbacks.+For the admitted 90-degree route, a segment's cut length is its corner-to-corner interval minus one `bendRadius` for each adjacent interior turn: one radius at an end interval and two on an interval between two elbows. Validation rejects routes whose anchor spacing cannot accommodate those tangent setbacks.## KeepOut, clearance, and autorouting@@ -99,23 +99,23 @@ An existing structural body is not implicitly routable space: author or generate```firmamentKeepOut Frame {- Min: [400mm,-100mm,-100mm];- Max: [600mm,100mm,100mm];- Concept: StructureMember;+ min: [400mm,-100mm,-100mm];+ max: [600mm,100mm,100mm];+ concept: StructureMember;}-RouteSpace SkidRouting { Clearance: 30mm; }+RouteSpace SkidRouting { clearance: 30mm; }RouteRequest SupplyRequest {- Connection: Supply;- Clearance: 30mm;- BendRadius: 50mm;- HardWaypoints: [];- AcceptAs: SupplyRoute;+ connection: Supply;+ clearance: 30mm;+ bendRadius: 50mm;+ hardWaypoints: [];+ acceptAs: SupplyRoute;}```Forbidden centerline space is the obstacle bound inflated by pipe radius plus required clearance. Candidate search conservatively adds one bend radius to that planning inflation so an elbow torus cannot cut inside an otherwise valid sharp corner; the reported final clearance is then recomputed against the actual trimmed straights and torus centerlines without that extra planning margin. The deterministic router builds coordinates from endpoints, hard waypoints, and inflated obstacle faces, then searches the adjacent 3D coordinate graph with A*. Cost is route length plus a 1000 mm penalty per elbow, so small length savings do not add fittings. Neighbor order and priority tie-breaking are stable. Collinear search points are removed before the proposal is exposed.-`RouteSpace.Clearance` is the system default. `RouteRequest.Clearance`, when present, is the request-local value used for proposal and final verification; current fixtures repeat it deliberately so generated state remains self-evident. `AcceptAs` performs the explicit acceptance step and names the materialized ordinary route. Omit `AcceptAs` to inspect a proposal without adding route geometry. Search neighbor order is `+X, -X, +Y, -Y, +Z, -Z`; exact anchors also depend on port positions/directions, policy radius, bend radius, hard waypoints, and obstacle bounds.+`RouteSpace.clearance` is the system default. `RouteRequest.clearance`, when present, is the request-local value used for proposal and final verification; current fixtures repeat it deliberately so generated state remains self-evident. `acceptAs` performs the explicit acceptance step and names the materialized ordinary route. Omit `acceptAs` to retain a proposal without adding its route geometry when the system also has an explicit or accepted route. A system containing only unaccepted requests rejects normal engineering compilation with `piping-route-required`; proposal-only compilation is not admitted. Search neighbor order is `+X, -X, +Y, -Y, +Z, -Z`; exact anchors also depend on port positions/directions, policy radius, bend radius, hard waypoints, and obstacle bounds.`aetheris inspect source.firmament --json` reports proposals separately from accepted routes. A successful proposal includes anchors, length, elbow count, minimum clearance, cost, and diagnostics. Failures distinguish endpoint direction, hard-waypoint reachability, excessive clearance, disconnection, and lock conflicts.@@ -125,17 +125,17 @@ Forbidden centerline space is the obstacle bound inflated by pipe radius plus re```firmamentLocalReroute AroundMotor {- Route: SupplyRoute;- FromAnchor: 0;- ToAnchor: 2;- Avoid: [Motor];- Clearance: 25mm;+ route: SupplyRoute;+ fromAnchor: 0;+ toAnchor: 2;+ avoid: [Motor];+ clearance: 25mm;}```-The prefix before `FromAnchor` and suffix after `ToAnchor` are copied unchanged. Locks outside the interval are shifted only by the number of replacement anchors; a lock inside the interval fails with `piping-local-reroute-crosses-lock`. The resulting ordinary route has `LocallyRerouted` provenance.+The prefix before `fromAnchor` and suffix after `toAnchor` are copied unchanged. Locks outside the interval are shifted only by the number of replacement anchors; a lock inside the interval fails with `piping-local-reroute-crosses-lock`. The resulting ordinary route has `LocallyRerouted` provenance.-Anchor and segment ordinals are zero-based. The authorized interval includes both boundary anchors but only segments with ordinals `FromAnchor .. ToAnchor-1`; the `ToAnchor` and the segment leaving it begin the preserved suffix. `LocalReroute` updates the named route in place and retains its identity—there is no `AcceptAs` because the operation is already an explicit authored edit. `LocalReroute.Clearance` overrides the RouteSpace default for the replacement interval. All system KeepOuts remain active; `Avoid` adds/names edit-specific obstacles and never disables unlisted KeepOuts.+Anchor and segment ordinals are zero-based. The authorized interval includes both boundary anchors but only segments with ordinals `FromAnchor .. ToAnchor-1`; the `toAnchor` and the segment leaving it begin the preserved suffix. `LocalReroute` updates the named route in place and retains its identity—there is no `acceptAs` because the operation is already an explicit authored edit. `LocalReroute.clearance` overrides the RouteSpace default for the replacement interval. All system KeepOuts remain active; `avoid` adds/names edit-specific obstacles and never disables unlisted KeepOuts.## Build and fabrication output@@ -148,7 +148,7 @@ Build emits an AP242 occurrence assembly plus sibling `.routing.json`, `.cutlist## Bounded support-Supported:+supported:- logical Connections independent of geometry;- stable port Interfaces and endpoint directions;@@ -168,3 +168,30 @@ Not supported:- stress, flow, gravity-slope, or plant-scale optimization.Copy the [autorouted connection fixture](../../../fixtures/Canonical/Piping/autorouted-connection.firmament), [local reroute fixture](../../../fixtures/Canonical/Piping/local-reroute.firmament), or [pump skid fixture](../../../fixtures/Canonical/Piping/pump-skid.firmament) as current examples.++## Frontend admission++`schema Piping` is optional. A conflicting explicit schema rejects; Piping does+not reinterpret another domain's source. The parser route in validation reports is+`UnifiedPiping`, and `valid` has validation level `Built`: validate uses the same+binding, routing, capability and geometry path as build without writing artifacts.+Validate, inspect and build expose structured diagnostics with codes, messages and+source locations. Existing raw diagnostic strings remain on the .NET compilation+result for compatibility.++Lengths accept mm quantities and historical bare numbers interpreted as mm.+Omitting document units retains the historical mm convention; an explicit+conflicting unit rejects.+Direction components are dimensionless. `connectionType` admits `Generic`,+`Flange`, `Weld` and `Threaded`; enum symbols remain case-sensitive. Index lists+must contain valid nonnegative integer segment indices. One optional `RouteSpace`+sets the system default; multiple defaults reject rather than choosing the first.++Direct system children belong to their documented production owners. The existing+Standard catalogue resolves `Use` directives and compile-time catalogue `Let`+aliases; declaring such an alias does not instantiate its product. In particular,+the shipped `tee.firmament` catalogue witness builds its explicitly authored+straight route, not a three-way fitting. Record/Static data and existing compile-+time expansion bind through the shared+domain value owner, including the specialized configuration emitted by Forge.+Unknown or incomplete record fields reject; unsupported declarations still reject.diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex a8a61c81..ad99e126 100644--- a/docs/public/firmament/syntax.md+++ b/docs/public/firmament/syntax.md@@ -128,12 +128,11 @@ remain stable even when their historical capitalization differs from new localstyle. Use `to: Parent` when replacing a relative transform; `to: World`explicitly means the assembly root frame.-Domain property migration is still incomplete. Piping currently needs its-documented `ConnectionType: Weld` spelling: the lowercase alias can silently-default to Generic. This is a known compiler defect, tracked with reproductions-in the [corpus report](../../development/FIRMAMENT-V2-CORPUS-MODERNIZATION-2026-10.md),-and prevents declaring X2 complete. Follow each domain guide for its admitted-properties; this style table does not add aliases to an independent owner.+Piping now binds fields through the shared AST: `connectionType: Weld` and its+historical `ConnectionType: Weld` alias retain the same connection style. Unknown+fields and malformed optional values reject instead of defaulting. Other domain+migrations remain individually qualified; see the [piping guide](piping.md) and+[corpus report](../../development/FIRMAMENT-V2-CORPUS-MODERNIZATION-2026-10.md).### Whitespace, comments and terminators@@ -899,9 +898,11 @@ remain within the selected domain; it cannot change the schema after admission.| `Sweep` | [Circular-section sweeps](sweep.md). || `SectionChain` | [Framed section chains](section-chains.md). || `Garment` | [Panels, stitch interfaces and fitting](garments.md). |+| `Piping` | [Ports, connections and routing](piping.md). |This selector does not list every Firmament root or product domain. Assembly,-Scene, SheetMetal, structural and piping sources have their own entry forms.+Scene, SheetMetal and structural sources have their own entry forms. Piping+uses its documented Model/PipingSystem form, optionally with `schema Piping`.Do not invent `schema Assembly` or wrap arbitrary domain declarations in a Model.| Authoring task | Start here |diff --git a/fixtures/Canonical/Piping/autorouted-connection.firmament b/fixtures/Canonical/Piping/autorouted-connection.firmamentindex 5effc16c..f69b4b55 100644--- a/fixtures/Canonical/Piping/autorouted-connection.firmament+++ b/fixtures/Canonical/Piping/autorouted-connection.firmament@@ -1,12 +1,12 @@Model AutoRouteWitness {units: mmPipingSystem AutoWitness {- PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }- Port Pump { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }- Port Cooler { Position: [1000mm,0mm,0mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }- Connection Supply { From: Pump; To: Cooler; PipePolicy: Pipe25; }- KeepOut Frame { Min: [400mm,-100mm,-100mm]; Max: [600mm,100mm,100mm]; Concept: StructureMember; }- RouteSpace Skid { Clearance: 30mm; }- RouteRequest SupplyRequest { Connection: Supply; Clearance: 30mm; BendRadius: 50mm; HardWaypoints: []; AcceptAs: SupplyRoute; }+ PipePolicy Pipe25 { outerDiameter: 25mm; wallThickness: 2mm; material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Pump { position: [0mm,0mm,0mm]; direction: [1,0,0]; pipePolicy: Pipe25; connectionType: Flange; }+ Port Cooler { position: [1000mm,0mm,0mm]; direction: [-1,0,0]; pipePolicy: Pipe25; connectionType: Flange; }+ Connection Supply { from: Pump; to: Cooler; pipePolicy: Pipe25; }+ KeepOut Frame { min: [400mm,-100mm,-100mm]; max: [600mm,100mm,100mm]; concept: StructureMember; }+ RouteSpace Skid { clearance: 30mm; }+ RouteRequest SupplyRequest { connection: Supply; clearance: 30mm; bendRadius: 50mm; hardWaypoints: []; acceptAs: SupplyRoute; }}}diff --git a/fixtures/Canonical/Piping/elbow90.firmament b/fixtures/Canonical/Piping/elbow90.firmamentindex d1637f81..996f6ceb 100644--- a/fixtures/Canonical/Piping/elbow90.firmament+++ b/fixtures/Canonical/Piping/elbow90.firmament@@ -1,10 +1,10 @@Model Elbow90Witness {units: mmPipingSystem ElbowWitness {- PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }- Port Inlet { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Weld; }- Port Outlet { Position: [300mm,500mm,0mm]; Direction: [0,-1,0]; PipePolicy: Pipe25; ConnectionType: Weld; }- Connection Run { From: Inlet; To: Outlet; PipePolicy: Pipe25; }- Route RunRoute { Connection: Run; Through: [[0mm,0mm,0mm],[300mm,0mm,0mm],[300mm,500mm,0mm]]; BendRadius: 50mm; Provenance: Explicit; }+ PipePolicy Pipe25 { outerDiameter: 25mm; wallThickness: 2mm; material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Inlet { position: [0mm,0mm,0mm]; direction: [1,0,0]; pipePolicy: Pipe25; connectionType: Weld; }+ Port Outlet { position: [300mm,500mm,0mm]; direction: [0,-1,0]; pipePolicy: Pipe25; connectionType: Weld; }+ Connection Run { from: Inlet; to: Outlet; pipePolicy: Pipe25; }+ Route RunRoute { connection: Run; through: [[0mm,0mm,0mm],[300mm,0mm,0mm],[300mm,500mm,0mm]]; bendRadius: 50mm; provenance: Explicit; }}}diff --git a/fixtures/Canonical/Piping/explicit-route.firmament b/fixtures/Canonical/Piping/explicit-route.firmamentindex 5577cd0e..acf6b8a2 100644--- a/fixtures/Canonical/Piping/explicit-route.firmament+++ b/fixtures/Canonical/Piping/explicit-route.firmament@@ -1,10 +1,10 @@Model ExplicitRouteWitness {units: mmPipingSystem ExplicitWitness {- PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }- Port PumpDischarge { Position: [0mm,0mm,100mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }- Port CoolerInlet { Position: [700mm,350mm,100mm]; Direction: [0,-1,0]; PipePolicy: Pipe25; ConnectionType: Flange; }- Connection Supply { From: PumpDischarge; To: CoolerInlet; PipePolicy: Pipe25; Service: "CoolingSupply"; }- Route SupplyRoute { Connection: Supply; Through: [[0mm,0mm,100mm],[400mm,0mm,100mm],[400mm,200mm,100mm],[700mm,200mm,100mm],[700mm,350mm,100mm]]; BendRadius: 50mm; Provenance: Explicit; }+ PipePolicy Pipe25 { outerDiameter: 25mm; wallThickness: 2mm; material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port PumpDischarge { position: [0mm,0mm,100mm]; direction: [1,0,0]; pipePolicy: Pipe25; connectionType: Flange; }+ Port CoolerInlet { position: [700mm,350mm,100mm]; direction: [0,-1,0]; pipePolicy: Pipe25; connectionType: Flange; }+ Connection Supply { from: PumpDischarge; to: CoolerInlet; pipePolicy: Pipe25; service: "CoolingSupply"; }+ Route SupplyRoute { connection: Supply; through: [[0mm,0mm,100mm],[400mm,0mm,100mm],[400mm,200mm,100mm],[700mm,200mm,100mm],[700mm,350mm,100mm]]; bendRadius: 50mm; provenance: Explicit; }}}diff --git a/fixtures/Canonical/Piping/local-reroute.firmament b/fixtures/Canonical/Piping/local-reroute.firmamentindex 0b677b68..9a5ba8f3 100644--- a/fixtures/Canonical/Piping/local-reroute.firmament+++ b/fixtures/Canonical/Piping/local-reroute.firmament@@ -1,13 +1,13 @@Model LocalRerouteWitness {units: mmPipingSystem LocalWitness {- PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }- Port Pump { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }- Port Cooler { Position: [1000mm,300mm,300mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }- Connection Supply { From: Pump; To: Cooler; PipePolicy: Pipe25; }- KeepOut Motor { Min: [250mm,-50mm,-50mm]; Max: [450mm,150mm,150mm]; Concept: EquipmentProxy; }- RouteSpace Skid { Clearance: 25mm; }- Route SupplyRoute { Connection: Supply; Through: [[0mm,0mm,0mm],[500mm,0mm,0mm],[500mm,300mm,0mm],[500mm,300mm,300mm],[1000mm,300mm,300mm]]; BendRadius: 50mm; LockedSegments: [2]; Provenance: AutoGenerated; }- LocalReroute AroundMotor { Route: SupplyRoute; FromAnchor: 0; ToAnchor: 2; Avoid: [Motor]; Clearance: 25mm; }+ PipePolicy Pipe25 { outerDiameter: 25mm; wallThickness: 2mm; material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Pump { position: [0mm,0mm,0mm]; direction: [1,0,0]; pipePolicy: Pipe25; connectionType: Flange; }+ Port Cooler { position: [1000mm,300mm,300mm]; direction: [-1,0,0]; pipePolicy: Pipe25; connectionType: Flange; }+ Connection Supply { from: Pump; to: Cooler; pipePolicy: Pipe25; }+ KeepOut Motor { min: [250mm,-50mm,-50mm]; max: [450mm,150mm,150mm]; concept: EquipmentProxy; }+ RouteSpace Skid { clearance: 25mm; }+ Route SupplyRoute { connection: Supply; through: [[0mm,0mm,0mm],[500mm,0mm,0mm],[500mm,300mm,0mm],[500mm,300mm,300mm],[1000mm,300mm,300mm]]; bendRadius: 50mm; lockedSegments: [2]; provenance: AutoGenerated; }+ LocalReroute AroundMotor { route: SupplyRoute; fromAnchor: 0; toAnchor: 2; avoid: [Motor]; clearance: 25mm; }}}diff --git a/fixtures/Canonical/Piping/pipe-segment.firmament b/fixtures/Canonical/Piping/pipe-segment.firmamentindex b1458ef5..5e5a1ce4 100644--- a/fixtures/Canonical/Piping/pipe-segment.firmament+++ b/fixtures/Canonical/Piping/pipe-segment.firmament@@ -1,10 +1,10 @@Model PipeSegmentWitness {units: mmPipingSystem SegmentWitness {- PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }- Port Inlet { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Weld; }- Port Outlet { Position: [500mm,0mm,0mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Weld; }- Connection Run { From: Inlet; To: Outlet; PipePolicy: Pipe25; Service: "CoolingWater"; }- Route RunRoute { Connection: Run; Through: [[0mm,0mm,0mm],[500mm,0mm,0mm]]; BendRadius: 50mm; Provenance: Explicit; }+ PipePolicy Pipe25 { outerDiameter: 25mm; wallThickness: 2mm; material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Inlet { position: [0mm,0mm,0mm]; direction: [1,0,0]; pipePolicy: Pipe25; connectionType: Weld; }+ Port Outlet { position: [500mm,0mm,0mm]; direction: [-1,0,0]; pipePolicy: Pipe25; connectionType: Weld; }+ Connection Run { from: Inlet; to: Outlet; pipePolicy: Pipe25; service: "CoolingWater"; }+ Route RunRoute { connection: Run; through: [[0mm,0mm,0mm],[500mm,0mm,0mm]]; bendRadius: 50mm; provenance: Explicit; }}}diff --git a/fixtures/Canonical/Piping/pump-skid.firmament b/fixtures/Canonical/Piping/pump-skid.firmamentindex e37f8288..04cb5d69 100644--- a/fixtures/Canonical/Piping/pump-skid.firmament+++ b/fixtures/Canonical/Piping/pump-skid.firmament@@ -1,22 +1,22 @@Model X3PumpCoolingSkid {units: mmPipingSystem CoolingSkid {- PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }- Port PumpDischarge { Position: [100mm,100mm,250mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; Equipment: Pump; NozzleLength: 50mm; }- Port CoolerInlet { Position: [1100mm,500mm,650mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; Equipment: Cooler; NozzleLength: 50mm; }- Port CoolerOutlet { Position: [1100mm,400mm,550mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; Equipment: Cooler; NozzleLength: 50mm; }- Port PumpSuction { Position: [100mm,200mm,150mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; Equipment: Pump; NozzleLength: 50mm; }- Connection Supply { From: PumpDischarge; To: CoolerInlet; PipePolicy: Pipe25; Service: "CoolingSupply"; }- Connection Return { From: CoolerOutlet; To: PumpSuction; PipePolicy: Pipe25; Service: "CoolingReturn"; }- KeepOut FrontRail { Min: [350mm,0mm,0mm]; Max: [390mm,600mm,800mm]; Concept: StructureMember; }- KeepOut BackRail { Min: [700mm,0mm,0mm]; Max: [740mm,600mm,800mm]; Concept: StructureMember; }- KeepOut PumpBody { Min: [0mm,0mm,0mm]; Max: [50mm,300mm,350mm]; Concept: EquipmentProxy; }- KeepOut CoolerBody { Min: [1150mm,300mm,300mm]; Max: [1250mm,600mm,800mm]; Concept: EquipmentProxy; }- Equipment Pump { KeepOut: PumpBody; }- Equipment Cooler { KeepOut: CoolerBody; }- RouteSpace SkidRouting { Clearance: 30mm; }- Route SupplyRoute { Connection: Supply; Through: [[100mm,100mm,250mm],[250mm,100mm,250mm],[250mm,650mm,250mm],[900mm,650mm,250mm],[900mm,650mm,650mm],[900mm,500mm,650mm],[1100mm,500mm,650mm]]; BendRadius: 50mm; LockedSegments: [3]; Provenance: Explicit; }- Route ReturnRoute { Connection: Return; Through: [[1100mm,400mm,550mm],[900mm,400mm,550mm],[900mm,-100mm,550mm],[900mm,-100mm,150mm],[300mm,-100mm,150mm],[300mm,200mm,150mm],[100mm,200mm,150mm]]; BendRadius: 50mm; Provenance: AutoGenerated; }- RouteRequest ReturnProposalWitness { Connection: Return; Clearance: 30mm; BendRadius: 50mm; HardWaypoints: [[900mm,-100mm,550mm]]; }+ PipePolicy Pipe25 { outerDiameter: 25mm; wallThickness: 2mm; material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port PumpDischarge { position: [100mm,100mm,250mm]; direction: [1,0,0]; pipePolicy: Pipe25; connectionType: Flange; equipment: Pump; nozzleLength: 50mm; }+ Port CoolerInlet { position: [1100mm,500mm,650mm]; direction: [-1,0,0]; pipePolicy: Pipe25; connectionType: Flange; equipment: Cooler; nozzleLength: 50mm; }+ Port CoolerOutlet { position: [1100mm,400mm,550mm]; direction: [-1,0,0]; pipePolicy: Pipe25; connectionType: Flange; equipment: Cooler; nozzleLength: 50mm; }+ Port PumpSuction { position: [100mm,200mm,150mm]; direction: [1,0,0]; pipePolicy: Pipe25; connectionType: Flange; equipment: Pump; nozzleLength: 50mm; }+ Connection Supply { from: PumpDischarge; to: CoolerInlet; pipePolicy: Pipe25; service: "CoolingSupply"; }+ Connection Return { from: CoolerOutlet; to: PumpSuction; pipePolicy: Pipe25; service: "CoolingReturn"; }+ KeepOut FrontRail { min: [350mm,0mm,0mm]; max: [390mm,600mm,800mm]; concept: StructureMember; }+ KeepOut BackRail { min: [700mm,0mm,0mm]; max: [740mm,600mm,800mm]; concept: StructureMember; }+ KeepOut PumpBody { min: [0mm,0mm,0mm]; max: [50mm,300mm,350mm]; concept: EquipmentProxy; }+ KeepOut CoolerBody { min: [1150mm,300mm,300mm]; max: [1250mm,600mm,800mm]; concept: EquipmentProxy; }+ Equipment Pump { keepOut: PumpBody; }+ Equipment Cooler { keepOut: CoolerBody; }+ RouteSpace SkidRouting { clearance: 30mm; }+ Route SupplyRoute { connection: Supply; through: [[100mm,100mm,250mm],[250mm,100mm,250mm],[250mm,650mm,250mm],[900mm,650mm,250mm],[900mm,650mm,650mm],[900mm,500mm,650mm],[1100mm,500mm,650mm]]; bendRadius: 50mm; lockedSegments: [3]; provenance: Explicit; }+ Route ReturnRoute { connection: Return; through: [[1100mm,400mm,550mm],[900mm,400mm,550mm],[900mm,-100mm,550mm],[900mm,-100mm,150mm],[300mm,-100mm,150mm],[300mm,200mm,150mm],[100mm,200mm,150mm]]; bendRadius: 50mm; provenance: AutoGenerated; }+ RouteRequest ReturnProposalWitness { connection: Return; clearance: 30mm; bendRadius: 50mm; hardWaypoints: [[900mm,-100mm,550mm]]; }}}diff --git a/fixtures/Canonical/Piping/route-around-keepout.firmament b/fixtures/Canonical/Piping/route-around-keepout.firmamentindex 6b9cf45c..ad25908b 100644--- a/fixtures/Canonical/Piping/route-around-keepout.firmament+++ b/fixtures/Canonical/Piping/route-around-keepout.firmament@@ -1,12 +1,12 @@Model RouteAroundKeepOut {units: mmPipingSystem KeepOutWitness {- PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }- Port Pump { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }- Port Cooler { Position: [1000mm,0mm,0mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }- Connection Supply { From: Pump; To: Cooler; PipePolicy: Pipe25; }- KeepOut Frame { Min: [400mm,-100mm,-100mm]; Max: [600mm,100mm,100mm]; Concept: StructureMember; }- RouteSpace Skid { Clearance: 30mm; }- Route SupplyRoute { Connection: Supply; Through: [[0mm,0mm,0mm],[300mm,0mm,0mm],[300mm,200mm,0mm],[700mm,200mm,0mm],[700mm,0mm,0mm],[1000mm,0mm,0mm]]; BendRadius: 50mm; Provenance: Explicit; }+ PipePolicy Pipe25 { outerDiameter: 25mm; wallThickness: 2mm; material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Pump { position: [0mm,0mm,0mm]; direction: [1,0,0]; pipePolicy: Pipe25; connectionType: Flange; }+ Port Cooler { position: [1000mm,0mm,0mm]; direction: [-1,0,0]; pipePolicy: Pipe25; connectionType: Flange; }+ Connection Supply { from: Pump; to: Cooler; pipePolicy: Pipe25; }+ KeepOut Frame { min: [400mm,-100mm,-100mm]; max: [600mm,100mm,100mm]; concept: StructureMember; }+ RouteSpace Skid { clearance: 30mm; }+ Route SupplyRoute { connection: Supply; through: [[0mm,0mm,0mm],[300mm,0mm,0mm],[300mm,200mm,0mm],[700mm,200mm,0mm],[700mm,0mm,0mm],[1000mm,0mm,0mm]]; bendRadius: 50mm; provenance: Explicit; }}}diff --git a/fixtures/Canonical/Piping/tee.firmament b/fixtures/Canonical/Piping/tee.firmamentindex 39419b53..bd2de29e 100644--- a/fixtures/Canonical/Piping/tee.firmament+++ b/fixtures/Canonical/Piping/tee.firmament@@ -4,10 +4,10 @@ Model StandardTeeWitness {Let TeeProduct = Standard.Piping.TeeLet TeePolicy = Standard.Piping.TeePolicyPipingSystem TeeLibraryWitness {- PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }- Port Inlet { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Weld; }- Port Outlet { Position: [300mm,0mm,0mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Weld; }- Connection Run { From: Inlet; To: Outlet; PipePolicy: Pipe25; Service: "TeeLibraryWitness"; }- Route RunRoute { Connection: Run; Through: [[0mm,0mm,0mm],[300mm,0mm,0mm]]; BendRadius: 50mm; Provenance: Explicit; }+ PipePolicy Pipe25 { outerDiameter: 25mm; wallThickness: 2mm; material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Inlet { position: [0mm,0mm,0mm]; direction: [1,0,0]; pipePolicy: Pipe25; connectionType: Weld; }+ Port Outlet { position: [300mm,0mm,0mm]; direction: [-1,0,0]; pipePolicy: Pipe25; connectionType: Weld; }+ Connection Run { from: Inlet; to: Outlet; pipePolicy: Pipe25; service: "TeeLibraryWitness"; }+ Route RunRoute { connection: Run; through: [[0mm,0mm,0mm],[300mm,0mm,0mm]]; bendRadius: 50mm; provenance: Explicit; }}}diff --git a/fixtures/Canonical/README.md b/fixtures/Canonical/README.mdindex bbc03c74..4012e097 100644--- a/fixtures/Canonical/README.md+++ b/fixtures/Canonical/README.md@@ -70,7 +70,7 @@ under `Regression/WireFormSurfaceSupport`, pending normal support admission.| Sculpting | `Aetheris.Modules.Tests` and `Aetheris.CLI.Tests` || FEA and Materials | `Aetheris.FEA.Tests` || Assembly | `Aetheris.Kernel.Firmament.Tests` assembly suite |-| Piping | `PipingX3Tests` |+| Piping | `PipingX3Tests`, `PipingAstAdmissionTests`, `PipingAdmissionCliTests` (shared AST fields, compatibility and validate/build agreement) || Drawings | `Aetheris.CLI.Tests` drawing suite |The compact action map is `qualification.json`; `coverage.json` is the public-operation guard. Generated outputs go to `artifacts/local/`, never beside these sources.diff --git a/fixtures/Compatibility/FirmamentV2/Piping/README.md b/fixtures/Compatibility/FirmamentV2/Piping/README.mdnew file mode 100644index 00000000..797665e3--- /dev/null+++ b/fixtures/Compatibility/FirmamentV2/Piping/README.md@@ -0,0 +1,13 @@+# Piping field spelling compatibility++These eight sources preserve the pre-migration canonical files byte-for-byte+from revision `9de80654`. Current cookbook versions live under+`fixtures/Canonical/Piping/` and use camelCase fields.++`PipingAstAdmissionTests` compiles each original/current pair through the same+production owner and checks exact STEP, ports, equipment identities, routing,+BOM, cut lists and bounds. The normal CLI qualification also compares the new+canonical artifacts against outputs captured before the owner migration.++`tee.firmament` is a catalogue-reference witness with an explicit straight+route. Its catalogue aliases do not request a three-way fitting.diff --git a/fixtures/Compatibility/FirmamentV2/Piping/autorouted-connection.firmament b/fixtures/Compatibility/FirmamentV2/Piping/autorouted-connection.firmamentnew file mode 100644index 00000000..5effc16c--- /dev/null+++ b/fixtures/Compatibility/FirmamentV2/Piping/autorouted-connection.firmament@@ -0,0 +1,12 @@+Model AutoRouteWitness {+ units: mm+ PipingSystem AutoWitness {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Pump { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Port Cooler { Position: [1000mm,0mm,0mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Connection Supply { From: Pump; To: Cooler; PipePolicy: Pipe25; }+ KeepOut Frame { Min: [400mm,-100mm,-100mm]; Max: [600mm,100mm,100mm]; Concept: StructureMember; }+ RouteSpace Skid { Clearance: 30mm; }+ RouteRequest SupplyRequest { Connection: Supply; Clearance: 30mm; BendRadius: 50mm; HardWaypoints: []; AcceptAs: SupplyRoute; }+ }+}diff --git a/fixtures/Compatibility/FirmamentV2/Piping/elbow90.firmament b/fixtures/Compatibility/FirmamentV2/Piping/elbow90.firmamentnew file mode 100644index 00000000..d1637f81--- /dev/null+++ b/fixtures/Compatibility/FirmamentV2/Piping/elbow90.firmament@@ -0,0 +1,10 @@+Model Elbow90Witness {+ units: mm+ PipingSystem ElbowWitness {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Inlet { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Weld; }+ Port Outlet { Position: [300mm,500mm,0mm]; Direction: [0,-1,0]; PipePolicy: Pipe25; ConnectionType: Weld; }+ Connection Run { From: Inlet; To: Outlet; PipePolicy: Pipe25; }+ Route RunRoute { Connection: Run; Through: [[0mm,0mm,0mm],[300mm,0mm,0mm],[300mm,500mm,0mm]]; BendRadius: 50mm; Provenance: Explicit; }+ }+}diff --git a/fixtures/Compatibility/FirmamentV2/Piping/explicit-route.firmament b/fixtures/Compatibility/FirmamentV2/Piping/explicit-route.firmamentnew file mode 100644index 00000000..5577cd0e--- /dev/null+++ b/fixtures/Compatibility/FirmamentV2/Piping/explicit-route.firmament@@ -0,0 +1,10 @@+Model ExplicitRouteWitness {+ units: mm+ PipingSystem ExplicitWitness {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port PumpDischarge { Position: [0mm,0mm,100mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Port CoolerInlet { Position: [700mm,350mm,100mm]; Direction: [0,-1,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Connection Supply { From: PumpDischarge; To: CoolerInlet; PipePolicy: Pipe25; Service: "CoolingSupply"; }+ Route SupplyRoute { Connection: Supply; Through: [[0mm,0mm,100mm],[400mm,0mm,100mm],[400mm,200mm,100mm],[700mm,200mm,100mm],[700mm,350mm,100mm]]; BendRadius: 50mm; Provenance: Explicit; }+ }+}diff --git a/fixtures/Compatibility/FirmamentV2/Piping/local-reroute.firmament b/fixtures/Compatibility/FirmamentV2/Piping/local-reroute.firmamentnew file mode 100644index 00000000..0b677b68--- /dev/null+++ b/fixtures/Compatibility/FirmamentV2/Piping/local-reroute.firmament@@ -0,0 +1,13 @@+Model LocalRerouteWitness {+ units: mm+ PipingSystem LocalWitness {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Pump { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Port Cooler { Position: [1000mm,300mm,300mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Connection Supply { From: Pump; To: Cooler; PipePolicy: Pipe25; }+ KeepOut Motor { Min: [250mm,-50mm,-50mm]; Max: [450mm,150mm,150mm]; Concept: EquipmentProxy; }+ RouteSpace Skid { Clearance: 25mm; }+ Route SupplyRoute { Connection: Supply; Through: [[0mm,0mm,0mm],[500mm,0mm,0mm],[500mm,300mm,0mm],[500mm,300mm,300mm],[1000mm,300mm,300mm]]; BendRadius: 50mm; LockedSegments: [2]; Provenance: AutoGenerated; }+ LocalReroute AroundMotor { Route: SupplyRoute; FromAnchor: 0; ToAnchor: 2; Avoid: [Motor]; Clearance: 25mm; }+ }+}diff --git a/fixtures/Compatibility/FirmamentV2/Piping/pipe-segment.firmament b/fixtures/Compatibility/FirmamentV2/Piping/pipe-segment.firmamentnew file mode 100644index 00000000..b1458ef5--- /dev/null+++ b/fixtures/Compatibility/FirmamentV2/Piping/pipe-segment.firmament@@ -0,0 +1,10 @@+Model PipeSegmentWitness {+ units: mm+ PipingSystem SegmentWitness {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Inlet { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Weld; }+ Port Outlet { Position: [500mm,0mm,0mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Weld; }+ Connection Run { From: Inlet; To: Outlet; PipePolicy: Pipe25; Service: "CoolingWater"; }+ Route RunRoute { Connection: Run; Through: [[0mm,0mm,0mm],[500mm,0mm,0mm]]; BendRadius: 50mm; Provenance: Explicit; }+ }+}diff --git a/fixtures/Compatibility/FirmamentV2/Piping/pump-skid.firmament b/fixtures/Compatibility/FirmamentV2/Piping/pump-skid.firmamentnew file mode 100644index 00000000..e37f8288--- /dev/null+++ b/fixtures/Compatibility/FirmamentV2/Piping/pump-skid.firmament@@ -0,0 +1,22 @@+Model X3PumpCoolingSkid {+ units: mm+ PipingSystem CoolingSkid {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port PumpDischarge { Position: [100mm,100mm,250mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; Equipment: Pump; NozzleLength: 50mm; }+ Port CoolerInlet { Position: [1100mm,500mm,650mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; Equipment: Cooler; NozzleLength: 50mm; }+ Port CoolerOutlet { Position: [1100mm,400mm,550mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; Equipment: Cooler; NozzleLength: 50mm; }+ Port PumpSuction { Position: [100mm,200mm,150mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; Equipment: Pump; NozzleLength: 50mm; }+ Connection Supply { From: PumpDischarge; To: CoolerInlet; PipePolicy: Pipe25; Service: "CoolingSupply"; }+ Connection Return { From: CoolerOutlet; To: PumpSuction; PipePolicy: Pipe25; Service: "CoolingReturn"; }+ KeepOut FrontRail { Min: [350mm,0mm,0mm]; Max: [390mm,600mm,800mm]; Concept: StructureMember; }+ KeepOut BackRail { Min: [700mm,0mm,0mm]; Max: [740mm,600mm,800mm]; Concept: StructureMember; }+ KeepOut PumpBody { Min: [0mm,0mm,0mm]; Max: [50mm,300mm,350mm]; Concept: EquipmentProxy; }+ KeepOut CoolerBody { Min: [1150mm,300mm,300mm]; Max: [1250mm,600mm,800mm]; Concept: EquipmentProxy; }+ Equipment Pump { KeepOut: PumpBody; }+ Equipment Cooler { KeepOut: CoolerBody; }+ RouteSpace SkidRouting { Clearance: 30mm; }+ Route SupplyRoute { Connection: Supply; Through: [[100mm,100mm,250mm],[250mm,100mm,250mm],[250mm,650mm,250mm],[900mm,650mm,250mm],[900mm,650mm,650mm],[900mm,500mm,650mm],[1100mm,500mm,650mm]]; BendRadius: 50mm; LockedSegments: [3]; Provenance: Explicit; }+ Route ReturnRoute { Connection: Return; Through: [[1100mm,400mm,550mm],[900mm,400mm,550mm],[900mm,-100mm,550mm],[900mm,-100mm,150mm],[300mm,-100mm,150mm],[300mm,200mm,150mm],[100mm,200mm,150mm]]; BendRadius: 50mm; Provenance: AutoGenerated; }+ RouteRequest ReturnProposalWitness { Connection: Return; Clearance: 30mm; BendRadius: 50mm; HardWaypoints: [[900mm,-100mm,550mm]]; }+ }+}diff --git a/fixtures/Compatibility/FirmamentV2/Piping/route-around-keepout.firmament b/fixtures/Compatibility/FirmamentV2/Piping/route-around-keepout.firmamentnew file mode 100644index 00000000..6b9cf45c--- /dev/null+++ b/fixtures/Compatibility/FirmamentV2/Piping/route-around-keepout.firmament@@ -0,0 +1,12 @@+Model RouteAroundKeepOut {+ units: mm+ PipingSystem KeepOutWitness {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Pump { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Port Cooler { Position: [1000mm,0mm,0mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Flange; }+ Connection Supply { From: Pump; To: Cooler; PipePolicy: Pipe25; }+ KeepOut Frame { Min: [400mm,-100mm,-100mm]; Max: [600mm,100mm,100mm]; Concept: StructureMember; }+ RouteSpace Skid { Clearance: 30mm; }+ Route SupplyRoute { Connection: Supply; Through: [[0mm,0mm,0mm],[300mm,0mm,0mm],[300mm,200mm,0mm],[700mm,200mm,0mm],[700mm,0mm,0mm],[1000mm,0mm,0mm]]; BendRadius: 50mm; Provenance: Explicit; }+ }+}diff --git a/fixtures/Compatibility/FirmamentV2/Piping/tee.firmament b/fixtures/Compatibility/FirmamentV2/Piping/tee.firmamentnew file mode 100644index 00000000..39419b53--- /dev/null+++ b/fixtures/Compatibility/FirmamentV2/Piping/tee.firmament@@ -0,0 +1,13 @@+Use Standard.Piping+Model StandardTeeWitness {+ units: mm+ Let TeeProduct = Standard.Piping.Tee+ Let TeePolicy = Standard.Piping.TeePolicy+ PipingSystem TeeLibraryWitness {+ PipePolicy Pipe25 { OuterDiameter: 25mm; WallThickness: 2mm; Material: "Standard.Materials.StainlessSteel.304_Annealed"; }+ Port Inlet { Position: [0mm,0mm,0mm]; Direction: [1,0,0]; PipePolicy: Pipe25; ConnectionType: Weld; }+ Port Outlet { Position: [300mm,0mm,0mm]; Direction: [-1,0,0]; PipePolicy: Pipe25; ConnectionType: Weld; }+ Connection Run { From: Inlet; To: Outlet; PipePolicy: Pipe25; Service: "TeeLibraryWitness"; }+ Route RunRoute { Connection: Run; Through: [[0mm,0mm,0mm],[300mm,0mm,0mm]]; BendRadius: 50mm; Provenance: Explicit; }+ }+}diff --git a/fixtures/Regression/FrontendX2/piping-field-unknown.pending.firmament b/fixtures/Invalid/Piping/unknown-port-field.firmamentsimilarity index 100%rename from fixtures/Regression/FrontendX2/piping-field-unknown.pending.firmamentrename to fixtures/Invalid/Piping/unknown-port-field.firmamentdiff --git a/fixtures/Regression/FrontendX2/README.md b/fixtures/Regression/FrontendX2/README.mdindex 64ed393a..5af38e23 100644--- a/fixtures/Regression/FrontendX2/README.md+++ b/fixtures/Regression/FrontendX2/README.md@@ -13,8 +13,8 @@| `sibling-data.invalid.firmament` | Rejected: the sibling Static secret is invisible; validate/build reject at its authored reference. || `panel-radians.firmament` | Existing radian-valued Panel arc admission retains exact sampled surface coordinates. Normal solid STEP export still reports its existing panel-only capability limitation. || `traceloop-rect2.firmament` | Accepted: original source formerly mislabeled as an invalid non-loop. A Rect2 is a closed boundary and TraceLoop is now supported. The Invalid/Pipeline witness now uses an actual open Line2. |-| `piping-field-casing.pending.firmament` | Known defect: validate/build accept, but inspection reports Generic for requested lowercase `connectionType: Weld`. Not qualified as correct behavior. |-| `piping-field-unknown.pending.firmament` | Known defect: an unknown optional Port field is ignored. It must reject after Piping's owning field reader migrates to AST consumption. |+| `piping-field-casing.firmament` | Accepted: the original lowercase witness binds Weld on both ports and retains exact canonical STEP geometry. |+| `../../Invalid/Piping/unknown-port-field.firmament` | Rejected: the original unknown-field witness now fails validate, inspect and build at unexpectedIntent, with no STEP output. |The component tests compare accepted geometry to concrete/renamed equivalents,check generated identities, and retain source-located private-name rejection explicitly.diff --git a/fixtures/Regression/FrontendX2/piping-field-casing.pending.firmament b/fixtures/Regression/FrontendX2/piping-field-casing.firmamentsimilarity index 100%rename from fixtures/Regression/FrontendX2/piping-field-casing.pending.firmamentrename to fixtures/Regression/FrontendX2/piping-field-casing.firmamentdiff --git a/scripts/Clear-FirmamentCorpusIntermediates.ps1 b/scripts/Clear-FirmamentCorpusIntermediates.ps1new file mode 100644index 00000000..6bdd42f4--- /dev/null+++ b/scripts/Clear-FirmamentCorpusIntermediates.ps1@@ -0,0 +1,70 @@+<#+.SYNOPSIS+Previews obsolete intermediate output from the October 2026 corpus pass.+.DESCRIPTION+Only the fixed paths below are eligible. Final qualification outputs, reports,+source, fixtures and baseline evidence are retained. Review without arguments;+use -Apply to remove the listed intermediates, or -Apply -WhatIf to preview+PowerShell's deletion operations. This script does not stop runtime processes.+#>+[CmdletBinding(SupportsShouldProcess = $true)]+param([switch]$Apply)++$ErrorActionPreference = 'Stop'+$repoRoot = [IO.Path]::GetFullPath((Split-Path $PSScriptRoot -Parent))+if (-not (Test-Path -LiteralPath (Join-Path $repoRoot 'Aetheris.slnx') -PathType Leaf)) {+ throw 'Run the checked-in script from its Aetheris scripts directory.'+}+$artifactRoot = [IO.Path]::GetFullPath((Join-Path $repoRoot 'artifacts/local/corpus-modernization'))+$prefix = $artifactRoot.TrimEnd([IO.Path]::DirectorySeparatorChar) + [IO.Path]::DirectorySeparatorChar+$relativeTargets = @(+ 'after',+ 'after-structural',+ 'accepted-canonical',+ 'editor/bin',+ 'editor/obj',+ 'baseline-structural/entries.jsonl',+ 'accepted-structural/entries.jsonl'+)++# Resolve and check every target before the first deletion. Reject junctions and+# symlinks both above and within a target, so recursion cannot escape the workspace.+$targets = foreach ($relative in $relativeTargets) {+ $target = [IO.Path]::GetFullPath((Join-Path $artifactRoot $relative))+ if (-not $target.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) {+ throw "Target escapes the intended artifact directory: $target"+ }+ $ancestor = $target+ while ($ancestor) {+ if (Test-Path -LiteralPath $ancestor) {+ $item = Get-Item -LiteralPath $ancestor -Force+ if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) {+ throw "Refusing a reparse point in target ancestry: $ancestor"+ }+ }+ $ancestor = Split-Path $ancestor -Parent+ }+ if (-not (Test-Path -LiteralPath $target)) { continue }+ $item = Get-Item -LiteralPath $target -Force+ $children = if ($item.PSIsContainer) { @(Get-ChildItem -LiteralPath $target -Recurse -Force) } else { @($item) }+ if ($children | Where-Object { $_.Attributes -band [IO.FileAttributes]::ReparsePoint }) {+ throw "Refusing target containing a junction or symlink: $target"+ }+ [pscustomobject]@{+ Path = $target+ Bytes = [long](($children | Where-Object { -not $_.PSIsContainer } | Measure-Object Length -Sum).Sum)+ Directory = $item.PSIsContainer+ }+}+$targets | Format-Table Path, Bytes -AutoSize+$total = ($targets | Measure-Object Bytes -Sum).Sum+Write-Output ("Eligible intermediates: {0}; size: {1:N1} MiB" -f @($targets).Count, ($total / 1MB))+if (-not $Apply) {+ Write-Output 'Preview only. Review the fixed list, then run with -Apply to delete it.'+ return+}+foreach ($target in $targets) {+ if ($PSCmdlet.ShouldProcess($target.Path, 'Delete obsolete corpus intermediate')) {+ Remove-Item -LiteralPath $target.Path -Recurse:$target.Directory -Force+ }+}