Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Support oriented Firmament profile layouts

Yuechen Li99aa452bdf19
diff --git a/Aetheris.CLI.Tests/FirmamentFrontendX0CliTests.cs b/Aetheris.CLI.Tests/FirmamentFrontendX0CliTests.cs
index b00be0da..b942e454 100644
--- a/Aetheris.CLI.Tests/FirmamentFrontendX0CliTests.cs
+++ b/Aetheris.CLI.Tests/FirmamentFrontendX0CliTests.cs
@@ -11,7 +11,7 @@ public sealed class FirmamentFrontendX0CliTests
[InlineData("unknown-box-field")]
[InlineData("unknown-compose-statement")]
[InlineData("unknown-boundary-field")]
- [InlineData("unsupported-xz-layout")]
+ [InlineData("unsupported-layout-frame")]
[InlineData("combined-fillet-hole-intersection")]
[InlineData("unresolved-semantic-source")]
[InlineData("edgefinish-generic-variant")]
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX0Tests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX0Tests.cs
index 413e2885..66618be2 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX0Tests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX0Tests.cs
@@ -12,7 +12,7 @@ public sealed class FirmamentFrontendX0Tests
[InlineData("unknown-model-statement", "UnifiedMechanical")]
[InlineData("unknown-modify-statement", "UnifiedMechanical")]
[InlineData("unknown-box-field", "UnifiedMechanical")]
- [InlineData("unsupported-xz-layout", "UnifiedMechanical")]
+ [InlineData("unsupported-layout-frame", "UnifiedMechanical")]
public void InvalidSource_IsRejectedByParserReportAndEngineeringCompiler(string fixture, string route)
{
var source = Read(fixture);
@@ -62,7 +62,12 @@ public sealed class FirmamentFrontendX0Tests
Assert.Equal(30d, points.Max(point => point.Y) - points.Min(point => point.Y), 8);
Assert.Equal(3d, points.Max(point => point.Z) - points.Min(point => point.Z), 8);
Assert.Equal(8, imported.Value.Topology.Faces.Count());
- Assert.False(FirmamentBuildAndExport.CompileSource(xz).IsSuccess);
+ var oriented = FirmamentBuildAndExport.CompileSource(xz);
+ Assert.True(oriented.IsSuccess, string.Join("; ", oriented.Diagnostics.Select(d => d.Message)));
+ var measured = new Analysis.FirmamentMeasurements(oriented.Value);
+ Assert.Equal([0d, -3, 0], measured.Bounds!.MinimumMm);
+ Assert.Equal([60d, 0, 30], measured.Bounds.MaximumMm);
+ Assert.Equal(imported.Value.Topology.Faces.Count(), Step242Importer.ImportBody(oriented.Value.StepText).Value.Topology.Faces.Count());
Assert.False(FirmamentBuildAndExport.CompileSource(xy.Replace("Using Layout", "Using MissingFrame", StringComparison.Ordinal)).IsSuccess);
}
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX1Tests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX1Tests.cs
index c286d28c..ad1fddb4 100644
--- a/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX1Tests.cs
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentFrontendX1Tests.cs
@@ -181,13 +181,15 @@ public sealed class FirmamentFrontendX1Tests
}
[Fact]
- public void UnsupportedFrame_IsRetainedAsAuthoredBeforeSemanticRejection()
+ public void PrincipalFrame_IsRetainedAsAuthoredAndAdmittedWithItsOrientation()
{
var source = File.ReadAllText(Root("fixtures/Regression/FrontendX0/unsupported-xz-layout.firmament"));
var declaration = Assert.Single(FirmamentSyntaxEvidence.Declarations(Parse(source).Document), d => d.Name?.Text == "Layout");
var frame = Assert.IsType<ReferenceSyntax>(Assert.Single(declaration.Clauses).Value);
Assert.Equal("XZ", frame.Name.Text);
- Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ var built = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));
+ Assert.Equal([60d, 0, 30], new Analysis.FirmamentMeasurements(built.Value).Bounds!.MaximumMm);
}
[Fact]
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentSketchTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentSketchTests.cs
new file mode 100644
index 00000000..2f7ab35c
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentSketchTests.cs
@@ -0,0 +1,255 @@
+using Aetheris.Kernel.Firmament.FirmamentV2;
+using Aetheris.Kernel.Firmament.Analysis;
+using Aetheris.Kernel.Core.Brep.Verification;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public class FirmamentSketchTests
+{
+ private static string Fixture(string name) => File.ReadAllText(Path.Combine(Root(), "fixtures", "Regression", "Sketcher", name));
+ private static string Root()
+ {
+ for (var directory = new DirectoryInfo(AppContext.BaseDirectory); directory is not null; directory = directory.Parent)
+ if (Directory.Exists(Path.Combine(directory.FullName, "fixtures"))) return directory.FullName;
+ throw new DirectoryNotFoundException("Repository fixtures are required.");
+ }
+
+ [Fact]
+ public void ProfileProjectionAndParameterEditKeepFourOpeningsAndExpressions()
+ {
+ var source = Fixture("plate.firmament");
+ var view = FirmamentSketchService.Project(source, "plate.firmament", "7");
+ Assert.Empty(view.Diagnostics);
+ Assert.Equal("ProfileResolvedNotBuilt", view.ValidationLevel);
+ Assert.Equal(5, view.Loops.Count);
+ Assert.Equal(5, view.Shapes.Count);
+ var width = view.Shapes.Single(s => s.Name == "Outline").Controls.Single(c => c.Label == "Width");
+ Assert.Equal("Width", width.Parameter);
+ Assert.True(width.Editable);
+ Assert.False(view.Shapes.Single(s => s.Name == "MountA").Controls.Single(c => c.Label == "Center X").Editable);
+ var edited = FirmamentSketchService.Edit(source, "plate.firmament", "7", new("dimensions", view.Node,
+ Changes: [new(width.Id, 100)]));
+ Assert.Contains("Static Width: Length = 100mm", edited.Text);
+ Assert.Contains("size: [Width, Height]", edited.Text);
+ Assert.Contains("center: [Width / 2 - 8mm", edited.Text);
+ var after = FirmamentSketchService.Project(edited.Text, "plate.firmament", "8");
+ Assert.Empty(after.Diagnostics);
+ Assert.Equal(5, after.Loops.Count);
+ Assert.Equal(42, after.Shapes.Single(s => s.Name == "MountB").Center[0], 8);
+ Assert.Equal(view.Loops.SelectMany(l => l.Curves).Select(c => c.Id), after.Loops.SelectMany(l => l.Curves).Select(c => c.Id));
+ var built = FirmamentBuildAndExport.CompileSource(edited.Text);
+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));
+ var measured = new FirmamentMeasurements(built.Value);
+ Assert.Equal([-50d, -25, 0], measured.Bounds!.MinimumMm);
+ Assert.Equal([50d, 25, 6], measured.Bounds.MaximumMm);
+ }
+
+ [Fact]
+ public void FourOpeningWorkflowNamesDrivingValuesAndRetainsGeometryThroughResize()
+ {
+ var source = FirmamentSketchService.Edit("Model Plate { units: mm }", "p.firmament", "0", new("create", "Plate", "Rect2")).Text;
+ var view = FirmamentSketchService.Project(source, "p.firmament", "1");
+ var reference = Assert.Single(view.OpeningReferences);
+ foreach (var anchor in new[] { "BottomLeft", "BottomRight", "TopRight", "TopLeft" })
+ {
+ source = FirmamentSketchService.Edit(source, "p.firmament", "1", new("opening", view.Node,
+ X: 8, Y: 8, Reference: reference.Id, Anchor: anchor)).Text;
+ view = FirmamentSketchService.Project(source, "p.firmament", "1");
+ }
+ Assert.Equal(5, view.Loops.Count);
+ Assert.Equal(4, view.Shapes.Count(s => s.Kind == "Circle2"));
+ var width = view.Shapes.Single(s => s.Kind == "Rect2").Controls.Single(c => c.Label == "Width");
+ Assert.Equal("OutlineWidth", width.Parameter);
+ var before = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(before.IsSuccess, string.Join("; ", before.Diagnostics.Select(d => d.Message)));
+ var beforeVolume = new FirmamentMeasurements(before.Value).Volume().ValueMm3;
+ var resized = FirmamentSketchService.Edit(source, "p.firmament", "1", new("dimensions", view.Node, Changes: [new(width.Id, 100)])).Text;
+ var built = FirmamentBuildAndExport.CompileSource(resized);
+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));
+ var measured = new FirmamentMeasurements(built.Value);
+ Assert.NotNull(beforeVolume);
+ Assert.Equal(beforeVolume.Value + 20 * 50 * 6, measured.Volume().ValueMm3!.Value, 5);
+ var after = FirmamentSketchService.Project(resized, "p.firmament", "2");
+ Assert.All(after.Shapes.Where(s => s.Kind == "Circle2"), s => Assert.Equal(42, Math.Abs(s.Center[0]), 8));
+ Assert.Equal(before.Value.StepText, FirmamentBuildAndExport.CompileSource(source).Value.StepText);
+ Assert.Throws<FirmamentLanguageEditException>(() => FirmamentSketchService.Edit(resized, "p.firmament", "2",
+ new("opening", after.Node, X: 8, Y: 8, Reference: reference.Id, Anchor: "BottomLeft")));
+ var removed = FirmamentLanguageEditService.Apply(resized, "p.firmament", "2", [new("removeDeclaration") { Node = reference.Id }]);
+ Assert.False(FirmamentBuildAndExport.CompileSource(removed.Text).IsSuccess);
+ }
+
+ [Fact]
+ public void TracedFrameIsProjectedAndPreservedByDimensionEditing()
+ {
+ var source = File.ReadAllText(Path.Combine(Root(), "fixtures", "Regression", "Profile", "valid", "construction-plane-positive-x.firmament"));
+ var view = FirmamentSketchService.Project(source, "side.firmament", "1");
+ Assert.Empty(view.Diagnostics);
+ Assert.Equal([1d, 0, 0], view.Frame!.Normal);
+ Assert.Equal([10d, 2, 3], view.Frame.Origin);
+ var width = Assert.Single(view.Shapes).Controls.Single(c => c.Label == "Width");
+ source = FirmamentSketchService.Edit(source, "side.firmament", "1", new("dimensions", view.Node, Changes: [new(width.Id, 30)])).Text;
+ var built = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));
+ var bounds = new FirmamentMeasurements(built.Value).Bounds!;
+ Assert.Equal([5d, -13, -2], bounds.MinimumMm);
+ Assert.Equal([15d, 17, 8], bounds.MaximumMm);
+ }
+
+ [Theory]
+ [InlineData("XY", -15, -5, 0, 15, 5, 6)]
+ [InlineData("XZ", -15, -6, -5, 15, 0, 5)]
+ [InlineData("YZ", 0, -15, -5, 6, 15, 5)]
+ public void PrincipalLayoutFramesHaveExplicitRightHandedWorldGeometry(string plane,
+ double minX, double minY, double minZ, double maxX, double maxY, double maxZ)
+ {
+ var source = $$"""
+ Concept Struct Layout on {{plane}} { Rect2 Outline { center: [0mm, 0mm] size: [30mm, 10mm] } }
+ Profile Section using Layout { Loop Outer { Outline |> TraceLoop } }
+ Struct Part { Extrude Body { profile: Section from: 0mm to: 6mm } }
+ """;
+ var view = FirmamentSketchService.Project(source, "part.firmament", "1");
+ Assert.Empty(view.Diagnostics);
+ var normal = plane switch { "XY" => new[] { 0d, 0, 1 }, "XZ" => [0d, -1, 0], _ => [1d, 0, 0] };
+ Assert.Equal(normal, view.Frame!.Normal);
+ var built = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));
+ var measurement = new FirmamentMeasurements(built.Value);
+ Assert.Equal([minX, minY, minZ], measurement.Bounds!.MinimumMm);
+ Assert.Equal([maxX, maxY, maxZ], measurement.Bounds.MaximumMm);
+ Assert.Equal(1800, measurement.Volume().ValueMm3!.Value, 6);
+ var profile = ProfileAuthoringParser.ResolveNamedProfile(source, "Section", out var diagnostics);
+ Assert.Empty(diagnostics); Assert.Equal(1, profile!.EffectiveConstructionPlane.Determinant, 10);
+ if (plane == "XY") Assert.Equal(built.Value.StepText, FirmamentBuildAndExport.CompileSource(source.Replace(" on XY", "")).Value.StepText);
+ }
+
+ [Theory]
+ [InlineData("XY", -15, -5, 0, 15, 5, 6)]
+ [InlineData("XZ", -15, -6, -5, 15, 0, 5)]
+ [InlineData("YZ", 0, -15, -5, 6, 15, 5)]
+ public void ComposeInheritsItsOperandFrame(string plane,
+ double minX, double minY, double minZ, double maxX, double maxY, double maxZ)
+ {
+ var source = $$"""
+ Concept Struct Layout on {{plane}} { Rect2 Outline { center: [0mm,0mm] size: [30mm,10mm] } }
+ Profile Section using Layout { Loop Outer { Outline |> TraceLoop } }
+ Struct Part { Compose Body { Base Stock { profile: Section from: 0mm to: 6mm } } }
+ """;
+ var built = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));
+ var measured = new FirmamentMeasurements(built.Value);
+ Assert.Equal([minX, minY, minZ], measured.Bounds!.MinimumMm);
+ Assert.Equal([maxX, maxY, maxZ], measured.Bounds.MaximumMm);
+ Assert.Equal(1800, measured.Volume().ValueMm3!.Value, 6);
+ if (plane == "XY") Assert.Equal(built.Value.StepText, FirmamentBuildAndExport.CompileSource(source.Replace(" on XY", "")).Value.StepText);
+ }
+
+ [Fact]
+ public void X4BracketHasAbsoluteXzBoundsForBothFrameSpellings()
+ {
+ foreach (var path in new[] { "f01-xz-layout.firmament", "reference/f01-xz-layout.firmament" })
+ {
+ var source = File.ReadAllText(Path.Combine(Root(), "fixtures", "Regression", "FrontendX4", "cases", path));
+ var built = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));
+ var measured = new FirmamentMeasurements(built.Value);
+ Assert.Equal([0d, -30, 0], measured.Bounds!.MinimumMm);
+ Assert.Equal([60d, 0, 40], measured.Bounds.MaximumMm);
+ var mass = BrepMassProperties.Evaluate(measured.Body);
+ Assert.True(mass.IsEnclosed);
+ Assert.Equal(14250, mass.AbsoluteVolume, 6);
+ }
+ }
+
+ [Fact]
+ public void ComposePreservesTracedOriginAndCommonFrameRemoval()
+ {
+ var source = File.ReadAllText(Path.Combine(Root(), "fixtures", "Regression", "Profile", "valid", "construction-plane-positive-x.firmament"));
+ source = source.Replace("Extrude Solid { Profile: SideProfile; From: -5mm; To: 5mm }", """
+ Profile Cut using PositiveXWorkplane {
+ Rect2 Opening { center: [0mm,0mm] size: [4mm,2mm] }
+ Opening |> TraceLoop
+ }
+ Compose Solid {
+ Base Stock { profile: SideProfile from: -5mm to: 5mm }
+ Remove Opening { profile: Cut from: -5mm to: 5mm }
+ }
+ """);
+ var built = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(built.IsSuccess, string.Join("; ", built.Diagnostics.Select(d => d.Message)));
+ var measured = new FirmamentMeasurements(built.Value);
+ Assert.Equal([5d, -8, -2], measured.Bounds!.MinimumMm);
+ Assert.Equal([15d, 12, 8], measured.Bounds.MaximumMm);
+ var mass = BrepMassProperties.Evaluate(measured.Body);
+ Assert.True(mass.IsEnclosed);
+ Assert.Equal(1920, mass.AbsoluteVolume, 6);
+ }
+
+ [Theory]
+ [InlineData("Remove Cut { profile: Other from: 0mm to: 6mm }", "compose-profile-frame-mismatch")]
+ [InlineData("Placement Override { anchor: [0mm,0mm,0mm] profilePlane: XY axis: +Z referenceDirection: +X }", "compose-profile-frame-mismatch")]
+ [InlineData("Hole<Shaft> Drill { on: +Z center: [0mm,0mm] diameter: 2mm end: ThroughAll }", "compose-oriented-feature-not-admitted")]
+ public void ComposeRejectsConflictingOrUnqualifiedFrameConsumers(string operation, string code)
+ {
+ var source = $$"""
+ Concept Struct Layout on XZ { Rect2 Outline { center: [0mm,0mm] size: [30mm,10mm] } }
+ Profile Section using Layout { Loop Outer { Outline |> TraceLoop } }
+ Profile Other { Rect2 Cut { center: [0mm,0mm] size: [4mm,2mm] } Cut |> TraceLoop }
+ Struct Part { Compose Body { Base Stock { profile: Section from: 0mm to: 6mm } {{operation}} } }
+ """;
+ var built = FirmamentBuildAndExport.CompileSource(source);
+ Assert.False(built.IsSuccess);
+ Assert.Contains(built.Diagnostics, d => d.Message.Contains(code, StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData("Concept Struct Layout on Missing { Rect2 Outline { center: [0mm,0mm] size: [30mm,10mm] } }")]
+ [InlineData("Concept Struct Layout on XZ { Datum: Plane { Origin: [0mm,0mm,0mm] Normal: [0,0,1] } Rect2 Outline { center: [0mm,0mm] size: [30mm,10mm] } }")]
+ public void UnsupportedLayoutIntentNeverFallsBackToXy(string layout)
+ {
+ var source = layout + "\nProfile Section using Layout { Loop Outer { Outline |> TraceLoop } }\nStruct Part { Extrude Body { profile: Section from: 0mm to: 6mm } }";
+ Assert.False(FirmamentBuildAndExport.CompileSource(source).IsSuccess);
+ Assert.Equal("Unresolved", FirmamentSketchService.Project(source, "part.firmament", "1").ValidationLevel);
+ }
+
+ [Fact]
+ public void UnusedUnknownLayoutFrameIsStillRejected()
+ {
+ const string source = "Model Part { units: mm Concept Struct Layout on Missing { Rect2 Guide { center: [0mm,0mm] size: [30mm,10mm] } } Box Body { size: [30mm,10mm,6mm] } }";
+ var result = FirmamentBuildAndExport.CompileSource(source);
+ Assert.False(result.IsSuccess);
+ Assert.Contains(result.Diagnostics, d => d.Message.Contains("profile-layout-placement-unsupported", StringComparison.Ordinal));
+ }
+
+ [Theory]
+ [InlineData("Rect2")]
+ [InlineData("Circle2")]
+ [InlineData("Slot2")]
+ [InlineData("RoundedRect2")]
+ public void CreateProducesAnOrdinaryEditableProfile(string shape)
+ {
+ const string source = "Model NewPart { units: mm }";
+ var edited = FirmamentSketchService.Edit(source, "part.firmament", "0", new("create", "NewPart", shape));
+ var view = FirmamentSketchService.Project(edited.Text, "part.firmament", "1");
+ Assert.Empty(view.Diagnostics);
+ Assert.Single(view.Loops);
+ Assert.Equal(shape, Assert.Single(view.Shapes).Kind);
+ Assert.Empty(view.EmptyModels);
+ var compiled = FirmamentBuildAndExport.CompileSource(edited.Text);
+ Assert.True(compiled.IsSuccess, string.Join("\n", compiled.Diagnostics));
+ }
+
+ [Fact]
+ public void InvalidRadiusAndDrivenCoordinatesAreRefusedWithoutSourceMutation()
+ {
+ var source = FirmamentSketchService.Edit("Model Part { units: mm }", "p.firmament", "0", new("create", "Part", "RoundedRect2")).Text;
+ var view = FirmamentSketchService.Project(source, "p.firmament", "1");
+ var radius = view.Shapes.Single().Controls.Single(c => c.Label.Equals("radius", StringComparison.OrdinalIgnoreCase));
+ Assert.Throws<FirmamentLanguageEditException>(() => FirmamentSketchService.Edit(source, "p.firmament", "1",
+ new("dimensions", view.Node, Changes: [new(radius.Id, 100)])));
+ source = Fixture("plate.firmament");
+ view = FirmamentSketchService.Project(source, "p.firmament", "1");
+ var x = view.Shapes.Single(s => s.Name == "MountA").Controls.Single(c => c.Label == "Center X");
+ Assert.Throws<FirmamentLanguageEditException>(() => FirmamentSketchService.Edit(source, "p.firmament", "1",
+ new("dimensions", view.Node, Changes: [new(x.Id, 0)])));
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.cs
index 4a63ed92..a2e4deef 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.cs
@@ -5,7 +5,7 @@ using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
namespace Aetheris.Kernel.Firmament.FirmamentV2;
/// <summary>One structural edit, addressed by outline node ids (<see cref="FirmamentLanguageOutlineService"/>).
-/// <c>Kind</c> is <c>setField</c>, <c>removeField</c>, <c>insertDeclaration</c>, <c>removeDeclaration</c>,
+/// <c>Kind</c> is <c>setField</c>, <c>setValue</c> (Static initializer), <c>removeField</c>, <c>insertDeclaration</c>, <c>removeDeclaration</c>,
/// <c>renameDeclaration</c>, <c>moveDeclaration</c>, <c>insertFeature</c> <c>extractFeature</c> or <c>nameFeature</c>.
/// <c>removeDeclaration</c> and <c>moveDeclaration</c> also take a call node (a placed Feature).</summary>
public sealed record FirmamentLanguageEditOperation(string Kind)
@@ -77,6 +77,7 @@ public static class FirmamentLanguageEditService
var (next, node) = operation.Kind switch
{
"setField" => SetField(text, before, operation),
+ "setValue" => SetValue(text, before, operation),
"removeField" => RemoveField(text, before, operation),
"insertDeclaration" => InsertDeclaration(text, before, operation),
"removeDeclaration" => RemoveDeclaration(text, before, operation, document, warnings),
@@ -100,6 +101,15 @@ public static class FirmamentLanguageEditService
// ---- Operations -------------------------------------------------------------------------
+ private static (string, string?) SetValue(string text, SyntaxParseResult parse, FirmamentLanguageEditOperation op)
+ {
+ var (id, declaration) = Find(parse, op.Node);
+ if (declaration.Type.Name.Text != "Static" || declaration.Initializer is null || declaration.Body is not null)
+ throw new FirmamentLanguageEditException("edit-value-readonly", "Only an authored Static initializer can be edited as a value.");
+ var value = RequireValue(op.Value, "Value");
+ return (Replace(text, declaration.Initializer.Span.Start, declaration.Initializer.Span.Length, value), id);
+ }
+
private static (string, string?) SetField(string text, SyntaxParseResult parse, FirmamentLanguageEditOperation op)
{
if (FindStatement(parse, op.Node) is { Call: true } placed) return (SetArgument(text, placed, op), placed.Id);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSketch.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSketch.cs
new file mode 100644
index 00000000..b33fc006
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSketch.cs
@@ -0,0 +1,320 @@
+using System.Globalization;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+public sealed record FirmamentSketchChoice(string Id, string Name);
+public sealed record FirmamentSketchControl(string Id, string Label, string Authored, double Value, string Unit,
+ bool Editable, string? Parameter, string? ReadOnlyReason, FirmamentOutlineSpan Span);
+public sealed record FirmamentSketchShape(string Id, string Name, string Kind, double[] Center,
+ IReadOnlyList<FirmamentSketchControl> Controls);
+public sealed record FirmamentSketchCurve(string Id, string Name, string Kind, double[][] Points,
+ double[]? Center = null, double Radius = 0, double StartAngle = 0, double Sweep = 0,
+ double MinorRadius = 0, double Rotation = 0, ProfileSegmentProvenance? Provenance = null);
+public sealed record FirmamentSketchLoop(string Name, bool IsOuter, IReadOnlyList<FirmamentSketchCurve> Curves);
+public sealed record FirmamentSketchFrame(string Name, double[] Origin, double[] X, double[] Y, double[] Normal);
+public sealed record FirmamentSketch(string Version, string Document, string Revision, string? Node,
+ IReadOnlyList<FirmamentSketchChoice> Profiles, IReadOnlyList<FirmamentSketchChoice> EmptyModels,
+ IReadOnlyList<FirmamentSketchChoice> OpeningReferences,
+ FirmamentSketchFrame? Frame, IReadOnlyList<FirmamentSketchLoop> Loops, IReadOnlyList<FirmamentSketchShape> Shapes,
+ IReadOnlyList<FirmamentOutlineDiagnostic> Diagnostics, string ValidationLevel);
+public sealed record FirmamentSketchChange(string Control, double Value);
+public sealed record FirmamentSketchEditRequest(string Kind, string? Node = null, string? Shape = null,
+ IReadOnlyList<FirmamentSketchChange>? Changes = null, double X = 0, double Y = 0,
+ string? Reference = null, string? Anchor = null, double Diameter = 4, double Width = 80, double Height = 50);
+
+/// <summary>Source-owned 2D projection and edits. It reuses domain binding, closed-boundary admission,
+/// Profile resolution and structural transactions. A resolved sketch is deliberately not a built solid.</summary>
+public static class FirmamentSketchService
+{
+ private static readonly HashSet<string> EditableShapes = ["Rect2", "Circle2", "Slot2", "RoundedRect2"];
+ private static readonly IReadOnlySet<string> DomainResults = new HashSet<string>(StringComparer.Ordinal);
+ private sealed record Target(string Node, string? Field, ExpressionSyntax Expression, string? Parameter);
+
+ public static FirmamentSketch Project(string source, string document, string revision, string? node = null)
+ => Read(source, document, revision, node).View;
+
+ private static (FirmamentSketch View, Dictionary<string, Target> Targets) Read(string source, string document, string revision, string? node)
+ {
+ var parsed = FirmamentSyntaxParser.Parse(source, document);
+ var declarations = FirmamentLanguageOutlineService.Declarations(parsed);
+ var outline = FirmamentLanguageOutlineService.Outline(source, document, revision);
+ var profiles = declarations.Where(d => d.Syntax.Type.Name.Text == "Profile" && d.Syntax.Name is not null
+ && !InRecipe(d.Id)).Select(d => new FirmamentSketchChoice(d.Id, d.Syntax.Name!.Text)).ToArray();
+ var empty = declarations.Where(d => d.Syntax.Type.Name.Text == "Model" && d.Syntax.Body is not null
+ && !FirmamentV2Parser.MechanicalDeclarations(d.Syntax.Body.Statements).Any(c => FirmamentV2Parser.IsPrimitiveDeclaration(c)
+ || c.Type.Name.Text is "Extrude" or "Revolve" or "Compose" or "InlineStep" or "Sculpt"))
+ .Select(d => new FirmamentSketchChoice(d.Id, d.Syntax.Name?.Text ?? d.Id)).ToArray();
+ node ??= profiles.FirstOrDefault()?.Id;
+ // A shape node opens the Profile that consumes it; a shared shape needs an explicit Profile choice.
+ if (node is not null && !profiles.Any(p => p.Id == node))
+ {
+ var candidates = profiles.Where(p => Reachable(p.Id).Contains(node)).ToArray();
+ if (candidates.Length == 1) node = candidates[0].Id;
+ }
+ var errors = parsed.Diagnostics.Select(d => Diagnostic(d.Code, d.Message, d.SourceSpan)).ToList();
+ var targets = new Dictionary<string, Target>(StringComparer.Ordinal);
+ FirmamentSketch Result(FirmamentSketchFrame? frame = null, IReadOnlyList<FirmamentSketchLoop>? loops = null,
+ IReadOnlyList<FirmamentSketchShape>? shapes = null) => new("firmament-sketch/1", document, revision, node,
+ profiles, empty, declarations.Where(d => reachableOpening(d.Id, shapes)).Select(d => new FirmamentSketchChoice(d.Id, d.Syntax.Name!.Text)).ToArray(), frame, loops ?? [], shapes ?? [], errors,
+ errors.Count == 0 && frame is not null ? "ProfileResolvedNotBuilt" : "Unresolved");
+ if (node is null) return (Result(), targets);
+ var selected = declarations.FirstOrDefault(d => d.Id == node);
+ if (selected.Syntax?.Type.Name.Text != "Profile")
+ {
+ errors.Add(Diagnostic("sketch-profile-required", "Choose the Profile to edit. A shape may be shared by several Profiles.", selected.Syntax?.Span));
+ return (Result(), targets);
+ }
+ if (profiles.Count(p => p.Name == selected.Syntax.Name!.Text) != 1)
+ {
+ errors.Add(Diagnostic("sketch-profile-ambiguous", "This projection requires a uniquely named Profile; choose a document with one unambiguous authored owner.", selected.Syntax.Span));
+ return (Result(), targets);
+ }
+ if (errors.Count > 0) return (Result(), targets);
+ var binding = new FirmamentDomainBinding(source, document, "Model", DomainResults);
+ errors.AddRange(binding.Diagnostics.Where(d => d.Severity is "error" or "fatal").Select(d => Diagnostic(d.Code, d.Message, d.SourceSpan)));
+ if (errors.Count > 0) return (Result(), targets);
+ var profile = binding.ResolveProfile(selected.Syntax.Name!.Text, out var codes);
+ errors.AddRange(codes.Select(c => Diagnostic(c.Split(':')[0], c, selected.Syntax.Span)));
+ if (profile is null || errors.Count > 0) return (Result(), targets);
+ var reachable = Reachable(node);
+ var shapes = new List<FirmamentSketchShape>();
+ foreach (var item in declarations.Where(d => reachable.Contains(d.Id) && EditableShapes.Contains(d.Syntax.Type.Name.Text) && !InRecipe(d.Id)))
+ {
+ var controls = new List<FirmamentSketchControl>();
+ var center = new double[2];
+ foreach (var field in item.Syntax.Body?.Statements.OfType<FieldSyntax>() ?? [])
+ {
+ var expression = field.Value;
+ var nominal = binding.Nominal(expression);
+ var unit = FirmamentSyntaxFields.SameField(field.Name.Text, "Rotation") ? "deg" : "mm";
+ var parts = Components(expression);
+ var values = Components(nominal);
+ if (parts.Length > 0 && values.Length == parts.Length)
+ {
+ for (var i = 0; i < parts.Length; i++) Add(parts[i], values[i], i);
+ }
+ else Add(expression, nominal, null);
+
+ void Add(ExpressionSyntax authored, ExpressionSyntax effective, int? axis)
+ {
+ if (!FirmamentSyntaxValues.TryMeasure(effective, unit, out var number) || !double.IsFinite(number)) return;
+ var id = item.Id + "/" + field.Name.Text + (axis is null ? "" : "/" + axis);
+ var target = new Target(item.Id, field.Name.Text, authored, null);
+ if (!Literal(authored))
+ {
+ // Only a directly named, literal Static is writable upstream. Arithmetic,
+ // toleranced values and scoped records retain their expression and provenance.
+ var edge = outline.Edges.Where(e => e.From == item.Id && e.Span.Start == authored.Span.Start && !e.Ambiguous).ToArray();
+ if (authored is ReferenceSyntax && edge.Length == 1)
+ {
+ var parameter = declarations.FirstOrDefault(d => d.Id == edge[0].To);
+ if (parameter.Syntax is { Type.Name.Text: "Static", Initializer: { } initial } && Literal(initial))
+ target = new(parameter.Id, null, initial, parameter.Syntax.Name?.Text);
+ }
+ }
+ var editable = Literal(target.Expression);
+ if (editable) targets[id] = target;
+ var label = FieldLabel(field.Name.Text, axis);
+ controls.Add(new(id, label, Slice(source, authored.Span), number, unit, editable, target.Parameter,
+ editable ? null : "Driven by an expression. Edit its inputs in Parameters or Source; dragging will not replace it.",
+ new(authored.Span.Start, authored.Span.Length)));
+ if (FirmamentSyntaxFields.SameField(field.Name.Text, "Center") && axis is 0 or 1) center[axis.Value] = number;
+ }
+ }
+ shapes.Add(new(item.Id, item.Syntax.Name!.Text, item.Syntax.Type.Name.Text, center, controls));
+ }
+ var plane = profile.EffectiveConstructionPlane;
+ return (Result(new(profile.PlaneFrame, [plane.Origin.X, plane.Origin.Y, plane.Origin.Z],
+ [plane.AxisX.X, plane.AxisX.Y, plane.AxisX.Z], [plane.AxisY.X, plane.AxisY.Y, plane.AxisY.Z],
+ [plane.AxisZ.X, plane.AxisZ.Y, plane.AxisZ.Z]),
+ profile.Loops.Select(l => new FirmamentSketchLoop(l.Name, l.IsOuter, l.Segments.Select(Curve).ToArray())).ToArray(), shapes), targets);
+
+ bool InRecipe(string id) => declarations.Any(d => (id == d.Id || id.StartsWith(d.Id + "/", StringComparison.Ordinal))
+ && (d.Syntax.Type.Name.Text is "Template" or "Feature" || d.Syntax.Modifiers.Any(m => m.Name.Text == "Template")));
+ HashSet<string> Reachable(string root)
+ {
+ var found = new HashSet<string>(StringComparer.Ordinal); var queue = new Queue<string>(); queue.Enqueue(root);
+ while (queue.TryDequeue(out var id))
+ {
+ if (!found.Add(id)) continue;
+ foreach (var child in outline.Nodes.FirstOrDefault(n => n.Id == id)?.Children ?? []) queue.Enqueue(child);
+ foreach (var edge in outline.Edges.Where(e => e.From == id && !e.Ambiguous && e.ToDocument is null)) queue.Enqueue(edge.To);
+ }
+ return found;
+ }
+ bool reachableOpening(string id, IReadOnlyList<FirmamentSketchShape>? shapes)
+ {
+ var shape = shapes?.FirstOrDefault(s => s.Id == id && s.Kind == "Rect2");
+ if (shape is null || shape.Controls.Any(c => c.Unit == "deg" && c.Value != 0)) return false;
+ var entry = declarations.Single(d => d.Id == id);
+ return declarations.Any(d => d.Id == entry.ParentId && d.Syntax.Type.Name.Text == "Model")
+ && new[] { "Width", "Height", "Center X", "Center Y" }.All(label => shape.Controls.Any(c => c.Label == label))
+ && declarations.FirstOrDefault(d => d.Id == node).Syntax?.Body is { } body
+ && !body.Statements.OfType<FieldSyntax>().Any(f => FirmamentSyntaxFields.SameField(f.Name.Text, "From"))
+ && outline.Nodes.FirstOrDefault(n => n.ParentId == node && n.Name == "Outer") is { } outer
+ && Reachable(outer.Id).Contains(id);
+ }
+ }
+
+ public static FirmamentLanguageEdit Edit(string source, string document, string revision, FirmamentSketchEditRequest request)
+ {
+ var operations = new List<FirmamentLanguageEditOperation>();
+ if (request.Kind == "create")
+ {
+ var view = Project(source, document, revision);
+ if (!view.EmptyModels.Any(m => m.Id == request.Node)) throw Refuse("sketch-model-occupied", "Choose an empty Model. A new sketch part creates one profile and one extrusion.");
+ if (request.Shape is null || !EditableShapes.Contains(request.Shape)) throw Refuse("sketch-shape-unsupported", "Choose Rectangle, Circle, Slot or Rounded rectangle.");
+ var names = FirmamentLanguageOutlineService.Outline(source, document, revision).Nodes.Select(n => n.Name).ToHashSet();
+ string Fresh(string stem) { var name = stem; for (var i = 2; names.Contains(name); i++) name = stem + i; names.Add(name); return name; }
+ var shape = Fresh("Outline"); var profile = Fresh("Section"); var body = Fresh("Body");
+ if (!double.IsFinite(request.Width) || !double.IsFinite(request.Height) || request.Width <= 0 || request.Height <= 0
+ || !double.IsFinite(request.X) || !double.IsFinite(request.Y)) throw Refuse("sketch-number-invalid", "Use finite positive sizes and a finite center.");
+ var fields = request.Shape switch
+ {
+ "Circle2" => $"diameter: {Length(request.Width)}", "Slot2" => $"length: {Length(request.Width)} width: {Length(request.Height)}",
+ "RoundedRect2" => $"size: [{Length(request.Width)}, {Length(request.Height)}] radius: {Length(Math.Min(request.Width, request.Height) / 8)}",
+ _ => $"size: [{Length(request.Width)}, {Length(request.Height)}]"
+ };
+ operations.Add(new("insertDeclaration") { Parent = request.Node, Source = $"{request.Shape} {shape} {{ center: [{Length(request.X)}, {Length(request.Y)}] {fields} }}" });
+ operations.Add(new("insertDeclaration") { Parent = request.Node, Source = $"Profile {profile} {{ Loop Outer {{ {shape} |> TraceLoop }} }}" });
+ operations.Add(new("insertDeclaration") { Parent = request.Node, Source = $"Extrude {body} {{ profile: {profile} from: 0mm to: 6mm }}" });
+ }
+ else if (request.Kind == "opening")
+ {
+ var view = Project(source, document, revision, request.Node);
+ if (view.ValidationLevel != "ProfileResolvedNotBuilt" || !view.OpeningReferences.Any(r => r.Id == request.Reference))
+ throw Refuse("sketch-opening-reference-unsupported", "An opening requires an unrotated Model-level Rect2 and an explicit-loop Profile. Other reference families are not qualified yet.");
+ if (!double.IsFinite(request.X) || !double.IsFinite(request.Y) || request.X < 0 || request.Y < 0 || !double.IsFinite(request.Diameter) || request.Diameter <= 0)
+ throw Refuse("sketch-opening-size-invalid", "Use finite nonnegative edge insets and a positive opening diameter.");
+ var signs = request.Anchor switch
+ {
+ "BottomLeft" => (-1, -1), "BottomRight" => (1, -1), "TopRight" => (1, 1), "TopLeft" => (-1, 1),
+ "Left" => (-1, 0), "Right" => (1, 0), "Bottom" => (0, -1), "Top" => (0, 1),
+ "Center" => (0, 0), _ => throw Refuse("sketch-anchor-unsupported", "Choose Center, a named corner or an edge midpoint.")
+ };
+ var referenceShape = view.Shapes.Single(s => s.Id == request.Reference);
+ double Dimension(string label) => referenceShape.Controls.Single(c => c.Label == label).Value;
+ var halfWidth = Dimension("Width") / 2; var halfHeight = Dimension("Height") / 2;
+ var px = Dimension("Center X") + signs.Item1 * (halfWidth - request.X);
+ var py = Dimension("Center Y") + signs.Item2 * (halfHeight - request.Y);
+ var radius = request.Diameter / 2;
+ if (Math.Abs(px - Dimension("Center X")) + radius >= halfWidth
+ || Math.Abs(py - Dimension("Center Y")) + radius >= halfHeight)
+ throw Refuse("sketch-opening-outside", "The entire circular opening must lie strictly inside the rectangular outline. Increase the edge inset or reduce its diameter.");
+ foreach (var loop in view.Loops.Where(l => !l.IsOuter))
+ {
+ if (loop.Curves.Count != 1 || loop.Curves[0].Kind != "Circle")
+ throw Refuse("sketch-opening-clearance-unqualified", "Adding an opening beside this noncircular inner loop requires a qualified clearance check; edit it in source.");
+ var circle = loop.Curves[0]; var dx = px - circle.Center![0]; var dy = py - circle.Center[1];
+ if (Math.Sqrt(dx * dx + dy * dy) <= radius + circle.Radius)
+ throw Refuse("sketch-opening-overlap", $"The new opening overlaps or touches '{loop.Name}'. Choose another anchor or inset.");
+ }
+ var declarations = FirmamentLanguageOutlineService.Declarations(FirmamentSyntaxParser.Parse(source));
+ var rectangle = declarations.Single(d => d.Id == request.Reference);
+ var names = declarations.Select(d => d.Syntax.Name?.Text).ToHashSet();
+ string Fresh(string stem) { var name = stem; for (var i = 2; names.Contains(name); i++) name = stem + i; names.Add(name); return name; }
+ var fields = rectangle.Syntax.Body!.Statements.OfType<FieldSyntax>().ToArray();
+ var center = fields.Single(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Center"));
+ var size = fields.Single(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Size"));
+ var c = Components(center.Value); var s = Components(size.Value);
+ if (c.Length != 2 || s.Length != 2) throw Refuse("sketch-reference-expression-unsupported", "This rectangle's center and size need two authored components.");
+ // Share the existing driving expressions by naming them, exactly as the Parameters
+ // sheet does. No sampled edge coordinates or new relation evaluator are persisted.
+ string Parameter(ExpressionSyntax expression, string suffix)
+ {
+ var text = Slice(source, expression.Span);
+ if (expression is ReferenceSyntax) return text;
+ var name = Fresh(rectangle.Syntax.Name!.Text + suffix);
+ operations.Add(new("insertDeclaration") { Parent = rectangle.ParentId, First = true, Source = $"Static {name}: Length = {text}" });
+ return name;
+ }
+ var cx = Parameter(c[0], "CenterX"); var cy = Parameter(c[1], "CenterY");
+ var width = Parameter(s[0], "Width"); var height = Parameter(s[1], "Height");
+ operations.Add(new("setField") { Node = rectangle.Id, Field = center.Name.Text, Value = $"[{cx}, {cy}]" });
+ operations.Add(new("setField") { Node = rectangle.Id, Field = size.Name.Text, Value = $"[{width}, {height}]" });
+ string Position(string origin, string dimension, int sign, double inset) => sign == 0 ? origin
+ : $"{origin} {(sign < 0 ? "-" : "+")} ({dimension} / 2 - {Length(inset)})";
+ var name = Fresh("MountOpening");
+ operations.Add(new("insertDeclaration") { Parent = rectangle.ParentId, Source = $"Circle2 {name} {{ center: [{Position(cx, width, signs.Item1, request.X)}, {Position(cy, height, signs.Item2, request.Y)}] diameter: {Length(request.Diameter)} }}" });
+ operations.Add(new("insertDeclaration") { Parent = view.Node, Source = $"Loop {name} {{ {name} |> TraceLoop }}" });
+ }
+ else if (request.Kind == "dimensions")
+ {
+ var (view, targets) = Read(source, document, revision, request.Node);
+ if (view.ValidationLevel != "ProfileResolvedNotBuilt") throw Refuse("sketch-unresolved", "Resolve the selected profile before editing its dimensions.");
+ var changes = request.Changes ?? [];
+ if (changes.Count == 0 || changes.Select(c => c.Control).Distinct().Count() != changes.Count) throw Refuse("sketch-edit-empty", "Supply unique dimension changes.");
+ var replacements = new Dictionary<(string Node, string? Field), List<(ExpressionSyntax Expression, string Value)>>();
+ foreach (var change in changes)
+ {
+ if (!targets.TryGetValue(change.Control, out var target)) throw Refuse("sketch-dimension-readonly", "The dimension is driven by an expression or is no longer available. Edit its inputs instead.");
+ if (!double.IsFinite(change.Value)) throw Refuse("sketch-number-invalid", "A dimension must be finite.");
+ var control = view.Shapes.SelectMany(s => s.Controls).Single(c => c.Id == change.Control);
+ var key = (target.Node, target.Field);
+ if (!replacements.TryGetValue(key, out var list)) replacements[key] = list = [];
+ var value = change.Value.ToString("R", CultureInfo.InvariantCulture) + control.Unit;
+ if (list.Any(p => p.Expression.Span == target.Expression.Span && p.Value != value))
+ throw Refuse("sketch-shared-parameter-conflict", "These dimensions share a parameter and requested different values. Edit the parameter once.");
+ list.Add((target.Expression, value));
+ }
+ var declarations = FirmamentLanguageOutlineService.Declarations(FirmamentSyntaxParser.Parse(source));
+ foreach (var (key, replacementsForField) in replacements)
+ {
+ var declaration = declarations.Single(d => d.Id == key.Node).Syntax;
+ var value = key.Field is null ? declaration.Initializer! : declaration.Body!.Statements.OfType<FieldSyntax>().Single(f => f.Name.Text == key.Field).Value;
+ var text = Slice(source, value.Span);
+ foreach (var replacement in replacementsForField.Distinct().OrderByDescending(p => p.Expression.Span.Start))
+ text = text.Remove(replacement.Expression.Span.Start - value.Span.Start, replacement.Expression.Span.Length)
+ .Insert(replacement.Expression.Span.Start - value.Span.Start, replacement.Value);
+ operations.Add(new(key.Field is null ? "setValue" : "setField") { Node = key.Node, Field = key.Field, Value = text });
+ }
+ }
+ else throw Refuse("sketch-operation-unsupported", "That sketch operation has not been qualified.");
+ var result = FirmamentLanguageEditService.Apply(source, document, revision, operations);
+ // No silently clamped radii, changed winding or implicit geometry repair. Reuse admission
+ // before returning a source transaction; the caller still performs the full engineering build.
+ var after = Project(result.Text, document, revision, request.Kind == "create" ? result.Nodes[^2] : request.Node);
+ if (after.ValidationLevel != "ProfileResolvedNotBuilt")
+ throw Refuse("sketch-profile-invalid", string.Join("\n", after.Diagnostics.Select(d => d.Message)));
+ return result;
+ }
+
+ private static string FieldLabel(string name, int? axis) => (name.ToLowerInvariant(), axis) switch
+ {
+ ("size", 0) => "Width", ("size", 1) => "Height", ("center", 0) => "Center X", ("center", 1) => "Center Y",
+ ("length", _) => "Overall length", _ => name + (axis is null ? "" : " " + axis)
+ };
+ private static ExpressionSyntax[] Components(ExpressionSyntax expression) => expression switch
+ {
+ SequenceSyntax { Kind: SequenceKind.List } list => list.Items.Select(a => a.Value).ToArray(),
+ CallSyntax { Target: ReferenceSyntax { Name.Text: "Point2" } } call => call.Arguments.Select(a => a.Value).ToArray(),
+ _ => []
+ };
+ private static bool Literal(ExpressionSyntax expression) => expression switch
+ {
+ LiteralSyntax { Kind: LiteralKind.Number } => true,
+ QuantitySyntax { Value: LiteralSyntax { Kind: LiteralKind.Number } } => true,
+ UnarySyntax { Operator: UnaryOperator.Positive or UnaryOperator.Negative } unary => Literal(unary.Operand),
+ _ => false
+ };
+ private static string Slice(string source, FirmamentV2SourceSpan span) => source.Substring(span.Start, span.Length);
+ private static FirmamentOutlineDiagnostic Diagnostic(string code, string message, FirmamentV2SourceSpan? span) => new("error", code, message,
+ span is null ? null : new(span.Start, span.Length));
+ private static FirmamentLanguageEditException Refuse(string code, string message) => new(code, message);
+ private static string Length(double value) => value.ToString("R", CultureInfo.InvariantCulture) + "mm";
+ private static FirmamentSketchCurve Curve(ResolvedProfileSegment2D segment)
+ {
+ static double[] P((double X, double Y) p) => [p.X, p.Y];
+ return segment.Geometry switch
+ {
+ LineArcLineSegment2D line => new(segment.Provenance.StableId, segment.Name, "Line", [P(line.Start), P(line.End)], Provenance: segment.Provenance),
+ LineArcCubicBezier2D cubic => new(segment.Provenance.StableId, segment.Name, "Cubic", [P(cubic.Start), P(cubic.Control1), P(cubic.Control2), P(cubic.End)], Provenance: segment.Provenance),
+ LineArcCircularArc2D arc => new(segment.Provenance.StableId, segment.Name, "Arc", [], P(arc.Center), arc.Radius, arc.StartAngleRadians, arc.SweepAngleRadians, Provenance: segment.Provenance),
+ LineArcFullCircle2D circle => new(segment.Provenance.StableId, segment.Name, "Circle", [], P(circle.Center), circle.Radius, Sweep: 2 * Math.PI, Provenance: segment.Provenance),
+ LineArcFullEllipse2D ellipse => new(segment.Provenance.StableId, segment.Name, "Ellipse", [], P(ellipse.Center), ellipse.MajorRadius, Sweep: 2 * Math.PI, MinorRadius: ellipse.MinorRadius, Rotation: ellipse.RotationRadians, Provenance: segment.Provenance),
+ _ => throw new NotSupportedException($"Sketch projection does not support {segment.Geometry.GetType().Name}.")
+ };
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
index 64686893..388b2f09 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs
@@ -60,7 +60,8 @@ public static partial class FirmamentV2Parser
var declarations = MechanicalDeclarations(model.Body.Statements).ToArray();
// Non-materialized guides are still authored intent. Validate them through
// their ordinary owner even when no Profile happens to consume them.
- diagnostics.AddRange(ProfileAuthoringParser.ValidateConstructionGuides(source));
+ diagnostics.AddRange(ProfileAuthoringParser.ValidateConstructionGuides(source,
+ compileTime is null ? null : compileTime.NominalExpression));
if (diagnostics.Any(IsFatalDiagnosticCode)) return CanonicalFailure(diagnostics, CanonicalDocumentMalformed);
var primitives = declarations.Where(IsPrimitiveDeclaration).ToArray();
var constructions = declarations.Where(d => d.Type.Name.Text is "Compose" or "Extrude").ToArray();
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
index f3cba264..5e409cf4 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
@@ -331,6 +331,9 @@ public static class ProfileAuthoringParser
{
var diagnostics = new List<string>();
AddOrdinaryGuides(source, new(StringComparer.Ordinal), new(StringComparer.Ordinal), diagnostics, applySpans: false,bind:bind);
+ foreach (var layout in SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements)
+ .Where(d => d.Type.Name.Text == "Struct" && d.Modifiers.Any(m => m.Name.Text == "Concept") && d.Clauses.Count > 0 && d.Name is not null))
+ _ = ResolveConstructionPlane(source, layout.Name!.Text, diagnostics);
return diagnostics;
}
@@ -1166,14 +1169,35 @@ public static class ProfileAuthoringParser
if (plane is null)
{
if (frame == "XY") return ConstructionPlane.WorldXY;
- var tokens = FirmamentLanguageAnalysisService.Lex(source).Where(token => token.Shape != "comment").ToArray();
- for (var index = 0; index + 3 < tokens.Length; index++)
+ var layouts = SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements)
+ .Where(d => d.Type.Name.Text == "Struct" && d.Modifiers.Any(m => m.Name.Text == "Concept") && d.Name?.Text == frame).ToArray();
+ if (layouts.Length > 1) { diagnostics.Add($"profile-frame-duplicate:{frame}"); return null; }
+ if (layouts.SingleOrDefault() is { } layout)
{
- if (tokens[index].Text != "Concept" || tokens[index + 1].Text != "Struct" || tokens[index + 2].Text != frame) continue;
- if (tokens[index + 3].Text is not ("On" or "on")) return ConstructionPlane.WorldXY;
- if (index + 4 < tokens.Length && tokens[index + 4].Text == "XY") return ConstructionPlane.WorldXY;
- diagnostics.Add($"profile-layout-placement-unsupported:{frame}:{(index + 4 < tokens.Length ? tokens[index + 4].Text : "missing")}:Concept Struct layouts currently require On XY; use a traced Construction Plane for oriented profiles.");
- return null;
+ if (layout.Clauses.Count == 0) return ConstructionPlane.WorldXY;
+ if (layout.Clauses.Count != 1 || layout.Clauses[0] is not { Kind: ClauseKind.On, Value: ReferenceSyntax placement }
+ || placement.Name.Text is not ("XY" or "XZ" or "YZ"))
+ {
+ diagnostics.Add($"profile-layout-placement-unsupported:{frame}:Use on XY, on XZ or on YZ for a 2D layout; arbitrary orientations use a traced Construction Plane.");
+ return null;
+ }
+ if (placement.Name.Text == "XY") return ConstructionPlane.WorldXY; // Preserve existing XY geometry and identity.
+ // `on` here selects a frame for local 2D guides. It is not a general
+ // transform of explicitly spatial Concept values.
+ var members = layout.Body?.Statements ?? [];
+ if (members.OfType<FieldSyntax>().Any(f => f.Value is not TypedValueSyntax typed
+ || FirmamentSyntaxValues.Reference(typed.Type) is not { } type || !FirmamentV2Parser.TryParseLetType(type, out _))
+ || members.OfType<DeclarationSyntax>().Any(d => !OwnsDeclaration(d) && d.Type.Name.Text != "Static"))
+ {
+ diagnostics.Add($"profile-layout-spatial-members-unsupported:{frame}:This non-XY 2D layout requires local 2D guides and scalar data. Put spatial semantic values in an unplaced Concept Struct and trace a Construction Plane for that workflow.");
+ return null;
+ }
+ var normal = placement.Name.Text == "XZ" ? new ConceptIrVector3(0, -1, 0) : new ConceptIrVector3(1, 0, 0);
+ var concept = new ConceptIrPlaneValue("concept-layout:" + frame, new(0, 0, 0), normal,
+ "ConceptLayoutFrame:" + placement.Name.Text, new(0, 0, 1));
+ if (!ConstructionPlane.TryTrace("construction:layout:" + frame, concept, $"offset:{layout.Span.Start}", out var layoutPlane, out var diagnostic))
+ diagnostics.Add(diagnostic ?? "ConstructionPlaneFrameInvalid");
+ return layoutPlane;
}
diagnostics.Add($"profile-frame-unresolved:{frame}:using must name a declared Concept Struct or Construction Plane.");
return null;
diff --git a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
index 98347168..448f5c1c 100644
--- a/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
+++ b/Aetheris.Kernel.Firmament/Materializer/PrismaticProfileComposition.cs
@@ -78,6 +78,9 @@ public sealed record PrismaticProfilePlacement(
string Name, double AnchorX, double AnchorY, double AnchorZ,
string ProfilePlane, string Axis, string ReferenceDirection, bool IsExplicit)
{
+ /// <summary>The bound operand frame, when placement is inherited from a Profile.</summary>
+ public ConstructionPlane? ProfileConstructionPlane { get; init; }
+
/// <summary>
/// Resolves the legacy textual placement through the shared construction-plane
/// authority. ReferenceDirection is the local profile X axis; local Y is derived
@@ -87,6 +90,11 @@ public sealed record PrismaticProfilePlacement(
{
frame = null;
diagnostic = null;
+ if (ProfileConstructionPlane is not null)
+ {
+ frame = ProfileConstructionPlane;
+ return true;
+ }
if (!TryAxis(Axis, out var normal) || !TryAxis(ReferenceDirection, out var reference))
{
diagnostic = $"compose-placement-invalid-axis:{Name}:axis={Axis}:reference={ReferenceDirection}";
@@ -274,7 +282,8 @@ public static class PrismaticProfileCompositionParser
else diagnostics.Add($"compose-profile-guide-missing-or-arc-sweep:{header.Groups["n"].Value}.{name}");
if (geometry is not null) segments.Add(new(name, geometry, new($"profile:{header.Groups["n"].Value}.Outer.{name}", $"concept:{header.Groups["layout"].Value}.{trace}", name, $"Trace({trace})", "XY")));
}
- var profile = new ResolvedProfile2D(header.Groups["n"].Value, "XY", [new ResolvedProfileLoop2D("Outer", true, segments)]);
+ var frame = ProfileAuthoringParser.ResolveNamedConstructionPlane(source, header.Groups["layout"].Value, diagnostics);
+ var profile = new ResolvedProfile2D(header.Groups["n"].Value, "XY", [new ResolvedProfileLoop2D("Outer", true, segments)], frame);
var validation = ResolvedProfile2DValidator.Validate(profile);
diagnostics.AddRange(validation.Diagnostics);
if (validation.IsValid) profiles.Add(profile.Name, profile);
@@ -303,6 +312,7 @@ public static class PrismaticProfileCompositionParser
if (resolved is not null && reported.Count == 0) profiles.Add(declaration.Name.Text, resolved);
}
if (diagnostics.Count > 0) return new(null, profiles, diagnostics.Distinct(StringComparer.Ordinal).ToArray());
+ var authoredProfiles = profiles.Keys.ToHashSet(StringComparer.Ordinal);
var compose = FirmamentSyntaxTraversal.Declarations(syntax.Document).FirstOrDefault(d => d.Type.Name.Text == "Compose");
if (compose?.Body is null || compose.Name is null) return new(null, profiles, diagnostics.Append("compose-source-missing-compose").ToArray());
if (compose.Clauses.Count > 0 || compose.Type.Arguments.Count > 0)
@@ -365,6 +375,16 @@ public static class PrismaticProfileCompositionParser
// Cardinality is authored semantics, not a LINQ assertion. Never call
// Single/SingleOrDefault while malformed input can still reach this boundary.
var stock = baseOperations.Length == 1 ? baseOperations[0] : null;
+ if (stock is not null && profiles.TryGetValue(stock.ProfileReference, out var stockProfile) && !placement.IsExplicit
+ && !SameFrame(stockProfile.EffectiveConstructionPlane, ConstructionPlane.WorldXY))
+ {
+ placement = placement with { ProfileConstructionPlane = stockProfile.EffectiveConstructionPlane };
+ // These adapters bind supports in world coordinates. Do not let them
+ // reinterpret a local +Z selector as world +Z on an oriented body.
+ foreach (var dependent in operationsSyntax.Document.Statements.OfType<DeclarationSyntax>()
+ .Where(d => d.Type.Name.Text is "Boss" or "Pocket" or "Hole" or "Slot" or "EdgeFinish"))
+ diagnostics.Add($"compose-oriented-feature-not-admitted:{dependent.Type.Name.Text}:{dependent.Name?.Text}: Oriented Compose currently admits Base/Add/Remove in one common Profile frame; this feature's support adapter requires world XY.");
+ }
if (stock is not null)
{
foreach (var declaration in operationsSyntax.Document.Statements.OfType<DeclarationSyntax>().Where(d => d.Type.Name.Text == "Boss"))
@@ -739,11 +759,27 @@ public static class PrismaticProfileCompositionParser
profiles.Add(profileName,profile); roundedRectangleSlots.Add(new(name,stableId,profileName,x,y,dx,dy,l,w,r,from,to,extentText,semanticRole,sourceSpan)); operations.Add(new(name,PrismaticProfileIntent.Remove,profileName,from,to,semanticRole,sourceSpan,stableId,"Slot<RoundedRectangle>"));
}
}
+ if (placement.TryResolveConstructionPlane(out var compositionFrame, out _))
+ foreach (var operation in operations.Where(o => authoredProfiles.Contains(o.ProfileReference)))
+ {
+ var operandFrame = profiles[operation.ProfileReference].EffectiveConstructionPlane;
+ // Legacy Placement transports unplaced XY Profiles. Already
+ // oriented Profiles must agree, rather than being transformed twice.
+ if (placement.IsExplicit && SameFrame(operandFrame, ConstructionPlane.WorldXY)) continue;
+ if (!SameFrame(operandFrame, compositionFrame!))
+ diagnostics.Add($"compose-profile-frame-mismatch:{operation.Name}:{operation.ProfileReference}: All operands must use the same construction frame; an explicit Placement cannot override an oriented Profile.");
+ }
var levels = operations.SelectMany(o => new[] { o.From, o.To }).Distinct().Order().ToArray();
var feature = diagnostics.Count == 0 ? new PrismaticProfileCompositionFeature(compose.Name.Text, placement.ProfilePlane, placement.Axis, placement, operations, levels, "parser-backed-scaffold-profile-composition", shaftHoles, capsuleSlots, roundedRectangleSlots, constructionPlaneBlindDrills, counterboreHoles, bosses, pockets, materialOffsets) : null;
return new(feature, profiles, diagnostics.Distinct().ToArray(), expansion.Evidence);
}
+ private static bool SameFrame(ConstructionPlane left, ConstructionPlane right)
+ => (left.Origin - right.Origin).LengthSquared < 1e-20
+ && (left.AxisX.ToVector() - right.AxisX.ToVector()).LengthSquared < 1e-20
+ && (left.AxisY.ToVector() - right.AxisY.ToVector()).LengthSquared < 1e-20
+ && (left.AxisZ.ToVector() - right.AxisZ.ToVector()).LengthSquared < 1e-20;
+
// Transitional engineering value readers operate on one AST field, never on
// arbitrary surrounding source. Field consumption and statement boundaries are
// owned by the recursive-descent frontend; existing domain checks stay here.
diff --git a/Aetheris.Web.Runtime/Program.cs b/Aetheris.Web.Runtime/Program.cs
index 44e657f7..8c9dfc93 100644
--- a/Aetheris.Web.Runtime/Program.cs
+++ b/Aetheris.Web.Runtime/Program.cs
@@ -58,6 +58,8 @@ public static partial class Program
"languageComplete" => LanguageComplete(request),
"languageAnalyze" => LanguageAnalyze(request),
"languageOutline" => LanguageOutline(request),
+ "languageSketch" => LanguageSketch(request),
+ "languageSketchEdit" => LanguageSketchEdit(request),
"languageEdit" => LanguageEdit(request),
"languagePalette" => FirmamentLanguagePaletteService.Palette(),
"languageHover" => LanguageHover(request),
@@ -159,6 +161,21 @@ public static partial class Program
return FirmamentLanguageOutlineService.Outline(new FirmamentProjectSnapshot(request.ProjectRoot ?? name, documents), name, request.SourceRevision);
}
+ private static object LanguageSketch(WebRequest request)
+ {
+ if (request.Source is null || request.SourceRevision is null)
+ throw new WebRuntimeException("source-required", "A sketch query requires source and its revision.");
+ return FirmamentSketchService.Project(request.Source, request.SourceName ?? "model.firmament", request.SourceRevision, request.Node);
+ }
+
+ private static object LanguageSketchEdit(WebRequest request)
+ {
+ if (request.Source is null || request.SourceRevision is null || request.SketchEdit is null)
+ throw new WebRuntimeException("source-required", "A sketch edit requires source, revision and an operation.");
+ try { return FirmamentSketchService.Edit(request.Source, request.SourceName ?? "model.firmament", request.SourceRevision, request.SketchEdit); }
+ catch (FirmamentLanguageEditException error) { throw new WebRuntimeException(error.Code, error.Message); }
+ }
+
private static object LanguageEdit(WebRequest request)
{
if (request.Source is null || string.IsNullOrWhiteSpace(request.SourceRevision) || request.Operations is not { Count: > 0 })
@@ -278,7 +295,8 @@ public static partial class Program
bool Performance = false, IReadOnlyDictionary<string, string>? ProjectDocuments = null, string? ProjectRoot = null,
int? Bridge = null, IReadOnlyList<FirmamentLanguageEditOperation>? Operations = null,
string? Motion = null, double? TimeSeconds = null, bool PreserveEndpoint = false,
- IReadOnlyList<string>? Formats = null, Aetheris.Geometry.MeasurementRequest? Measurement = null);
+ IReadOnlyList<string>? Formats = null, Aetheris.Geometry.MeasurementRequest? Measurement = null,
+ string? Node = null, FirmamentSketchEditRequest? SketchEdit = null);
/// <summary>
/// BUILD-PERF-M3 response bridge (request <c>bridge: 1</c>, sent by the SDK). Large numeric arrays
diff --git a/Aetheris.Web.Runtime/sdk/README.md b/Aetheris.Web.Runtime/sdk/README.md
index 71a10175..39469400 100644
--- a/Aetheris.Web.Runtime/sdk/README.md
+++ b/Aetheris.Web.Runtime/sdk/README.md
@@ -166,3 +166,23 @@ an absent or empty array means common to all variants. Schema-driven controls
must honor this metadata or request completion. For example, `CounterboreDepth`
applies to `Counterbore`, never `Shaft`. Part build diagnostics use the shared
compiler presenter, retaining stable error codes and authored source locations.
+
+### Profile workspace projection
+
+`cad.language.sketch(source, profileNodeIdOrNull, { sourceName, sourceRevision })`
+returns `firmament-sketch/1`: the authored Profile choices, resolved local analytic
+curves, construction frame, source provenance, and dimension controls. A null id
+chooses the first authored Profile. The validation level is
+`ProfileResolvedNotBuilt`; this query does not construct or admit a solid.
+
+`cad.language.sketchEdit(source, request, options)` prepares a normal
+`LanguageEdit` for `dimensions`, `create`, or a qualified circular `opening`.
+Dimension changes use the returned control ids and numeric values in their
+displayed units. Read-only expressions/tolerances cannot be replaced through
+this operation. A directly named literal Static is updated at its initializer.
+The caller must compare source revisions before applying the edit and then use
+the normal compile/rebuild transaction. A refused edit returns its stable SDK
+error code and explanation, with no source mutation.
+
+This first contract addresses authored Profiles in one document. It does not
+rewrite included/generated declarations. See [the authoring guide](../../../docs/public/firmament/sketcher.md).
diff --git a/Aetheris.Web.Runtime/sdk/src/index.d.ts b/Aetheris.Web.Runtime/sdk/src/index.d.ts
index 0d36c0d2..e6c0cb62 100644
--- a/Aetheris.Web.Runtime/sdk/src/index.d.ts
+++ b/Aetheris.Web.Runtime/sdk/src/index.d.ts
@@ -46,6 +46,7 @@ export interface LanguageOutline { readonly version: 'firmament-outline/1'; read
export interface DeclarationSpec { readonly kind: string; readonly variant?: string | null; readonly modifiers?: readonly string[] | null; readonly name?: string | null; readonly fields?: readonly { readonly name: string; readonly value: string }[] | null }
/** One structural edit, addressed by outline node ids. Operations apply in order; each later one sees the ids the earlier ones produced. */
export type LanguageEditOperation =
+ | { readonly kind: 'setValue'; readonly node: string; readonly value: string }
| { readonly kind: 'setField'; readonly node: string; readonly field: string; readonly value: string }
| { readonly kind: 'removeField'; readonly node: string; readonly field: string }
| { readonly kind: 'insertDeclaration'; readonly parent: string | null; readonly declaration?: DeclarationSpec; readonly source?: string; readonly name?: string; readonly after?: string; readonly first?: boolean }
@@ -60,6 +61,25 @@ export interface LanguageEdit { readonly document: string; readonly revision: st
/** Something a visual editor can add. `placement` `model` inserts with `insertDeclaration`; `feature` with `insertFeature` on a body. `source` declares `nameStem`; pass a unique `name` with the insert. Every item is proven to build. */
export interface PaletteItem { readonly id: string; readonly label: string; readonly category: string; readonly description: string; readonly placement: 'model' | 'feature'; readonly nameStem: string; readonly source: string; readonly requiresEmptyModel?: boolean }
export interface LanguagePalette { readonly version: 'firmament-palette/1'; readonly items: readonly PaletteItem[] }
+export interface SketchControl { id: string; label: string; authored: string; value: number; unit: string; editable: boolean; parameter: string | null; readOnlyReason: string | null; span: { start: number; length: number } }
+export interface SketchShape { id: string; name: string; kind: string; center: readonly number[]; controls: readonly SketchControl[] }
+export interface SketchCurve {
+ id: string; name: string; kind: string; points: readonly (readonly number[])[]; center: readonly number[] | null;
+ radius: number; startAngle: number; sweep: number; minorRadius: number; rotation: number;
+ /** Resolver evidence. Its sourceSpan can identify lowered source; use control spans for authored navigation. */
+ provenance?: { stableId: string; conceptStableId: string; sourceSpan: string; derivation: string; sourceFrame: string; tracedFrom?: string | null; reversed: boolean; pipelineIndex?: number | null; invocationSourceRange?: string | null };
+}
+export interface SketchProjection {
+ version: 'firmament-sketch/1'; document: string; revision: string; node: string | null;
+ profiles: readonly { id: string; name: string }[]; emptyModels: readonly { id: string; name: string }[];
+ openingReferences: readonly { id: string; name: string }[];
+ frame: { name: string; origin: readonly number[]; x: readonly number[]; y: readonly number[]; normal: readonly number[] } | null;
+ loops: readonly { name: string; isOuter: boolean; curves: readonly SketchCurve[] }[];
+ shapes: readonly SketchShape[]; diagnostics: readonly { severity: string; code: string; message: string; span: { start: number; length: number } | null }[];
+ validationLevel: 'ProfileResolvedNotBuilt' | 'Unresolved';
+}
+export interface SketchEditRequest { kind: 'dimensions' | 'create' | 'opening'; node?: string | null; shape?: string; changes?: readonly { control: string; value: number }[]; x?: number; y?: number; reference?: string; anchor?: string; diameter?: number; width?: number; height?: number }
+
export interface LanguageHover { readonly document: string; readonly revision: string; readonly start: number; readonly length: number; readonly title: string; readonly description: string }
export interface LanguageFormat { readonly document: string; readonly revision: string; readonly text: string; readonly changed: boolean }
export interface SemanticFieldSchema { readonly id: string; readonly name: string; readonly kind: string; readonly unit: 'None' | 'Length' | 'Angle'; readonly required: boolean; readonly default: string | null; readonly choices: readonly string[]; readonly variants?: readonly string[]; readonly description: string | null; readonly sourceEditable: boolean }
@@ -77,7 +97,7 @@ export class Aetheris {
static create(options?: AetherisOptions): Promise<Aetheris>;
readonly runtimeInfo: RuntimeInfo;
readonly workerTiming: WorkerTiming | null;
- readonly language: { complete(source: string, offset: number, options: LanguageOptions): Promise<LanguageCompletion>; analyze(source: string, options: LanguageOptions): Promise<LanguageAnalysis>; outline(source: string, options: LanguageOptions): Promise<LanguageOutline>; edit(source: string, operations: readonly LanguageEditOperation[], options: LanguageOptions): Promise<LanguageEdit>; palette(): Promise<LanguagePalette>; hover(source: string, offset: number, options: LanguageOptions): Promise<LanguageHover | null>; definition(source: string, offset: number, options: LanguageOptions): Promise<SourceReference | null>; format(source: string, options: LanguageOptions): Promise<LanguageFormat>; schema(): Promise<SemanticSchema> };
+ readonly language: { sketch(source: string, node: string | null, options: LanguageOptions): Promise<SketchProjection>; sketchEdit(source: string, edit: SketchEditRequest, options: LanguageOptions): Promise<LanguageEdit>; complete(source: string, offset: number, options: LanguageOptions): Promise<LanguageCompletion>; analyze(source: string, options: LanguageOptions): Promise<LanguageAnalysis>; outline(source: string, options: LanguageOptions): Promise<LanguageOutline>; edit(source: string, operations: readonly LanguageEditOperation[], options: LanguageOptions): Promise<LanguageEdit>; palette(): Promise<LanguagePalette>; hover(source: string, offset: number, options: LanguageOptions): Promise<LanguageHover | null>; definition(source: string, offset: number, options: LanguageOptions): Promise<SourceReference | null>; format(source: string, options: LanguageOptions): Promise<LanguageFormat>; schema(): Promise<SemanticSchema> };
info(): Promise<RuntimeInfo>;
capabilities(): Promise<RuntimeCapabilities>;
compile(source: string, options?: CompileOptions): Promise<{ model: ModelSession | null; diagnostics: readonly Diagnostic[] }>;
diff --git a/Aetheris.Web.Runtime/sdk/src/index.js b/Aetheris.Web.Runtime/sdk/src/index.js
index 133f11ca..25bea1d1 100644
--- a/Aetheris.Web.Runtime/sdk/src/index.js
+++ b/Aetheris.Web.Runtime/sdk/src/index.js
@@ -89,6 +89,10 @@ export class Aetheris {
outline: (source, options = {}) => this.transport.request({ operation: 'languageOutline', source,
sourceName: options.sourceName, sourceRevision: options.sourceRevision, projectDocuments: options.projectDocuments, projectRoot: options.projectRoot }),
palette: () => this.transport.request({ operation: 'languagePalette' }),
+ sketch: (source, node, options = {}) => this.transport.request({ operation: 'languageSketch', source, node,
+ sourceName: options.sourceName, sourceRevision: options.sourceRevision }),
+ sketchEdit: (source, sketchEdit, options = {}) => this.transport.request({ operation: 'languageSketchEdit', source, sketchEdit,
+ sourceName: options.sourceName, sourceRevision: options.sourceRevision }),
edit: (source, operations, options = {}) => this.transport.request({ operation: 'languageEdit', source, operations,
sourceName: options.sourceName, sourceRevision: options.sourceRevision }),
hover: (source, offset, options = {}) => this.transport.request({ operation: 'languageHover', source, offset,
diff --git a/Aetheris.Web.Runtime/sdk/tests/language.test.mjs b/Aetheris.Web.Runtime/sdk/tests/language.test.mjs
index 88f2fb4a..9a6747ed 100644
--- a/Aetheris.Web.Runtime/sdk/tests/language.test.mjs
+++ b/Aetheris.Web.Runtime/sdk/tests/language.test.mjs
@@ -2,6 +2,18 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { Aetheris } from '../src/index.js';
+test('sketch projection and edit retain the authored revision and selected Profile without compiling', async () => {
+ const requests = []; const cad = new Aetheris({ request: async request => { requests.push(request); return { revision: request.sourceRevision }; } });
+ const options = { sourceName: 'part.firmament', sourceRevision: 'r5' };
+ await cad.language.sketch('source', 'Part/Section', options);
+ const edit = { kind: 'dimensions', node: 'Part/Section', changes: [{ control: 'width', value: 100 }] };
+ await cad.language.sketchEdit('source', edit, options);
+ assert.deepEqual(requests, [
+ { operation: 'languageSketch', source: 'source', node: 'Part/Section', ...options },
+ { operation: 'languageSketchEdit', source: 'source', sketchEdit: edit, ...options },
+ ]);
+});
+
test('public language completion sends source revision and offset through runtime transport', async () => {
const requests = [];
const cad = new Aetheris({ request: async request => {
diff --git a/Aetheris.Web.Runtime/telos/src/index.ts b/Aetheris.Web.Runtime/telos/src/index.ts
index 15b2938e..045730da 100644
--- a/Aetheris.Web.Runtime/telos/src/index.ts
+++ b/Aetheris.Web.Runtime/telos/src/index.ts
@@ -11,3 +11,4 @@ export * from "./presentation.js";
export * from "./temporal.js";
export * from "./concepts.js";
export * from "./measurement.js";
+export * from "./sketch.js";
diff --git a/Aetheris.Web.Runtime/telos/src/sketch.ts b/Aetheris.Web.Runtime/telos/src/sketch.ts
new file mode 100644
index 00000000..4d99b5a3
--- /dev/null
+++ b/Aetheris.Web.Runtime/telos/src/sketch.ts
@@ -0,0 +1,274 @@
+/** A compiler projection, never an independent sketch model or constraint system. */
+export interface SketchControl { id: string; label: string; authored: string; value: number; unit: string; editable: boolean; parameter: string | null; readOnlyReason: string | null; span: { start: number; length: number } }
+export interface SketchShape { id: string; name: string; kind: string; center: readonly number[]; controls: readonly SketchControl[] }
+export interface SketchCurve {
+ id: string; name: string; kind: string; points: readonly (readonly number[])[]; center: readonly number[] | null;
+ radius: number; startAngle: number; sweep: number; minorRadius: number; rotation: number;
+ /** Resolver evidence. Its sourceSpan can identify lowered source; use control spans for authored navigation. */
+ provenance?: { stableId: string; conceptStableId: string; sourceSpan: string; derivation: string; sourceFrame: string; tracedFrom?: string | null; reversed: boolean; pipelineIndex?: number | null; invocationSourceRange?: string | null };
+}
+export interface SketchProjection {
+ version: 'firmament-sketch/1'; document: string; revision: string; node: string | null;
+ profiles: readonly { id: string; name: string }[]; emptyModels: readonly { id: string; name: string }[];
+ openingReferences: readonly { id: string; name: string }[];
+ frame: { name: string; origin: readonly number[]; x: readonly number[]; y: readonly number[]; normal: readonly number[] } | null;
+ loops: readonly { name: string; isOuter: boolean; curves: readonly SketchCurve[] }[];
+ shapes: readonly SketchShape[]; diagnostics: readonly { severity: string; code: string; message: string; span: { start: number; length: number } | null }[];
+ validationLevel: 'ProfileResolvedNotBuilt' | 'Unresolved';
+}
+export interface SketchEditRequest { kind: 'dimensions' | 'create' | 'opening'; node?: string | null; shape?: string; changes?: readonly { control: string; value: number }[]; x?: number; y?: number; reference?: string; anchor?: string; diameter?: number; width?: number; height?: number }
+export interface SketchCallbacks {
+ project(node: string | null): Promise<SketchProjection>;
+ preview(request: SketchEditRequest): Promise<SketchProjection>;
+ apply(request: SketchEditRequest): Promise<string | null>;
+ source(span: { start: number; length: number }): void;
+ close(): void;
+}
+
+const ns = 'http://www.w3.org/2000/svg';
+const number = (value: number) => Number(value.toPrecision(8)).toString();
+const errorText = (error: unknown) => {
+ const code = (error as { code?: unknown })?.code;
+ return (typeof code === 'string' ? `${code}: ` : '') + (error instanceof Error ? error.message : String(error));
+};
+/** Display sampling only; source geometry and engineering validation stay with Profile resolution. */
+export function sketchCurvePoints(curve: SketchCurve): number[][] {
+ if (curve.kind === 'Line') return curve.points.map(p => [...p]);
+ if (curve.kind === 'Cubic') return Array.from({ length: 49 }, (_, i) => {
+ const t = i / 48, u = 1 - t, p = curve.points;
+ return [0, 1].map(a => u ** 3 * p[0][a] + 3 * u ** 2 * t * p[1][a] + 3 * u * t ** 2 * p[2][a] + t ** 3 * p[3][a]);
+ });
+ const count = Math.max(8, Math.ceil(Math.abs(curve.sweep) * 36));
+ return Array.from({ length: count + 1 }, (_, i) => {
+ const angle = curve.startAngle + curve.sweep * i / count;
+ const x = curve.radius * Math.cos(angle), y = (curve.kind === 'Ellipse' ? curve.minorRadius : curve.radius) * Math.sin(angle);
+ return [curve.center![0] + x * Math.cos(curve.rotation) - y * Math.sin(curve.rotation),
+ curve.center![1] + x * Math.sin(curve.rotation) + y * Math.cos(curve.rotation)];
+ });
+}
+
+/** Framework-independent 2D workspace shared by product hosts. Each completed gesture is one source edit. */
+export class SketchWorkspace {
+ private view: SketchProjection | null = null;
+ private selected: string | null = null;
+ private generation = 0;
+ private disposed = false;
+ private pending = false;
+ private error = '';
+ private draft = false;
+ private revision: unknown;
+ private timer?: ReturnType<typeof setTimeout>;
+ private dragCleanup?: () => void;
+ private svg?: SVGSVGElement;
+ private extent = [-60, -40, 120, 80];
+ private readonly keyboard = (event: KeyboardEvent) => {
+ if (event.key === 'Tab') {
+ const controls = Array.from(this.host.querySelectorAll<HTMLElement>('button:not(:disabled),input:not(:disabled),select:not(:disabled),[tabindex="0"]'));
+ const first = controls[0], last = controls.at(-1);
+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }
+ return;
+ }
+ if (event.key !== 'Escape') return;
+ if (this.dragCleanup) { this.cancelDrag(); this.render(); }
+ else if (!(event.target as HTMLElement)?.closest('input,select')) this.callbacks.close();
+ };
+ constructor(private host: HTMLElement, private callbacks: SketchCallbacks) {
+ host.style.cssText = 'position:absolute;inset:0;z-index:30;display:flex;flex-direction:column;background:#fafaf7;color:#242424;font:13px/1.45 system-ui';
+ host.style.colorScheme = 'light';
+ host.setAttribute('role', 'region'); host.setAttribute('aria-label', 'Sketch workspace');
+ host.tabIndex = -1; host.focus();
+ host.addEventListener('keydown', this.keyboard);
+ }
+ async load(revision: unknown, node: string | null = this.view?.node ?? null) {
+ this.revision = revision; this.cancelDrag();
+ const generation = ++this.generation;
+ this.pending = true; this.render();
+ try {
+ const view = await this.callbacks.project(node);
+ if (generation !== this.generation || this.disposed) return;
+ this.view = view; this.error = ''; this.draft = false;
+ if (!view.shapes.some(s => s.id === this.selected)) this.selected = view.shapes[0]?.id ?? null;
+ } catch (error) { if (generation === this.generation) { this.view = null; this.error = errorText(error); } }
+ finally { if (generation === this.generation && !this.disposed) { this.pending = false; this.render(); } }
+ }
+ dispose() { this.disposed = true; ++this.generation; this.cancelDrag(); this.host.removeEventListener('keydown', this.keyboard); this.host.replaceChildren(); }
+ private cancelDrag() { clearTimeout(this.timer); this.dragCleanup?.(); this.dragCleanup = undefined; this.draft = false; }
+ private async apply(request: SketchEditRequest) {
+ if (this.pending) return;
+ const generation = ++this.generation;
+ this.pending = true; this.error = ''; this.draft = false; this.render();
+ try {
+ const refused = await this.callbacks.apply(request);
+ if (generation !== this.generation || this.disposed) return;
+ if (refused) this.error = refused;
+ } catch (error) { if (generation === this.generation) this.error = errorText(error); }
+ finally { if (generation === this.generation && !this.disposed) { this.pending = false; this.render(); } }
+ }
+ private render() {
+ this.host.replaceChildren();
+ const bar = document.createElement('div'); bar.style.cssText = 'display:flex;gap:8px;align-items:center;padding:10px 14px;border-bottom:1px solid #ddd;flex-wrap:wrap'; this.host.append(bar);
+ const button = (parent: HTMLElement, text: string, action: () => void) => {
+ const b = document.createElement('button'); b.type = 'button'; b.textContent = text; b.onclick = action;
+ b.style.cssText = 'padding:6px 10px;border:1px solid #b7b7af;border-radius:4px;background:white;color:#222;cursor:pointer'; parent.append(b); return b;
+ };
+ const title = document.createElement('strong'); title.textContent = 'Sketch'; bar.append(title);
+ const profiles = document.createElement('select'); profiles.setAttribute('aria-label', 'Sketch profile');
+ for (const profile of this.view?.profiles ?? []) { const option = document.createElement('option'); option.value = profile.id; option.textContent = profile.name; profiles.append(option); }
+ profiles.value = this.view?.node ?? ''; profiles.disabled = this.pending;
+ profiles.onchange = () => void this.load(this.revision, profiles.value); bar.append(profiles);
+ button(bar, 'Fit', () => this.draw(true));
+ const close = button(bar, 'Done', () => this.callbacks.close()); close.style.marginLeft = 'auto';
+ if (this.view?.frame) {
+ const frame = document.createElement('div'); frame.textContent = `Plane: ${this.view.frame.name} · origin (${this.view.frame.origin.map(number).join(', ')}) mm · normal (${this.view.frame.normal.map(number).join(', ')})`;
+ frame.style.cssText = 'padding:6px 14px;color:#62625a;background:#f1f0e9'; this.host.append(frame);
+ }
+ if (this.view?.emptyModels.length) {
+ const create = document.createElement('div'); create.style.cssText = 'padding:8px 14px;display:flex;gap:8px;align-items:center';
+ const label = document.createElement('span'); label.textContent = 'Start a profile + 6 mm extrusion:'; create.append(label);
+ const parent = document.createElement('select'); parent.setAttribute('aria-label', 'New sketch model');
+ for (const model of this.view.emptyModels) { const option = document.createElement('option'); option.value = model.id; option.textContent = model.name; parent.append(option); } create.append(parent);
+ for (const [shape, text] of [['Rect2', 'Rectangle'], ['Circle2', 'Circle'], ['Slot2', 'Slot'], ['RoundedRect2', 'Rounded rectangle']])
+ button(create, text, () => void this.apply({ kind: 'create', node: parent.value, shape })).disabled = this.pending;
+ this.host.append(create);
+ }
+ const content = document.createElement('div'); content.style.cssText = 'display:flex;flex:1;min-height:0'; this.host.append(content);
+ const canvas = document.createElement('div'); canvas.style.cssText = 'position:relative;flex:1;min-width:0;overflow:hidden'; content.append(canvas);
+ this.svg = document.createElementNS(ns, 'svg'); this.svg.setAttribute('aria-label', 'Profile canvas'); this.svg.style.cssText = 'width:100%;height:100%;min-height:260px;touch-action:none'; canvas.append(this.svg);
+ this.svg.addEventListener('wheel', event => {
+ event.preventDefault(); const scale = event.deltaY > 0 ? 1.12 : 1 / 1.12;
+ const [x, y, w, h] = this.extent; this.extent = [x + w * (1 - scale) / 2, y + h * (1 - scale) / 2, w * scale, h * scale]; this.draw(false);
+ }, { passive: false });
+ this.svg.addEventListener('pointerdown', event => {
+ if (event.button !== 1 && !(event.button === 0 && event.altKey)) return;
+ event.preventDefault(); this.cancelDrag();
+ const startX = event.clientX, startY = event.clientY, extent = [...this.extent];
+ const scale = 1 / Math.abs(this.svg!.getScreenCTM()?.a ?? 1);
+ const move = (next: PointerEvent) => { this.extent = [extent[0] - (next.clientX - startX) * scale, extent[1] - (next.clientY - startY) * scale, extent[2], extent[3]]; this.draw(false); };
+ const finish = () => { cleanup(); this.dragCleanup = undefined; };
+ const cleanup = () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', finish); window.removeEventListener('pointercancel', finish); };
+ this.dragCleanup = cleanup; window.addEventListener('pointermove', move); window.addEventListener('pointerup', finish); window.addEventListener('pointercancel', finish);
+ });
+ const inspector = document.createElement('div'); inspector.style.cssText = 'width:250px;max-width:38%;padding:12px;overflow:auto;border-left:1px solid #ddd;background:white'; content.append(inspector);
+ const choices = document.createElement('select'); choices.setAttribute('aria-label', 'Sketch shape'); choices.style.width = '100%';
+ for (const shape of this.view?.shapes ?? []) { const option = document.createElement('option'); option.value = shape.id; option.textContent = `${shape.name} · ${shape.kind}`; choices.append(option); }
+ choices.value = this.selected ?? ''; choices.onchange = () => { this.selected = choices.value; this.render(); }; inspector.append(choices);
+ const shape = this.view?.shapes.find(s => s.id === this.selected);
+ for (const control of shape?.controls ?? []) {
+ const row = document.createElement('label'); row.style.cssText = 'display:block;margin-top:12px';
+ const label = document.createElement('span'); label.textContent = `${control.label} (${control.unit})`; row.append(label);
+ const input = document.createElement('input'); input.type = 'number'; input.step = 'any'; input.value = number(control.value);
+ input.setAttribute('aria-label', control.label); input.disabled = this.pending || !control.editable;
+ input.title = control.readOnlyReason ?? (control.parameter ? `Edits parameter ${control.parameter}` : control.authored);
+ input.style.cssText = 'display:block;box-sizing:border-box;width:100%;padding:6px;margin-top:3px'; row.append(input);
+ let submitted = false;
+ const commit = () => {
+ if (submitted || input.value.trim() === '' || !Number.isFinite(input.valueAsNumber) || input.valueAsNumber === control.value) return;
+ submitted = true; void this.apply({ kind: 'dimensions', node: this.view?.node, changes: [{ control: control.id, value: input.valueAsNumber }] });
+ };
+ input.onblur = commit; input.onkeydown = event => { if (event.key === 'Enter') { event.preventDefault(); commit(); } if (event.key === 'Escape') { input.value = number(control.value); input.blur(); } };
+ const origin = document.createElement('small'); origin.style.cssText = 'display:block;color:#777;overflow-wrap:anywhere';
+ origin.textContent = control.parameter ? `↗ ${control.parameter} · shared parameter` : control.editable ? 'Driving dimension' : `ƒ ${control.authored}`;
+ row.append(origin);
+ if (!control.editable) button(row, 'Edit source', () => this.callbacks.source(control.span));
+ inspector.append(row);
+ }
+ if (this.view?.openingReferences.length && !this.pending) {
+ const form = document.createElement('form'); form.style.cssText = 'border-top:1px solid #ddd;margin-top:20px;padding-top:10px';
+ const heading = document.createElement('strong'); heading.textContent = 'Circular profile opening'; form.append(heading);
+ const help = document.createElement('p'); help.textContent = 'Follow a rectangle corner with shared driving parameters. Insets are inward from its edges.'; form.append(help);
+ const reference = document.createElement('select'); reference.setAttribute('aria-label', 'Opening reference');
+ for (const item of this.view.openingReferences) { const option = document.createElement('option'); option.value = item.id; option.textContent = item.name; reference.append(option); } form.append(reference);
+ const anchor = document.createElement('select'); anchor.setAttribute('aria-label', 'Opening anchor');
+ for (const name of ['BottomLeft', 'BottomRight', 'TopRight', 'TopLeft', 'Center', 'Left', 'Right', 'Bottom', 'Top']) { const option = document.createElement('option'); option.value = name; option.textContent = name.replace(/([a-z])([A-Z])/g, '$1 $2') + (['Left', 'Right', 'Bottom', 'Top'].includes(name) ? ' midpoint' : ''); anchor.append(option); } form.append(anchor);
+ const input = (name: string, initial: number) => {
+ const label = document.createElement('label'); label.textContent = `${name} (mm)`; label.style.cssText = 'display:block;margin-top:8px';
+ const field = document.createElement('input'); field.type = 'number'; field.step = 'any'; field.min = '0'; field.value = String(initial); field.required = true; field.setAttribute('aria-label', name); field.style.width = '95%'; label.append(field); form.append(label); return field;
+ };
+ const insetX = input('X inset', 8), insetY = input('Y inset', 8), diameter = input('Opening diameter', 4);
+ anchor.onchange = () => { insetX.disabled = ['Center', 'Top', 'Bottom'].includes(anchor.value); insetY.disabled = ['Center', 'Left', 'Right'].includes(anchor.value); };
+ const add = button(form, 'Add opening', () => { if (form.reportValidity()) void this.apply({ kind: 'opening', node: this.view?.node,
+ reference: reference.value, anchor: anchor.value, x: insetX.valueAsNumber, y: insetY.valueAsNumber, diameter: diameter.valueAsNumber }); });
+ add.style.marginTop = '10px'; form.onsubmit = event => { event.preventDefault(); add.click(); }; inspector.append(form);
+ }
+ const status = document.createElement('div'); status.setAttribute('role', this.error || this.view?.diagnostics.length ? 'alert' : 'status');
+ status.style.cssText = 'padding:8px 14px;border-top:1px solid #ddd;white-space:pre-wrap;max-height:120px;overflow:auto';
+ status.textContent = this.error || this.view?.diagnostics.map(d => `${d.code}: ${d.message}`).join('\n') || (this.pending ? 'Resolving…' : this.draft ? 'Profile preview · not built' : this.view && !this.view.profiles.length && !this.view.emptyModels.length
+ ? 'No authored Profile in this document. Use Command palette → New sketch part, or open a document containing a Profile.'
+ : 'Drag a dimension or type a value. Scroll to zoom; middle-drag to pan. Solid admission is checked by Build.'); this.host.append(status);
+ this.draw(true);
+ }
+ private draw(fit: boolean, preview = this.view) {
+ const svg = this.svg; if (!svg) return; svg.replaceChildren();
+ const curves = preview?.loops.flatMap(l => l.curves) ?? [];
+ const points = curves.flatMap(sketchCurvePoints);
+ if (fit && points.length) {
+ const xs = points.map(p => p[0]), ys = points.map(p => p[1]);
+ const x = Math.min(...xs), y = Math.min(...ys), w = Math.max(1, Math.max(...xs) - x), h = Math.max(1, Math.max(...ys) - y);
+ const pad = Math.max(w, h) * .3; this.extent = [x - pad, -y - h - pad, w + 2 * pad, h + 2 * pad];
+ }
+ svg.setAttribute('viewBox', this.extent.join(' '));
+ const element = (tag: string, attrs: Record<string, string>) => {
+ const el = document.createElementNS(ns, tag); for (const [key, value] of Object.entries(attrs)) el.setAttribute(key, value); svg.append(el); return el;
+ };
+ const [x, y, w, h] = this.extent;
+ for (const [a, b, c, d, color] of [[x, 0, x + w, 0, '#bb7777'], [0, y, 0, y + h, '#779977']])
+ element('line', { x1: String(a), y1: String(b), x2: String(c), y2: String(d), stroke: String(color), 'stroke-width': '1', 'vector-effect': 'non-scaling-stroke', 'stroke-dasharray': '4 5' });
+ for (const curve of curves) {
+ const p = sketchCurvePoints(curve);
+ const path = element('polyline', { points: p.map(v => `${v[0]},${-v[1]}`).join(' '), fill: 'none', stroke: this.draft ? '#ad7a17' : '#293c48', 'stroke-width': '2', 'vector-effect': 'non-scaling-stroke', 'data-member': curve.id });
+ const title = document.createElementNS(ns, 'title'); title.textContent = curve.name; path.append(title);
+ }
+ const label = element('text', { x: String(x + w * .02), y: String(y + h * .05), 'font-size': String(w / 65), fill: '#667' }); label.textContent = '+X → +Y ↑ · mm';
+ const shape = preview?.shapes.find(s => s.id === this.selected);
+ for (const candidate of preview?.shapes ?? []) {
+ const marker = element('circle', { cx: String(candidate.center[0]), cy: String(-candidate.center[1]), r: String(w / 180),
+ fill: candidate.id === this.selected ? '#c99630' : '#fff', stroke: '#a27b2d', 'stroke-width': '1', 'vector-effect': 'non-scaling-stroke',
+ tabindex: '0', role: 'button', 'aria-label': `Select ${candidate.name}` });
+ marker.style.cursor = 'pointer'; marker.addEventListener('click', () => { this.selected = candidate.id; this.render(); });
+ marker.addEventListener('keydown', event => { if ((event as KeyboardEvent).key === 'Enter') { this.selected = candidate.id; this.render(); } });
+ }
+ const controls = shape?.controls.filter(c => c.label !== 'Center X' && c.label !== 'Center Y') ?? [];
+ controls.forEach((control, index) => {
+ const fontSize = 13 / Math.abs(svg.getScreenCTM?.()?.a ?? (600 / w));
+ const cx = x + w * (.09 + .46 * (index % 2)), cy = y + h * .82 + fontSize * 1.7 * Math.floor(index / 2);
+ const text = element('text', { x: String(cx), y: String(cy), 'font-size': String(fontSize), fill: control.editable ? '#885d0c' : '#777', tabindex: control.editable ? '0' : '-1', role: 'button', 'aria-label': `Drag ${control.label}`, 'data-control': control.id });
+ text.textContent = `${control.editable ? '◆ ' : 'ƒ '}${control.label}: ${number(control.value)} ${control.unit}`;
+ text.style.cursor = control.editable ? 'ew-resize' : 'help';
+ text.addEventListener('pointerdown', event => { if (control.editable && !this.pending) this.beginDrag(event as PointerEvent, control); });
+ text.addEventListener('keydown', event => {
+ const key = (event as KeyboardEvent).key;
+ if (!control.editable || !['ArrowLeft', 'ArrowRight'].includes(key)) return;
+ event.preventDefault(); void this.apply({ kind: 'dimensions', node: this.view?.node, changes: [{ control: control.id, value: control.value + (key === 'ArrowRight' ? 1 : -1) }] });
+ });
+ });
+ }
+ private beginDrag(event: PointerEvent, control: SketchControl) {
+ event.preventDefault(); this.cancelDrag(); const start = event.clientX;
+ const matrix = this.svg!.getScreenCTM(); const mmPerPixel = matrix ? 1 / Math.abs(matrix.a) : this.extent[2] / this.svg!.clientWidth;
+ let value = control.value, requested = 0, inFlight = false, finished = false;
+ const request = (): SketchEditRequest => ({ kind: 'dimensions', node: this.view?.node, changes: [{ control: control.id, value }] });
+ const preview = async () => {
+ if (inFlight || finished) return; inFlight = true; const current = requested;
+ try {
+ const view = await this.callbacks.preview(request());
+ if (finished || current !== requested || this.disposed) return;
+ this.draft = true; this.error = ''; this.draw(false, view);
+ const status = this.host.querySelector('[role="status"],[role="alert"]'); if (status) status.textContent = 'Profile preview · not built';
+ } catch (error) { if (!finished && current === requested) { this.error = errorText(error); const status = this.host.querySelector('[role="status"],[role="alert"]'); if (status) status.textContent = this.error; } }
+ finally { inFlight = false; if (!finished && current !== requested) this.timer = setTimeout(() => void preview(), 60); }
+ };
+ const move = (next: PointerEvent) => {
+ value = Math.round((control.value + (next.clientX - start) * mmPerPixel) * 100) / 100; ++requested;
+ clearTimeout(this.timer); this.timer = setTimeout(() => void preview(), 60);
+ };
+ const up = () => {
+ cleanup(); this.dragCleanup = undefined; this.draft = false;
+ if (value !== control.value) void this.apply(request()); else this.render();
+ };
+ const cleanup = () => { finished = true; clearTimeout(this.timer); window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); window.removeEventListener('pointercancel', cancel); };
+ const cancel = () => { cleanup(); this.dragCleanup = undefined; this.draft = false; this.render(); };
+ this.dragCleanup = cleanup;
+ window.addEventListener('pointermove', move); window.addEventListener('pointerup', up, { once: true }); window.addEventListener('pointercancel', cancel, { once: true });
+ }
+}
diff --git a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
index 215117da..f1023174 100644
--- a/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
+++ b/docs/development/FIRMAMENT-LANGUAGE-DECISIONS-2026-10.md
@@ -1,5 +1,22 @@
# October 2026 Firmament language decision register
+Sketcher / principal-plane amendment (2026-10-19): `Concept Struct on XZ`
+was an admission limitation, not a language prohibition worth preserving.
+For a local 2D layout consumed by `Profile ... using Layout`, admit XY, XZ and YZ
+through the existing ConstructionPlane owner. XZ has local axes +X/+Z and normal
+-Y; YZ has local axes +Y/+Z and normal +X. Keep default/explicit XY byte-compatible.
+This is a frame selection for local 2D guides, not an implicit transform of typed
+3D semantic values or unrelated consumers. Mixed spatial layouts and unsupported
+material consumers still need explicit admission. The original X0/X4 XZ specimens
+are retained; their rejection assertions must become orientation/geometry checks
+after qualification, with an explicit traced-plane reference for X4 f01.
+No specimen is rewritten to disguise the original requested plane.
+Compose now preserves the inherited Base Profile frame and requires matching
+frames for authored Base/Add/Remove operands. Existing world-coordinate support
+adapters reject oriented Boss/Pocket/Hole/Slot/EdgeFinish combinations explicitly.
+The X4 f01 qualification includes absolute world bounds, because comparing two
+routes that both dropped the frame originally gave false parity.
+
Shared Profile amendment (2026-10-16):
[mechanical / sheet-metal reconciliation](FIRMAMENT-SHEET-METAL-SYNTAX-2026-10.md)
admits compact `Profile name = Rect2/Circle2/Slot2 { ... }` through the existing
diff --git a/docs/development/UI-SKETCHER-2026-10-20.md b/docs/development/UI-SKETCHER-2026-10-20.md
new file mode 100644
index 00000000..9440e6b0
--- /dev/null
+++ b/docs/development/UI-SKETCHER-2026-10-20.md
@@ -0,0 +1,174 @@
+# Profile workspace: first implementation and qualification
+
+## Result
+
+Helios now has a source-backed 2D Profile workspace. Its compiler service resolves
+the existing engineering Profile, exposes driving dimensions, and prepares ordinary
+structural source edits. The public SDK transports that projection; shared Telos
+renders it; Helios applies edits through its existing undo/build/draft transaction.
+There is no second saved sketch model, expression evaluator or constraint solver.
+
+The motivating workflow was exercised in the live browser: create a rectangular
+part, add four named corner openings with inward insets, resize the plate, drag a
+dimension, then undo that gesture once. The openings follow the driving dimensions
+and their identities and expressions remain intact. A duplicate opening is refused
+with `sketch-opening-overlap` and no source revision change.
+
+## Supported first slice
+
+- Rectangle, circle, slot and rounded-rectangle starters produce ordinary source:
+ shape, Profile and 6 mm Extrude.
+- Existing authored Profiles expose resolved local curves and their world frame.
+ Analytic geometry/provenance comes from the compiler. Browser curve sampling is
+ for display only.
+- Literal dimensions and directly referenced literal Static initializers can be
+ edited by typing or dragging. Labels identify shared Static parameters.
+- Formula, record-derived and typed-tolerance inputs remain read-only; source
+ navigation exposes their authored expression rather than overwriting intent.
+- A Model-level unrotated rectangular outer loop supports named circular openings
+ at its center, corners and edge midpoints. The compiler names/reuses the existing
+ center/size inputs and writes expressions for the requested relation.
+- Overlap, containment, invalid radius and conflicting shared-value requests are
+ rejected before returning an edit. Normal full build remains the solid authority;
+ later failure retains the application's existing revertible draft/last model.
+- Pan, zoom, Fit, keyboard dimension adjustment, source navigation, drag preview
+ coalescing, revision guards and cleanup are included.
+- Export's menu button is vertically centered alongside Build.
+
+The preview contract explicitly reports `ProfileResolvedNotBuilt`. A resolved 2D
+profile is not proof that an extrusion or any downstream feature can build.
+
+## Frame decision and discovered compiler defects
+
+Rejecting every `Concept Struct on XZ` was inherited admission debt, rather than a
+useful language rule. Local 2D layouts now select a right-handed construction frame:
+
+| Layout | Local X | Local Y | Normal |
+| --- | --- | --- | --- |
+| XY | world +X | world +Y | world +Z |
+| XZ | world +X | world +Z | world -Y |
+| YZ | world +Y | world +Z | world +X |
+
+Default and explicit XY retain identical STEP output in the witnesses. Arbitrary
+origins/orientations retain the existing traced Construction Plane workflow. This
+does not imply rotating typed spatial Concept members or admitting every other
+domain consumer. Unknown frames and unqualified mixed spatial layouts reject,
+including unused unknown placed layouts.
+
+Three compiler ownership gaps surfaced:
+
+1. Construction-guide admission read unbound Static dimension expressions. Build
+ now passes the same bound nominal-expression reader used by domain binding.
+2. Profile frame admission scanned token sequences and imposed XY. It now reads
+ the existing AST declaration/clauses and resolves a ConstructionPlane.
+3. Compose retained local Profile curves but discarded their resolved frame at
+ emission. Its existing placement contract now carries the inherited Base
+ Profile frame. Explicit legacy Placement still transports unplaced XY inputs.
+ Authored operands must share the resulting frame; a conflicting explicit
+ Placement cannot override an already oriented Profile.
+
+Compose's existing world-coordinate support adapters for Boss/Pocket/Hole/Slot/
+EdgeFinish are not qualified for inherited oriented frames and now reject that
+combination explicitly. Base/Add/Remove operate in one common frame. This is a
+bounded capability boundary, not an implicit XY substitution.
+
+The X4 f01 source and its explicit traced-plane reference originally matched while
+both emitted the wrong XY variant. Absolute bounds tests exposed this; route parity
+alone was insufficient. Before repair, XZ minimum was `[-15,-5,0]` where the simple
+asymmetric witness required `[-15,-6,-5]`. After repair, both f01 spellings require
+world bounds `[0,-30,0]..[60,0,40]`, enclosed volume 14250 mm³. Only f01's recorded
+oracle is regenerated for this intended orientation correction; its source is
+preserved. Existing XY geometry checks remain unchanged.
+
+## Qualification
+
+| Lane | Result |
+| --- | --- |
+| Release solution build | Passed |
+| Focused sketch/frame tests | 22 passed |
+| Fast Core lane, excluding SlowCorpus | 1,087 passed |
+| Full Release solution gate, one worker | 5,728 passed in 20 suites; no failures or skips |
+| Helios build and UI tests | Build passed; 104 tests passed |
+| Public SDK transport tests | 17 passed |
+| Shared Telos tests | 15 passed |
+| Cadmata client tests | 96 passed |
+| X4 authoring corpus | 32/32 passed, including chimera baseline parity |
+
+Commands used for the .NET gate:
+
+```powershell
+$env:MSBUILDDISABLENODEREUSE = '1'
+$env:DOTNET_PROCESSOR_COUNT = '2'
+dotnet build Aetheris.slnx -c Release -m:1 -nr:false -p:UseSharedCompilation=false
+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build --filter 'Category!=SlowCorpus'
+dotnet test Aetheris.slnx -c Release --no-build -m:1 -- RunConfiguration.MaxCpuCount=1
+```
+
+Build, corpus CLI invocations and SDK repack run serially to avoid DLL locks.
+The Firmament corpus test host peaked at about 2 GB and released its memory on
+exit; no claim of a memory-leak fix is made. Existing compiler/analyzer and WASM
+interop warnings remain; there were no build errors. The Helios bundle retains
+its existing large-chunk advisory.
+During development, a React hot-refresh invalidation reused a disposed workspace
+worker and required a page reload. Fresh startup and the final refreshed SDK
+passed the browser checks. That development lifecycle issue is recorded here;
+this pass does not claim to repair Helios hot-refresh lifecycle management.
+
+Kernel tests cover bounds, enclosed BRep volume, topology/provenance stability,
+XY STEP equality, common-frame removal, traced origins, mixed-frame rejection,
+four starter families, four-opening resize, refusal and preserved expressions.
+The browser witness also confirms the XZ normal `(0,-1,0)`.
+After the final SDK refresh, the live WASM compiler also built the oriented Compose
+witness without diagnostics. Build and Export both measured top 11 px, height
+30 px, center Y 26 px in the actual toolbar. The owned test tab and Vite process
+were closed after capture; no .NET/testhost processes remained.
+
+Evidence lives under ignored `artifacts/local/`:
+
+- `sketch-compose-before.log`: failing absolute frame witnesses before repair.
+- `sketch-frame-final.log`: focused kernel witnesses after repair.
+- `sketch-solution-build-final.log`, `sketch-fast-tests.log`, `sketch-full-tests.log`.
+- `sketch-x4-f01.log`, `sketch-x4-full.log`.
+- `sketch-helios-build-final.log`, `sketch-helios-tests-final.log`.
+- `sketch-sdk-tests.log`, `sketch-telos-tests.log`, `sketch-cadmata-tests.log`.
+- `sketcher/plate-workspace.png`, `sketcher/linked-opening-refusal.png`,
+ `sketcher/xz-workspace.png`, `sketcher/xz-compose-built.png`: actual browser captures.
+
+The BRep volume cross-check for the oriented nonconvex witnesses uses the existing
+enclosed mass-properties evaluation. This does not extend the separate exact-volume
+assertion recognizer's supported families.
+
+## Deliberate limits
+
+This is the first shape-and-dimension workspace, not completion of every sketching
+idea from the discussion. General cursor snaps, arbitrary reference expressions,
+polyline direct-distance entry, boundary-edit GUI tools and arbitrary trim/extend
+remain outside this slice. No simultaneous constraint solving was introduced.
+Editing included/generated recipe bodies requires an authored owner/provenance
+contract and is not inferred from expanded geometry. Profile selection requires a
+unique authored name. Opening clearance currently admits circular inner loops;
+noncircular inner-loop clearance refuses explicitly.
+
+The shared renderer and SDK are available to product hosts; this pass wires the
+workspace into Helios. It does not claim a new Cadmata sketch command or native
+desktop interaction qualification. Cadmata's existing unit suite is checked for
+compatibility with the shared package.
+
+The authoring contract and current boundaries are documented in
+[the public sketcher guide](../public/firmament/sketcher.md) and
+[syntax](../public/firmament/syntax.md).
+
+## Code review and verdict
+
+The pass adds no regex parser, whole-document dispatch route, source macro system
+or diagnostic fatality allowlist. Edit preparation uses existing AST-addressed
+operations and Profile admission. Unknown/unsupported frames do not fall back to
+XY. Compiler-owned messages and source spans are transported to the workspace;
+curve provenance may refer to lowered source, while control spans identify the
+authored expression for navigation. Browser preview results are revision-guarded
+and event listeners/timers are disposed with the workspace.
+
+**Success for this bounded first slice.** The four-opening workflow improves in
+the real Helios path, and both simple extrusion and Compose now preserve the
+qualified Profile frame. The deferred sketch tools and domain-specific oriented
+feature adapters listed above remain explicit follow-ups, not hidden support.
diff --git a/docs/public/firmament/boundaries.md b/docs/public/firmament/boundaries.md
index e75b0f6e..d20faeae 100644
--- a/docs/public/firmament/boundaries.md
+++ b/docs/public/firmament/boundaries.md
@@ -59,7 +59,7 @@ Polygon2<Explicit> Outline { vertices: vertices }
RegularPolygon2<6> Hex { center: [0mm,0mm] acrossFlats: 32mm rotation: 30deg }
```
-`rotation: Angle` rotates a shape in its local XY plane. Placement remains owned by the existing `Concept Struct ... on XY` / `Profile ... using ...` frame architecture; the shape declarations do not introduce a second frame system.
+`rotation: Angle` rotates a shape in its local 2D coordinates. Placement remains owned by `Concept Struct ... on XY/XZ/YZ` and `Profile ... using ...`, or by a traced Construction Plane; the shape declarations do not introduce a second frame system. XZ uses world +X/+Z with normal -Y; YZ uses +Y/+Z with normal +X. A plane-scoped 2D layout does not implicitly transform spatial semantic members. See [the sketch workspace](sketcher.md#planes).
Explicit Triangle2 and Polygon2 boundaries use their authored point coordinates.
A nonzero `rotation` on those variants is rejected; it previously disappeared.
diff --git a/docs/public/firmament/sketcher.md b/docs/public/firmament/sketcher.md
new file mode 100644
index 00000000..dac552c3
--- /dev/null
+++ b/docs/public/firmament/sketcher.md
@@ -0,0 +1,110 @@
+# Sketching in Helios
+
+The sketch workspace edits ordinary Firmament source. There is no separate saved
+sketch model, browser constraint solver or mesh-to-profile conversion.
+
+Open **Command palette → New sketch part** to start a rectangular profile and a
+6 mm extrusion. Circle, slot and rounded-rectangle sketch starters are also in the
+command palette. For an existing part, use **Sketch** above the viewport, or
+double-click its Profile/shape node in the graph. Choose the Profile when a guide
+is shared by more than one Profile.
+
+## Dimensions and navigation
+
+The workspace uses the Profile's local coordinates. Its header identifies the
+resolved plane, world origin and normal; the canvas shows local +X and +Y.
+Scroll to zoom, middle-drag or Alt-drag to pan, and use **Fit** to see the outline.
+Select a named shape in the inspector or click its center marker.
+
+Type a dimension in the inspector and press Enter or leave the field. Drag a
+gold dimension label for an approximate adjustment; type a number for the final
+size. Keyboard arrows on a dimension label change it by one displayed unit.
+Lengths display in millimetres and rotations in degrees. Slot **overall length**
+includes both semicircular ends.
+
+- A literal is a directly editable driving dimension.
+- A directly referenced literal `Static` is edited at its declaration. The UI
+ names that shared parameter, so other consumers changing is explicit.
+- An expression is read-only here. **Edit source** navigates to it; edit its
+ driving inputs in Parameters or Source. Dragging never replaces a formula or
+ typed tolerance with a literal.
+
+Drag previews resolve the Profile without constructing the solid. Releasing a
+drag or entering a dimension prepares one source transaction and invokes the
+normal engineering build. An invalid profile edit is refused without changing
+source. A later solid-build failure retains the previous geometry and the
+existing revertible draft. Source edits retain Monaco undo history.
+
+`ProfileResolvedNotBuilt` describes the preview's validation level. It does not
+mean an extrusion, revolve, loft or downstream feature has passed its build.
+
+## Mounting openings that follow their dimensions
+
+For a Profile whose explicit outer loop traces an unrotated Model-level Rect2,
+**Circular profile opening** offers its center, corners and edge midpoints.
+Choose the rectangle, anchor, inward X/Y insets and opening diameter, then
+**Add opening**. Inapplicable insets are disabled. For a four-hole plate, add one
+opening at each corner with the same insets.
+
+The operation shares the rectangle's driving values through named `Static`
+parameters. Literals/expressions are promoted when necessary; existing named
+inputs are reused. For example, the resulting relationship can read:
+
+```firmament
+Static OutlineCenterX: Length = 0mm
+Static OutlineCenterY: Length = 0mm
+Static OutlineWidth: Length = 80mm
+Static OutlineHeight: Length = 50mm
+Rect2 Outline {
+ center: [OutlineCenterX, OutlineCenterY]
+ size: [OutlineWidth, OutlineHeight]
+}
+Circle2 MountOpening {
+ center: [OutlineCenterX + (OutlineWidth / 2 - 8mm),
+ OutlineCenterY + (OutlineHeight / 2 - 8mm)]
+ diameter: 4mm
+}
+```
+
+This is dimensional dependence through existing compile-time values. It does
+not introduce an `Outline.Right.Offset(...)` expression or store sampled edge
+coordinates. The opening becomes an explicitly named inner Profile loop. It is
+a profile opening, rather than a drilled Hole feature with drill-point or
+counterbore semantics. The compiler rejects overlapping/touching circular
+openings and openings outside the rectangle. Complex inner-loop clearance and
+other reference families are not offered yet.
+
+## Planes
+
+Local 2D Concept layouts admit these right-handed principal frames when consumed
+by `Profile ... using Layout`:
+
+| Layout | Local +X | Local +Y | Extrusion +normal |
+| --- | --- | --- | --- |
+| `on XY` | world +X | world +Y | world +Z |
+| `on XZ` | world +X | world +Z | world -Y |
+| `on YZ` | world +Y | world +Z | world +X |
+
+Omitting `on` retains XY. Arbitrary origins/orientations use a traced
+Construction Plane. A principal-plane layout is a frame for local 2D guides and
+scalar data; it does not implicitly rotate typed 3D semantic members or override
+the admission rules of Sheet Metal, Assembly mates or other consumers.
+
+Extrude uses that resolved frame. Compose inherits its Base Profile frame and
+requires all authored Base/Add/Remove Profiles to share it. Legacy explicit
+Placement can transport unplaced XY Profiles; it cannot override a different
+oriented Profile. Oriented Compose with Boss/Pocket/Hole/Slot/EdgeFinish is
+explicitly rejected while those support adapters still assume world XY.
+
+## Current boundary
+
+This first workspace edits authored Rect2, Circle2, Slot2 and RoundedRect2 fields
+and displays the resolved line/arc/ellipse/cubic curves of other Profiles.
+Generated Template/Feature bodies do not become writable source through their
+expanded geometry. Profiles must have an unambiguous authored name in the
+document; edits do not reach into included files.
+
+General cursor snaps, arbitrary one-way geometric references, polyline distance
+entry, boundary-edit tools, arbitrary trim/extend and simultaneous constraint
+solving are not implemented in this first pass. Existing code-authored geometry
+continues to use its normal compiler owners.
diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.md
index d566e87b..c8d00fe6 100644
--- a/docs/public/firmament/syntax.md
+++ b/docs/public/firmament/syntax.md
@@ -12,6 +12,10 @@ make it legal in every other domain.
## A first part
+For visual profile authoring in Helios, use **Command palette → New sketch part**.
+The [sketch workspace](sketcher.md) edits the same dimensions and compile-time
+parameters described here; its 2D preview is followed by the normal solid build.
+
**Complete file — a plate with a through hole:**
```firmament
@@ -551,8 +555,13 @@ admit `rotation` in degrees; a rotation is redundant for a circle. Explicit
Triangle2 and Polygon2 variants use authored points directly and reject nonzero
rotation. Rotate those points or place a derived Profile with Curve2 instead.
These remain planar guides: trace a Profile
-and give it a material consumer to obtain a solid. Layout `on XY` is admitted;
-an unsupported `on XZ` does not silently change the plane. These forms do not
+and give it a material consumer to obtain a solid. Local 2D Concept layouts admit
+`on XY`, `on XZ` and `on YZ` through `Profile ... using Layout`. Their local axes
+are respectively world X/Y, X/Z and Y/Z; the right-handed normals are +Z, -Y and
++X. Extrude uses the resolved frame; Compose inherits its Base Profile frame and
+requires a common frame for Base/Add/Remove operands. Oriented Compose rejects
+Boss/Pocket/Hole/Slot/EdgeFinish while their support adapters require world XY.
+Typed spatial members require their own explicit frame workflow. These forms do not
promise arbitrary 2D Boolean operations, implicit sketch solving, or first-class
shape arguments to predicate Concepts. See [boundary details](boundaries.md)
for variant fields and exact curve families.
@@ -700,8 +709,10 @@ different reference types. `on` appears in several contexts; it is not one
universal placement operation. A profile context, Hole support, section frame
and Assembly attachment each have their own type and admission rules.
-Use only a plane or frame admitted by that consumer. Do not assume replacing
-`on XY` with `on XZ` rotates every downstream feature. Follow
+Use only a plane or frame admitted by that consumer. `Concept Struct ... on XZ`
+selects the frame for its local 2D guides when a Profile uses that layout; it does
+not transform unrelated spatial members or change another consumer's support.
+Follow
[Concept derivation](concept-derivation.md) and the consuming guide; unsupported
placement must reject rather than substitute XY.
diff --git a/docs/public/reference/diagnostics.md b/docs/public/reference/diagnostics.md
index 059ad6ed..1e6805f1 100644
--- a/docs/public/reference/diagnostics.md
+++ b/docs/public/reference/diagnostics.md
@@ -11,7 +11,7 @@ successful export. See [drawing generation](../drawings.md).
Generic V2 build/validation errors use structured objects with `code`, `severity`, `message`, `sourceFile`, optional `sourceSpan`, `line`, `column`, and `locationNote`. The existing `fatal` spelling means an error that prevents admission; `warning` remains nonfatal. Parser route metadata is for debugging. An enclosing-declaration span is explicitly labelled when the legacy producer supplied no precise original-source provenance. Monaco consumes the same compiler presentation. Specialized domain commands are not yet all migrated to this representation.
-Unknown canonical statements and Box fields are errors. `profile-layout-placement-unsupported` rejects unsupported Concept Struct layout planes instead of substituting XY. Use a traced Construction Plane for supported oriented profile workflows. `SemanticSourceNotFound` preserves the missing source and the provenance explanation. An accidental through-depth Pocket fails; explicit `end: ThroughAll` selects the admitted through cut. Box top-boundary Fillet with disjoint ThroughAll shaft/counterbore holes is supported; `CombinedFeatureInteractionUnsupported` identifies a hole touching the finish band or another hole. Unsupported combined selectors retain `CombinedFeatureSelectionLost` at the EdgeFinish declaration.
+Unknown canonical statements and Box fields are errors. Local 2D Concept layouts admit XY, XZ and YZ for Profile consumers. `profile-layout-placement-unsupported` rejects other layout selectors instead of substituting XY; `profile-layout-spatial-members-unsupported` identifies a non-XY layout mixing local guides with spatial semantic members. Use a traced Construction Plane for arbitrary supported orientations. `SemanticSourceNotFound` preserves the missing source and the provenance explanation. An accidental through-depth Pocket fails; explicit `end: ThroughAll` selects the admitted through cut. Box top-boundary Fillet with disjoint ThroughAll shaft/counterbore holes is supported; `CombinedFeatureInteractionUnsupported` identifies a hole touching the finish band or another hole. Unsupported combined selectors retain `CombinedFeatureSelectionLost` at the EdgeFinish declaration.
## Exact face grafts and subdivision meshes
diff --git a/fixtures/Regression/FrontendX0/unsupported-layout-frame.firmament b/fixtures/Regression/FrontendX0/unsupported-layout-frame.firmament
new file mode 100644
index 00000000..c78a0c8e
--- /dev/null
+++ b/fixtures/Regression/FrontendX0/unsupported-layout-frame.firmament
@@ -0,0 +1,18 @@
+Concept Struct Layout On MissingPlane {
+ Point2 A { Position: [0mm, 0mm] }
+ Point2 B { Position: [60mm, 0mm] }
+ Point2 C { Position: [60mm, 5mm] }
+ Point2 D { Position: [5mm, 5mm] }
+ Point2 E { Position: [5mm, 30mm] }
+ Point2 F { Position: [0mm, 30mm] }
+ Line2 AB { From: A; To: B }
+ Line2 BC { From: B; To: C }
+ Line2 CD { From: C; To: D }
+ Line2 DE { From: D; To: E }
+ Line2 EF { From: E; To: F }
+ Line2 FA { From: F; To: A }
+}
+Profile Outline Using Layout {
+ Loop Outer { AB |> BC |> CD |> DE |> EF |> FA |> Close }
+}
+Struct Bracket { Extrude Body { Profile: Outline; From: 0mm; To: 3mm } }
diff --git a/fixtures/Regression/FrontendX4/README.md b/fixtures/Regression/FrontendX4/README.md
index 66873b13..e4521da4 100644
--- a/fixtures/Regression/FrontendX4/README.md
+++ b/fixtures/Regression/FrontendX4/README.md
@@ -9,6 +9,11 @@ comes with a reference spelling that builds today, and the reference is the geom
Recorded at `0a72e6f1`: **13 of 32 checks pass.** The 13 are the 11 guards plus two diagnostic
cases (e02, f01). Every `fix` and `design` case fails, and so does the chimera.
+Principal-plane amendment (2026-10-19): f01's original source is retained and now
+must build in XZ. Its geometry oracle is an explicit traced Construction Plane
+with local axes +X/+Z and normal -Y. This admission change is recorded in the
+language decision register; an XZ layout is no longer a required rejection.
+
## Run
```sh
@@ -88,7 +93,7 @@ removes about 31 mm³.
| d05 | capability follow-up | #24 | F5 | Originally `CombinedFeatureSelectionLost` at (1,1) | Now builds the original source: 11 faces, 23 edges, 14 vertices; 4 fillet cylinders plus the hole wall |
| e01 | fix | X3 #13 | F21 | `pocket-missing-required-field` | `Pocket … End: ThroughAll` = `Remove … Role: ThroughCut` |
| e02 | diagnostic | X3 #13 | F21 | correct at (6,5) | Keep it |
-| f01 | diagnostic | X0 #5 | F9 | correct code at line 9, after `ConceptPathProfileNotAdmittedByCompose` noise | Keep it; drop the noise |
+| f01 | fix | X0 #5 | F9 | formerly rejected XZ layout | Admit and match the explicit oriented-plane reference |
| f02 | design | X3 #20 | F11 | `polygon2-variant-unsupported` | Inline `Points` list |
| f03 | diagnostic | X3 #20 | F11 | `ConceptPathProfileNotAdmittedByCompose` (1,1) | Endpoint diagnostic at the first Segment (5), or admit and add a reference |
| f04 | design | X3 #20 + X2 #9 | F11 F18 | `polygon2-variant-unsupported` | Inline `Points` with arithmetic |
diff --git a/fixtures/Regression/FrontendX4/cases/reference/f01-xz-layout.firmament b/fixtures/Regression/FrontendX4/cases/reference/f01-xz-layout.firmament
new file mode 100644
index 00000000..a1c77717
--- /dev/null
+++ b/fixtures/Regression/FrontendX4/cases/reference/f01-xz-layout.firmament
@@ -0,0 +1,19 @@
+Static Corners: Set<Point2> {
+ Heel => Point2(0mm, 0mm)
+ Toe => Point2(60mm, 0mm)
+ Lip => Point2(60mm, 5mm)
+ Inner => Point2(5mm, 5mm)
+ Top => Point2(5mm, 40mm)
+ Back => Point2(0mm, 40mm)
+}
+Concept Struct Layout {
+ Polygon2<Explicit> Outline { Vertices: Corners }
+}
+Concept Struct Orientation { Datum: Plane { Origin: [0mm,0mm,0mm]; Normal: [0,-1,0]; Up: [0,0,1] } }
+Construction Plane XZFrame { trace: Orientation.Datum }
+Profile Section using XZFrame { Loop Outer { Outline |> TraceLoop } }
+Struct Bracket {
+ Compose Body {
+ Base Stock { Profile: Section; From: 0mm; To: 30mm; Role: Stock }
+ }
+}
diff --git a/fixtures/Regression/FrontendX4/expected.json b/fixtures/Regression/FrontendX4/expected.json
index 3d4da2de..7996b65d 100644
--- a/fixtures/Regression/FrontendX4/expected.json
+++ b/fixtures/Regression/FrontendX4/expected.json
@@ -773,14 +773,35 @@
{
"id": "f01",
"file": "cases/f01-xz-layout.firmament",
- "kind": "diagnostic",
+ "kind": "fix",
"register": "X0 #5",
"findings": "F9",
- "expect": "invalid",
+ "expect": "valid",
"observedAt0a72e6f": "profile-layout-placement-unsupported at (9,1), preceded by ConceptPathProfileNotAdmittedByCompose",
- "note": "Stays rejected for the frame reason. Passes today; the extra ConceptPathProfileNotAdmittedByCompose noise ahead of it should go.",
- "code": "profile-layout-placement-unsupported",
- "line": 9
+ "note": "2026-10-19 principal-plane decision: original source retained; local X/Y map to world X/Z with normal -Y. Absolute bounds [0,-30,0]..[60,0,40] are checked in kernel tests as well as against the explicit traced-plane reference.",
+ "reference": "cases/reference/f01-xz-layout.firmament",
+ "geometry": {
+ "faces": 8,
+ "edges": 18,
+ "vertices": 12,
+ "bbox": [
+ [
+ 0,
+ -30,
+ 0
+ ],
+ [
+ 60,
+ 0,
+ 40
+ ]
+ ],
+ "assessment": "enclosed-manifold",
+ "surfaces": {
+ "plane": 8
+ },
+ "volume": 14250
+ }
},
{
"id": "f02",
diff --git a/fixtures/Regression/Sketcher/plate.firmament b/fixtures/Regression/Sketcher/plate.firmament
new file mode 100644
index 00000000..3476aa56
--- /dev/null
+++ b/fixtures/Regression/Sketcher/plate.firmament
@@ -0,0 +1,18 @@
+Model SketchPlate {
+ units: mm
+ Static Width: Length = 80mm
+ Static Height: Length = 50mm
+ Rect2 Outline { center: [0mm, 0mm] size: [Width, Height] }
+ Circle2 MountA { center: [-Width / 2 + 8mm, -Height / 2 + 8mm] diameter: 4mm }
+ Circle2 MountB { center: [Width / 2 - 8mm, -Height / 2 + 8mm] diameter: 4mm }
+ Circle2 MountC { center: [Width / 2 - 8mm, Height / 2 - 8mm] diameter: 4mm }
+ Circle2 MountD { center: [-Width / 2 + 8mm, Height / 2 - 8mm] diameter: 4mm }
+ Profile Section {
+ Loop Outer { Outline |> TraceLoop }
+ Loop MountA { MountA |> TraceLoop }
+ Loop MountB { MountB |> TraceLoop }
+ Loop MountC { MountC |> TraceLoop }
+ Loop MountD { MountD |> TraceLoop }
+ }
+ Extrude Body { profile: Section from: 0mm to: 6mm }
+}