Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Support construction-aware Firmament sketch editing

Yuechen Liabbebdead085
diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentIntelliDraftTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentIntelliDraftTests.cs
new file mode 100644
index 00000000..18714d18
--- /dev/null
+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentIntelliDraftTests.cs
@@ -0,0 +1,197 @@
+using Aetheris.Kernel.Firmament.Analysis;
+using Aetheris.Kernel.Firmament.FirmamentV2;
+
+namespace Aetheris.Kernel.Firmament.Tests;
+
+public class FirmamentIntelliDraftTests
+{
+ [Fact]
+ public void RetainedRectanglesResolveTheirSharedDimensionsThroughNormalCompilation()
+ {
+ var root = new DirectoryInfo(AppContext.BaseDirectory);
+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx"))) root = root.Parent;
+ var source = File.ReadAllText(Path.Combine(root!.FullName, "fixtures", "Regression", "IntelliDraft", "rectangles-l.firmament"));
+ var view = FirmamentIntelliDraft.Project(source, "rectangles.firmament");
+ Assert.Empty(view.Diagnostics);
+ Assert.Equal(2, view.Shapes.Count);
+ var resolved = ProfileAuthoringParser.ResolveNamedProfile(source, "section", out var diagnostics);
+ Assert.True(resolved is not null, string.Join(";", diagnostics));
+ var result = FirmamentBuildAndExport.CompileSource(source);
+ Assert.True(result.IsSuccess, string.Join(";", result.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(4416, new FirmamentMeasurements(result.Value).Volume().ValueMm3!.Value, 6);
+ }
+ private sealed class Draft
+ {
+ public string Source = "Model Part { units: mm }";
+ public FirmamentDraftConstruction View => FirmamentIntelliDraft.Project(Source, "draft.firmament");
+ public string Id(string name) => View.Elements.Single(e => e.Name == name).Id;
+ public void Add(FirmamentDraftOperation operation) => Source = FirmamentSketchService.Edit(Source, "draft.firmament", "0", new("construction", Construction: operation)).Text;
+ }
+
+ [Fact]
+ public void RectangleRelationshipsAndTracesSurviveUpstreamDimensionChanges()
+ {
+ var draft = new Draft(); draft.Add(new("layout", Name: "layout"));
+ draft.Add(new("rectangle", draft.Id("layout"), "outer", Width: 60, Height: 40));
+ draft.Add(new("rectangle", draft.Id("layout"), "notch", Reference: draft.Id("outer"), InsetX: 8));
+ Assert.Equal(2, draft.View.Shapes.Count);
+ Assert.DoesNotContain("Point2", draft.Source); Assert.DoesNotContain("Line2", draft.Source);
+ FirmamentDraftTrace Span(string reference, string from, string to)
+ {
+ Assert.Contains(draft.View.Spans, s => s.Reference == reference && s.From == from && s.To == to);
+ return new(reference, from, to, Connect: true);
+ }
+ var trace = new[] {
+ Span("outer.Bottom", "outer.BottomLeft", "outer.BottomRight"),
+ Span("outer.Right", "outer.BottomRight", "notch.BottomRight"),
+ Span("notch.Bottom", "notch.BottomLeft", "notch.BottomRight"),
+ Span("notch.Left", "notch.TopLeft", "notch.BottomLeft"),
+ Span("outer.Top", "notch.TopLeft", "outer.TopLeft"),
+ Span("outer.Left", "outer.TopLeft", "outer.BottomLeft") };
+ draft.Add(new("trace", draft.Id("layout"), "section", Trace: trace));
+ draft.Add(new("extrude", draft.Id("section"), "body", Length: 6));
+ GeometryMatches(draft.Source, "rectangles-l.firmament");
+ var before = FirmamentSketchService.Project(draft.Source, "draft.firmament", "0").Loops[0].Curves.Select(c => c.Id).ToArray();
+ var width = draft.View.Shapes.Single(s => s.Name == "outer").Controls.Single(c => c.Label == "Width");
+ draft.Source = FirmamentSketchService.Edit(draft.Source, "draft.firmament", "1", new("constructionDimensions", Changes: [new(width.Id, 80)])).Text;
+ Assert.Equal(72, draft.View.Shapes.Single(s => s.Name == "notch").Controls.Single(c => c.Label == "Width").Value);
+ draft.Add(new("parameter", draft.Id("notchWall"), Value: 10));
+ var built = FirmamentBuildAndExport.CompileSource(draft.Source);
+ Assert.True(built.IsSuccess, string.Join(";", built.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(6600, new FirmamentMeasurements(built.Value).Volume().ValueMm3!.Value, 6);
+ Assert.Equal(before, FirmamentSketchService.Project(draft.Source, "draft.firmament", "2").Loops[0].Curves.Select(c => c.Id));
+ var previous = draft.Source;
+ Assert.Throws<FirmamentLanguageEditException>(() => draft.Add(new("parameter", draft.Id("notchWall"), Value: 100)));
+ Assert.Equal(previous, draft.Source);
+ draft.Add(new("trace", draft.Id("layout"), "section", Trace: trace, TargetProfile: draft.Id("section")));
+ Assert.True(FirmamentBuildAndExport.CompileSource(draft.Source).IsSuccess);
+ }
+
+ [Fact]
+ public void WholeRectangleTracingRetainsTheShapeAndDoesNotInventPoints()
+ {
+ var draft = new Draft(); draft.Add(new("layout", Name: "layout", Plane: "XZ"));
+ draft.Add(new("rectangle", draft.Id("layout"), "plate", Width: 60, Height: 40));
+ draft.Add(new("trace", draft.Id("layout"), "section", Trace: [new("plate", WholeLoop: true)]));
+ draft.Add(new("extrude", draft.Id("section"), "body", Length: 6));
+ var built = FirmamentBuildAndExport.CompileSource(draft.Source); Assert.True(built.IsSuccess);
+ Assert.Equal([-30d, -6, -20], new FirmamentMeasurements(built.Value).Bounds!.MinimumMm);
+ Assert.Equal([30d, 0, 20], new FirmamentMeasurements(built.Value).Bounds!.MaximumMm);
+ Assert.Contains("Rect2 plate", draft.Source); Assert.Contains("plate |> TraceLoop", draft.Source);
+ Assert.DoesNotContain("Line2", draft.Source);
+ }
+
+ [Fact]
+ public void NamedLineConstructionTracesAnLWithoutFlatteningReferences()
+ {
+ var draft = new Draft();
+ draft.Add(new("layout", Name: "layout"));
+ var points = new[] { ("a", 0d, 0d), ("b", 60d, 0d), ("c", 60d, 8d), ("d", 8d, 8d), ("e", 8d, 40d), ("f", 0d, 40d) };
+ foreach (var (name, x, y) in points) draft.Add(new("point", draft.Id("layout"), name, X: x, Y: y));
+ var names = new[] { "bottom", "right", "ledge", "upright", "top", "left" };
+ for (var i = 0; i < 6; i++) draft.Add(new("line", draft.Id("layout"), names[i], From: points[i].Item1, To: points[(i + 1) % 6].Item1));
+ Assert.Equal("ConstructionResolvedNotTraced", draft.View.ValidationLevel);
+ Assert.Equal(6, draft.View.Guides.Count);
+ Assert.False(FirmamentBuildAndExport.CompileSource(draft.Source).IsSuccess);
+ draft.Add(new("trace", draft.Id("layout"), "section", Trace: names.Select(n => new FirmamentDraftTrace(n)).ToArray()));
+ draft.Add(new("extrude", draft.Id("section"), "body", Length: 6));
+ var built = FirmamentBuildAndExport.CompileSource(draft.Source);
+ Assert.True(built.IsSuccess, string.Join(";", built.Diagnostics.Select(d => d.Message)));
+ Assert.Equal(4416, new FirmamentMeasurements(built.Value).Volume().ValueMm3!.Value, 6);
+ Assert.Contains("from: a", draft.Source);
+ Assert.Contains("bottom |> right |> ledge", draft.Source);
+ Assert.All(FirmamentSketchService.Project(draft.Source, "draft.firmament", "1").Loops[0].Curves, c => Assert.NotNull(c.Provenance));
+ GeometryMatches(draft.Source, "named-lines-l.firmament");
+ var side = FirmamentBuildAndExport.CompileSource(draft.Source.Replace("on XY", "on XZ"));
+ Assert.True(side.IsSuccess);
+ Assert.Equal([0d, -6, 0], new FirmamentMeasurements(side.Value).Bounds!.MinimumMm);
+ Assert.Equal([60d, 0, 40], new FirmamentMeasurements(side.Value).Bounds!.MaximumMm);
+ }
+
+ [Fact]
+ public void ArcChordAndPathUseTheSameResolvedGeometryAsCode()
+ {
+ var draft = new Draft();
+ draft.Add(new("layout", Name: "layout"));
+ foreach (var (name, y) in new[] { ("center", 0d), ("lower", -15d), ("upper", 15d) })
+ draft.Add(new("point", draft.Id("layout"), name, Y: y));
+ draft.Add(new("circle", draft.Id("layout"), "rim", Radius: 15, From: "center"));
+ draft.Add(new("line", draft.Id("layout"), "chord", From: "upper", To: "lower"));
+ draft.Add(new("trace", draft.Id("layout"), "section", Trace: [new("rim", "lower", "upper", "arc"), new("chord")]));
+ draft.Add(new("extrude", draft.Id("section"), "body", Length: 6));
+ var result = FirmamentBuildAndExport.CompileSource(draft.Source);
+ Assert.True(result.IsSuccess, string.Join(";", result.Diagnostics.Select(d => d.Message)));
+ var dView = FirmamentSketchService.Project(draft.Source, "draft.firmament", "1");
+ var arc = Assert.Single(dView.Loops[0].Curves, c => c.Kind == "Arc");
+ Assert.Equal(15, arc.Radius);
+ Assert.Equal(Math.PI, arc.Sweep, 10);
+ Assert.Equal(4, new FirmamentMeasurements(result.Value).Topology.Faces);
+ GeometryMatches(draft.Source, "arc-chord-d.firmament");
+
+ var path = new Draft();
+ path.Add(new("path", Name: "outline"));
+ path.Add(new("step", path.Id("outline"), "bottom", "Line", Length: 40));
+ path.Add(new("step", path.Id("outline"), "right", "Line", Length: 20, Turn: 90));
+ path.Add(new("step", path.Id("outline"), "corner", "Arc", Radius: 10, Turn: 90));
+ path.Add(new("step", path.Id("outline"), "top", "Line", Length: 30));
+ path.Add(new("step", path.Id("outline"), "left", "Close"));
+ path.Add(new("trace", path.Id("outline"), "section"));
+ path.Add(new("extrude", path.Id("section"), "body", Length: 2));
+ var built = FirmamentBuildAndExport.CompileSource(path.Source);
+ Assert.True(built.IsSuccess, string.Join(";", built.Diagnostics.Select(d => d.Message)));
+ var pathView = FirmamentSketchService.Project(path.Source, "draft.firmament", "1");
+ Assert.Equal(5, pathView.Loops[0].Curves.Count);
+ var corner = Assert.Single(pathView.Loops[0].Curves, c => c.Kind == "Arc");
+ Assert.Equal(10, corner.Radius);
+ Assert.Equal(Math.PI / 2, corner.Sweep, 10);
+ Assert.Equal(7, new FirmamentMeasurements(built.Value).Topology.Faces);
+ GeometryMatches(path.Source, "line-arc-path.firmament");
+ }
+
+ [Fact]
+ public void FailedTraceAndInvalidInputDoNotChangeConstruction()
+ {
+ var draft = new Draft(); draft.Add(new("path", Name: "outline"));
+ draft.Add(new("step", draft.Id("outline"), "bottom", "Line"));
+ var before = draft.Source;
+ Assert.Throws<FirmamentLanguageEditException>(() => draft.Add(new("trace", draft.Id("outline"), "section")));
+ Assert.Equal(before, draft.Source);
+ Assert.Throws<FirmamentLanguageEditException>(() => draft.Add(new("step", draft.Id("outline"), "bad", "Arc", Radius: -2)));
+ Assert.Throws<FirmamentLanguageEditException>(() => draft.Add(new("path", Name: "bad } Model Inject {")));
+ }
+
+ [Fact]
+ public void PointAndPathDimensionsEditUpstreamWithoutFlatteningReferences()
+ {
+ var draft = new Draft(); draft.Add(new("layout", Name: "layout"));
+ draft.Add(new("point", draft.Id("layout"), "a"));
+ draft.Add(new("point", draft.Id("layout"), "b", X: 40));
+ draft.Add(new("line", draft.Id("layout"), "edge", From: "a", To: "b"));
+ draft.Add(new("movePoint", draft.Id("b"), X: 50));
+ Assert.Equal(50, draft.View.Guides.Single().Points[1][0]);
+ Assert.Contains("to: b", draft.Source);
+ draft.Add(new("path", Name: "outline"));
+ draft.Add(new("step", draft.Id("outline"), "bottom", "Line"));
+ draft.Add(new("dimension", draft.Id("bottom"), Field: "length", Value: 60));
+ Assert.Equal(60, draft.View.Guides.Single(g => g.Name == "outline.bottom").Points[1][0]);
+ var before = draft.Source;
+ Assert.Throws<FirmamentLanguageEditException>(() => draft.Add(new("dimension", draft.Id("bottom"), Field: "length", Value: -2)));
+ Assert.Equal(before, draft.Source);
+ }
+
+ private static void GeometryMatches(string authored, string fixture)
+ {
+ var root = new DirectoryInfo(AppContext.BaseDirectory);
+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx"))) root = root.Parent;
+ Assert.NotNull(root);
+ var reference = FirmamentBuildAndExport.CompileSource(File.ReadAllText(Path.Combine(root.FullName, "fixtures", "Regression", "IntelliDraft", fixture)));
+ var actual = FirmamentBuildAndExport.CompileSource(authored);
+ Assert.True(reference.IsSuccess); Assert.True(actual.IsSuccess);
+ var a = new FirmamentMeasurements(actual.Value); var b = new FirmamentMeasurements(reference.Value);
+ Assert.Equal(b.Topology, a.Topology);
+ Assert.Equal(b.Body.Geometry.Curves.Select(c => c.Value.ToString()).Order(), a.Body.Geometry.Curves.Select(c => c.Value.ToString()).Order());
+ Assert.Equal(b.Body.Geometry.Surfaces.Select(c => c.Value.ToString()).Order(), a.Body.Geometry.Surfaces.Select(c => c.Value.ToString()).Order());
+ Assert.Equal(b.Body.Topology.Vertices.Select(v => b.Body.TryGetVertexPoint(v.Id, out var p) ? p.ToString() : "missing").Order(),
+ a.Body.Topology.Vertices.Select(v => a.Body.TryGetVertexPoint(v.Id, out var p) ? p.ToString() : "missing").Order());
+ }
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentDomainBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentDomainBinding.cs
index bac36b78..672bcf0e 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentDomainBinding.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentDomainBinding.cs
@@ -62,6 +62,8 @@ public sealed class FirmamentDomainBinding
}
public ExpressionSyntax Nominal(ExpressionSyntax expression) => values.NominalExpression(expression);
+ internal (Dictionary<string, (double X, double Y)> Points, Dictionary<string, Materializer.LineArcProfileCurve2D> Guides, IReadOnlyList<string> Diagnostics)
+ InspectConstruction() => ProfileAuthoringParser.InspectConstruction(Source, values);
public Materializer.ResolvedProfile2D? ResolveProfile(string name,out IReadOnlyList<string> diagnostics) =>
ProfileAuthoringParser.ResolveNamedProfileCore(Source,name,new(StringComparer.Ordinal),out diagnostics,values);
public bool OwnsConstruction(DeclarationSyntax declaration) => ClosedBoundary2Authoring.IsBoundaryType(declaration.Type.Name.Text)
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentIntelliDraft.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentIntelliDraft.cs
new file mode 100644
index 00000000..3b39f097
--- /dev/null
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentIntelliDraft.cs
@@ -0,0 +1,277 @@
+using System.Globalization;
+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;
+using Aetheris.Kernel.Firmament.Materializer;
+
+namespace Aetheris.Kernel.Firmament.FirmamentV2;
+
+public sealed record FirmamentDraftElement(string Id, string Name, string Kind, string? Parent,
+ FirmamentOutlineSpan Span, IReadOnlyList<FirmamentDraftField> Fields);
+public sealed record FirmamentDraftField(string Name, string Value, double? Number, string? Unit, bool Editable);
+public sealed record FirmamentDraftPoint(string Name, double X, double Y);
+public sealed record FirmamentDraftConstruction(IReadOnlyList<FirmamentDraftElement> Elements,
+ IReadOnlyList<FirmamentDraftPoint> Points, IReadOnlyList<FirmamentSketchCurve> Guides,
+ IReadOnlyList<FirmamentOutlineDiagnostic> Diagnostics, string ValidationLevel)
+{
+ public IReadOnlyList<FirmamentDraftFrame> Frames { get; init; } = [];
+ public IReadOnlyList<FirmamentSketchShape> Shapes { get; init; } = [];
+ public IReadOnlyList<FirmamentDraftSpan> Spans { get; init; } = [];
+}
+public sealed record FirmamentDraftSpan(string Id, string Owner, string Reference, string From, string To, FirmamentSketchCurve Curve);
+public sealed record FirmamentDraftFrame(string Owner, FirmamentSketchFrame Frame);
+public sealed record FirmamentDraftTrace(string Reference, string? From = null, string? To = null,
+ string? Alias = null, bool Reverse = false, bool Connect = false, bool WholeLoop = false);
+public sealed record FirmamentDraftOperation(string Action, string? Parent = null, string? Name = null,
+ string? Kind = null, string Plane = "XY", double X = 0, double Y = 0, double Length = 40,
+ double Radius = 10, double Turn = 0, string? From = null, string? To = null,
+ IReadOnlyList<FirmamentDraftTrace>? Trace = null, string? Field = null, double Value = 0,
+ double Width = 60, double Height = 40, string? Reference = null, double InsetX = 8, double InsetY = 8,
+ bool SharedInset = true, string? TargetProfile = null);
+
+/// <summary>Bounded source transactions for construction, trace and extrusion. Open construction is
+/// explicitly not an admitted part. All geometry comes from the existing Profile binding owner.</summary>
+public static class FirmamentIntelliDraft
+{
+ public static FirmamentDraftConstruction Project(string source, string document)
+ {
+ var parsed = FirmamentSyntaxParser.Parse(source, document);
+ var declarations = FirmamentLanguageOutlineService.Declarations(parsed);
+ FirmamentDraftField Field(FieldSyntax f)
+ {
+ var unit = FirmamentSyntaxValues.TryMeasure(f.Value, "deg", out var value) ? "deg"
+ : FirmamentSyntaxValues.TryMeasure(f.Value, "mm", out value) ? "mm" : null;
+ return new(f.Name.Text, source.Substring(f.Value.Span.Start, f.Value.Span.Length), unit is null ? null : value,
+ unit, unit is not null && FirmamentSketchService.Literal(f.Value));
+ }
+ var elements = declarations.Where(d => d.Syntax.Type.Name.Text is "Model" or "Struct" or "Static" or "Rect2" or "Point2" or "Line2" or "Circle2" or "Path" or "Line" or "Arc" or "Close" or "Profile" or "Extrude")
+ .Select(d => new FirmamentDraftElement(d.Id, d.Syntax.Name?.Text ?? d.Id, d.Syntax.Type.Name.Text, d.ParentId,
+ new(d.Syntax.Span.Start, d.Syntax.Span.Length), (d.Syntax.Body?.Statements.OfType<FieldSyntax>() ?? [])
+ .Select(Field).Concat(d.Syntax.Initializer is { } initial ? [new FirmamentDraftField("value", source.Substring(initial.Span.Start, initial.Span.Length),
+ FirmamentSyntaxValues.TryMeasure(initial, "mm", out var number) ? number : null, "mm", FirmamentSketchService.Literal(initial))] : []).ToArray())).ToArray();
+ var diagnostics = parsed.Diagnostics.Where(d => d.Severity is "error" or "fatal")
+ .Select(d => new FirmamentOutlineDiagnostic("error", d.Code, d.Message, new(d.SourceSpan.Start, d.SourceSpan.Length))).ToList();
+ var binding = new FirmamentDomainBinding(source, document, "Model", new HashSet<string>());
+ diagnostics.AddRange(binding.Diagnostics.Where(d => d.Severity is "error" or "fatal")
+ .Select(d => new FirmamentOutlineDiagnostic("error", d.Code, d.Message,
+ d.SourceSpan is { } s ? new(s.Start, s.Length) : null)));
+ if (diagnostics.Count > 0) return new(elements, [], [], diagnostics, "Unresolved");
+ var duplicate = elements.Where(e => e.Kind is "Rect2" or "Point2" or "Line2" or "Circle2" or "Path")
+ .GroupBy(e => e.Name).FirstOrDefault(g => g.Count() > 1);
+ if (duplicate is not null)
+ return new(elements, [], [], [new("error", "draft-guide-ambiguous", $"Construction preview requires an unambiguous guide name: '{duplicate.Key}'.", duplicate.First().Span)], "Unresolved");
+ var bound = binding.InspectConstruction();
+ foreach (var code in bound.Diagnostics)
+ diagnostics.Add(new("error", code.Split(':')[0], $"Construction could not resolve: {code}. Check the named guide or Path step. Location is the enclosing Model; the resolver did not supply a more precise source span.", elements.FirstOrDefault(e => e.Kind == "Model")?.Span));
+ var curves = bound.Guides.Select(g =>
+ {
+ var owner = elements.FirstOrDefault(e => e.Name == g.Key || g.Key.StartsWith(e.Name + ".", StringComparison.Ordinal) && e.Kind is "Path" or "Rect2");
+ var span = owner is null ? "unavailable: expanded construction" : $"{document}:{owner.Span.Start}:{owner.Span.Length}";
+ return FirmamentSketchService.Curve(new(g.Key, g.Value,
+ new("construction:" + g.Key, "construction:" + g.Key, span, "ConstructionGuide", "Local2D")));
+ }).ToArray();
+ var frames = new List<FirmamentDraftFrame>();
+ foreach (var layout in elements.Where(e => e.Kind == "Struct"))
+ {
+ var frameDiagnostics = new List<string>();
+ var frame = ProfileAuthoringParser.ResolveNamedConstructionPlane(binding.Source, layout.Name, frameDiagnostics);
+ if (frame is not null) frames.Add(new(layout.Id, new(layout.Name,
+ [frame.Origin.X, frame.Origin.Y, frame.Origin.Z], [frame.AxisX.X, frame.AxisX.Y, frame.AxisX.Z],
+ [frame.AxisY.X, frame.AxisY.Y, frame.AxisY.Z], [frame.AxisZ.X, frame.AxisZ.Y, frame.AxisZ.Z])));
+ }
+ var spans = ProfileAuthoringParser.ConstructionSpans(bound.Points, bound.Guides).Select(s =>
+ {
+ var owner = elements.FirstOrDefault(e => s.Guide.StartsWith(e.Name + ".", StringComparison.Ordinal) && e.Kind == "Rect2");
+ var id = s.Guide + ":" + s.From + ":" + s.To;
+ var parentCurve = curves.Single(c => c.Name == s.Guide);
+ return new FirmamentDraftSpan(id, owner?.Id ?? "", s.Guide, s.From, s.To,
+ FirmamentSketchService.Curve(new(id, s.Geometry, parentCurve.Provenance! with { StableId = "construction-span:" + id })));
+ }).Where(s => s.Owner.Length > 0).ToArray();
+ return new(elements, bound.Points.Select(p => new FirmamentDraftPoint(p.Key, p.Value.X, p.Value.Y)).ToArray(),
+ curves, diagnostics, diagnostics.Count == 0 ? "ConstructionResolvedNotTraced" : "Unresolved")
+ { Frames = frames, Shapes = FirmamentSketchService.ConstructionShapes(source, document, "construction"), Spans = spans };
+ }
+
+ public static FirmamentLanguageEdit Edit(string source, string document, string revision, FirmamentDraftOperation request)
+ {
+ var view = Project(source, document);
+ var operations = new List<FirmamentLanguageEditOperation>();
+ FirmamentDraftElement Owner(params string[] kinds) => view.Elements.SingleOrDefault(e => e.Id == request.Parent && kinds.Contains(e.Kind))
+ ?? throw Refuse("draft-owner-required", "Choose the owning Model, construction layout or Path.");
+ string Name()
+ {
+ var name = FirmamentLanguageEditService.RequireIdentifier(request.Name, "construction name");
+ if (view.Elements.Any(e => e.Name == name && e.Id != request.TargetProfile)) throw Refuse("draft-name-exists", $"'{name}' already exists. Choose a stable, unique name.");
+ return name;
+ }
+ string Point(string? name) => view.Points.Any(p => p.Name == name) ? name! : throw Refuse("draft-point-required", $"Choose a resolved named point, instead of '{name}'.");
+ void Insert(string parent, string text) => operations.Add(new("insertDeclaration") { Parent = parent, Source = text });
+ var model = view.Elements.SingleOrDefault(e => e.Kind == "Model")
+ ?? throw Refuse("draft-model-required", "IntelliDraft requires one authored Model.");
+ switch (request.Action)
+ {
+ case "rectangle":
+ var rectangleOwner = Owner("Struct");
+ var rectangleName = Name();
+ var usedNames = view.Elements.Select(e => e.Name).ToHashSet(StringComparer.Ordinal);
+ string Parameter(string stem, string value, string parent)
+ {
+ var fresh = stem; for (var i = 2; !usedNames.Add(fresh); i++) fresh = stem + i;
+ Insert(parent, $"Static {fresh}: Length = {value}"); return fresh;
+ }
+ string cx, cy, width, height;
+ if (request.Reference is null)
+ {
+ cx = Parameter(rectangleName + "CenterX", Mm(request.X), model.Id);
+ cy = Parameter(rectangleName + "CenterY", Mm(request.Y), model.Id);
+ width = Parameter(rectangleName + "Width", Positive(request.Width) + "mm", model.Id);
+ height = Parameter(rectangleName + "Height", Positive(request.Height) + "mm", model.Id);
+ }
+ else
+ {
+ var reference = view.Shapes.SingleOrDefault(s => s.Id == request.Reference && s.Kind == "Rect2")
+ ?? throw Refuse("draft-rectangle-required", "Choose a retained Rect2 as the reference.");
+ var authored = FirmamentLanguageOutlineService.Declarations(FirmamentSyntaxParser.Parse(source)).Single(d => d.Id == reference.Id);
+ if (authored.ParentId != rectangleOwner.Id || reference.Controls.Any(c => c.Unit == "deg" && c.Value != 0))
+ throw Refuse("draft-inset-frame-unsupported", "Inset rectangles currently require an unrotated reference in the same Concept Struct.");
+ var ix = request.InsetX; var iy = request.SharedInset ? ix : request.InsetY;
+ var referenceWidth = reference.Controls.Single(c => c.Label == "Width").Value;
+ var referenceHeight = reference.Controls.Single(c => c.Label == "Height").Value;
+ if (!(ix > 0 && ix < referenceWidth && iy > 0 && iy < referenceHeight))
+ throw Refuse("draft-inset-invalid", "Insets must be positive and smaller than the reference width and height.");
+ string[] Share(string fieldName, string[] suffixes)
+ {
+ var field = authored.Syntax.Body!.Statements.OfType<FieldSyntax>().Single(f => FirmamentSyntaxFields.SameField(f.Name.Text, fieldName));
+ if (field.Value is not SequenceSyntax { Kind: SequenceKind.List } values || values.Items.Count != 2)
+ throw Refuse("draft-reference-expression-unsupported", "The reference rectangle needs an authored two-component center and size.");
+ var names = values.Items.Select((a, i) => a.Value is ReferenceSyntax ? source.Substring(a.Value.Span.Start, a.Value.Span.Length)
+ : Parameter(reference.Name + suffixes[i], source.Substring(a.Value.Span.Start, a.Value.Span.Length), model.Id)).ToArray();
+ operations.Add(new("setField") { Node = reference.Id, Field = field.Name.Text, Value = $"[{names[0]}, {names[1]}]" });
+ return names;
+ }
+ var center = Share("center", ["CenterX", "CenterY"]); var size = Share("size", ["Width", "Height"]);
+ var insetX = Parameter(rectangleName + (request.SharedInset ? "Wall" : "InsetX"), Mm(ix), model.Id);
+ var insetY = request.SharedInset ? insetX : Parameter(rectangleName + "InsetY", Mm(iy), model.Id);
+ cx = center[0] + " + " + insetX + " / 2"; cy = center[1] + " + " + insetY + " / 2";
+ width = size[0] + " - " + insetX; height = size[1] + " - " + insetY;
+ }
+ Insert(rectangleOwner.Id, $"Rect2 {rectangleName} {{ center: [{cx}, {cy}]; size: [{width}, {height}] }}");
+ break;
+ case "parameter":
+ var parameter = Owner("Static");
+ var parameterField = parameter.Fields.SingleOrDefault(f => f.Name == "value" && f.Editable && f.Number is not null)
+ ?? throw Refuse("draft-parameter-driven", "Choose a literal Length parameter. Expressions and typed tolerances retain their authoring inputs.");
+ operations.Add(new("setValue") { Node = parameter.Id, Value = Mm(request.Value) });
+ break;
+ case "movePoint":
+ var point = Owner("Point2");
+ var syntax = FirmamentLanguageOutlineService.Declarations(FirmamentSyntaxParser.Parse(source)).Single(d => d.Id == point.Id).Syntax;
+ var position = syntax.Body?.Statements.OfType<FieldSyntax>().SingleOrDefault(f => FirmamentSyntaxFields.SameField(f.Name.Text, "Position"));
+ if (position?.Value is not SequenceSyntax { Kind: SequenceKind.List } list || list.Items.Count != 2 || list.Items.Any(a => !FirmamentSketchService.Literal(a.Value)))
+ throw Refuse("draft-point-driven", "This point is driven by expressions. Edit its driving parameters; moving it will not replace those relationships.");
+ operations.Add(new("setField") { Node = point.Id, Field = position.Name.Text, Value = $"[{Mm(request.X)}, {Mm(request.Y)}]" });
+ break;
+ case "dimension":
+ var dimensionOwner = Owner("Line", "Arc", "Circle2", "Path", "Extrude");
+ var field = dimensionOwner.Fields.SingleOrDefault(f => f.Name == request.Field && f.Editable)
+ ?? throw Refuse("draft-dimension-driven", "Choose an authored literal dimension. Expressions retain their upstream relationships.");
+ operations.Add(new("setField") { Node = dimensionOwner.Id, Field = field.Name, Value = Number(request.Value) + field.Unit });
+ break;
+ case "layout":
+ if (request.Plane is not ("XY" or "XZ" or "YZ")) throw Refuse("draft-plane-required", "Choose XY, XZ or YZ.");
+ Insert(model.Id, $"Concept Struct {Name()} on {request.Plane} {{ }}");
+ break;
+ case "point":
+ Insert(Owner("Struct").Id, $"Point2 {Name()} {{ position: [{Mm(request.X)}, {Mm(request.Y)}] }}");
+ break;
+ case "line":
+ Insert(Owner("Struct").Id, $"Line2 {Name()} {{ from: {Point(request.From)}; to: {Point(request.To)} }}");
+ break;
+ case "circle":
+ Insert(Owner("Struct").Id, $"Circle2 {Name()} {{ center: {Point(request.From)}; radius: {Positive(request.Radius)}mm }}");
+ break;
+ case "path":
+ Insert(model.Id, $"Path {Name()} {{ start: Point2({Mm(request.X)}, {Mm(request.Y)}); heading: {Number(request.Turn)}deg }}");
+ break;
+ case "step":
+ var path = Owner("Path");
+ if (view.Elements.Any(e => e.Parent == path.Id && e.Kind == "Close"))
+ throw Refuse("draft-path-closed", "This Path is closed. Undo Close before appending a step.");
+ var stepName = Name();
+ Insert(path.Id, request.Kind switch
+ {
+ "Line" => $"Line {stepName} {{ length: {Positive(request.Length)}mm; turn: {Number(request.Turn)}deg }}",
+ "Arc" => $"Arc {stepName} {{ radius: {Positive(request.Radius)}mm; turn: {Number(request.Turn)}deg }}",
+ "Close" => $"Close {stepName}",
+ _ => throw Refuse("draft-step-required", "Choose Line, Arc or Close.")
+ });
+ break;
+ case "trace":
+ var owner = Owner("Struct", "Path");
+ var name = Name();
+ string? after = null;
+ if (request.TargetProfile is not null)
+ {
+ var target = view.Elements.SingleOrDefault(e => e.Id == request.TargetProfile && e.Kind == "Profile" && e.Parent == model.Id && e.Name == name)
+ ?? throw Refuse("draft-profile-required", "Choose the authored Profile being replaced.");
+ after = view.Elements.LastOrDefault(e => e.Parent == model.Id && e.Span.Start < target.Span.Start)?.Id;
+ operations.Add(new("removeDeclaration") { Node = target.Id });
+ }
+ void Profile(string text) => operations.Add(new("insertDeclaration") { Parent = model.Id, Source = text, After = after, First = request.TargetProfile is not null && after is null });
+ if (owner.Kind == "Path") Profile($"Profile {name} from {owner.Name};");
+ else
+ {
+ var entries = request.Trace ?? [];
+ if (entries.Count == 0) throw Refuse("draft-trace-empty", "Add guides in boundary order before tracing.");
+ (double X, double Y)? previous = null;
+ string Entry(FirmamentDraftTrace entry)
+ {
+ if (entry.WholeLoop)
+ {
+ if (entries.Count != 1 || !view.Shapes.Any(s => s.Name == entry.Reference && s.Kind == "Rect2"))
+ throw Refuse("draft-whole-loop-required", "A complete rectangle outline must be the only entry in this outer trace.");
+ return entry.Reference + " |> TraceLoop";
+ }
+ if (!view.Guides.Any(g => g.Name == entry.Reference)) throw Refuse("draft-guide-required", $"Unresolved guide '{entry.Reference}'.");
+ if (entry.Connect)
+ {
+ var start = view.Points.SingleOrDefault(p => p.Name == entry.From); var end = view.Points.SingleOrDefault(p => p.Name == entry.To);
+ if (start is null || end is null) throw Refuse("draft-point-required", "Select a span with named construction endpoints.");
+ if (previous is { } p && ProfileAuthoringParser.SameConstructionPoint(p, (end.X, end.Y))) (start, end) = (end, start);
+ if (previous is { } current && !ProfileAuthoringParser.SameConstructionPoint(current, (start.X, start.Y)))
+ throw Refuse("draft-trace-disconnected", $"'{entry.Reference}' does not join the preceding span. Select a connected span or reorder the trace.");
+ if (entry.Alias is null && entries.Count(e => e.Reference == entry.Reference) > 1)
+ throw Refuse("draft-edge-name-required", $"Give the separate spans of '{entry.Reference}' distinct edge names.");
+ entry = entry with { From = start.Name, To = end.Name, Alias = entry.Alias ?? entry.Reference.Replace('.', '_') };
+ }
+ previous = entry.To is null ? null : view.Points.Where(p => p.Name == entry.To).Select(p => ((double X, double Y)?)(p.X, p.Y)).SingleOrDefault();
+ var text = entry.Reference;
+ if (entry.From is not null || entry.To is not null) text += $" from {Point(entry.From)} to {Point(entry.To)}";
+ if (entry.Alias is not null) text += " as " + FirmamentLanguageEditService.RequireIdentifier(entry.Alias, "edge alias");
+ return text + (entry.Reverse ? " |> Reverse" : "");
+ }
+ Profile($"Profile {name} using {owner.Name} {{ Loop Outer {{ {string.Join(" |> ", entries.Select(Entry))}{(entries.Count == 1 && entries[0].WholeLoop ? "" : " |> Close")} }} }}");
+ }
+ break;
+ case "extrude":
+ var profile = Owner("Profile");
+ Insert(model.Id, $"Extrude {Name()} {{ profile: {profile.Name}; from: 0mm; to: {Positive(request.Length)}mm }}");
+ break;
+ default: throw Refuse("draft-action-unknown", $"Unknown IntelliDraft operation '{request.Action}'.");
+ }
+ var result = FirmamentLanguageEditService.Apply(source, document, revision, operations);
+ var candidate = Project(result.Text, document);
+ if (candidate.Diagnostics.FirstOrDefault(d => d.Severity is "error" or "fatal") is { } diagnostic)
+ throw Refuse(diagnostic.Code, diagnostic.Message);
+ if (request.Action == "trace")
+ {
+ var projected = FirmamentSketchService.Project(result.Text, document, revision);
+ if (projected.Diagnostics.FirstOrDefault(d => d.Severity is "error" or "fatal") is { } error) throw Refuse(error.Code, error.Message);
+ if (projected.ValidationLevel != "ProfileResolvedNotBuilt") throw Refuse("draft-trace-unresolved", "The trace did not resolve to a closed Profile.");
+ }
+ return result;
+ }
+ private static string Number(double value) => double.IsFinite(value) ? value.ToString("R", CultureInfo.InvariantCulture)
+ : throw Refuse("draft-number-invalid", "Use a finite dimension or angle.");
+ private static string Positive(double value) => value > 0 ? Number(value) : throw Refuse("draft-size-invalid", "Use a positive dimension.");
+ private static string Mm(double value) => Number(value) + "mm";
+ private static FirmamentLanguageEditException Refuse(string code, string message) => new(code, message);
+}
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.cs
index cd8c14b4..dafbc4a1 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.cs
@@ -691,7 +691,7 @@ public static partial class FirmamentLanguageEditService
return trimmed;
}
- private static string RequireIdentifier(string? value, string what)
+ internal static string RequireIdentifier(string? value, string what)
{
if (value is null || !Identifier.IsMatch(value))
throw new FirmamentLanguageEditException("edit-invalid-name", $"'{value}' is not a valid {what}: use letters, digits and _, starting with a letter.");
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSemanticValues.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSemanticValues.cs
index 489bd7e7..b18c7250 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSemanticValues.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSemanticValues.cs
@@ -47,11 +47,12 @@ public static class FirmamentSemanticValues
public static IReadOnlyList<SemanticValue> FromProfilesAndConceptPaths(string source, string sourceIdentity = "<memory>", ICollection<string>? reportedDiagnostics = null)
{
var expansionDiagnostics = new List<string>();
- var expansion = FirmamentV2TemplateExpansion.Expand(source, expansionDiagnostics);
+ var compileTime = new FirmamentCompileTimeValues(source);
+ var expansion = FirmamentV2TemplateExpansion.Expand(source, expansionDiagnostics, compileTime);
foreach (var diagnostic in expansionDiagnostics) reportedDiagnostics?.Add(diagnostic);
var expanded = expansion?.Source ?? source;
var bindDiagnostics = new List<string>();
- var profiles = ProfileAuthoringParser.BindPathDerivedProfiles(expanded, bindDiagnostics);
+ var profiles = ProfileAuthoringParser.BindPathDerivedProfiles(expanded, bindDiagnostics, compileTime);
foreach (var diagnostic in bindDiagnostics) reportedDiagnostics?.Add(diagnostic);
var inspections = ProfileAuthoringParser.InspectConceptPaths(source);
var values = new List<SemanticValue>();
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSketch.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSketch.cs
index b33fc006..69f0576d 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSketch.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentSketch.cs
@@ -18,11 +18,15 @@ public sealed record FirmamentSketch(string Version, string Document, string Rev
IReadOnlyList<FirmamentSketchChoice> Profiles, IReadOnlyList<FirmamentSketchChoice> EmptyModels,
IReadOnlyList<FirmamentSketchChoice> OpeningReferences,
FirmamentSketchFrame? Frame, IReadOnlyList<FirmamentSketchLoop> Loops, IReadOnlyList<FirmamentSketchShape> Shapes,
- IReadOnlyList<FirmamentOutlineDiagnostic> Diagnostics, string ValidationLevel);
+ IReadOnlyList<FirmamentOutlineDiagnostic> Diagnostics, string ValidationLevel)
+{
+ public FirmamentDraftConstruction? Construction { get; init; }
+}
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);
+ string? Reference = null, string? Anchor = null, double Diameter = 4, double Width = 80, double Height = 50,
+ FirmamentDraftOperation? Construction = null);
/// <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>
@@ -35,7 +39,10 @@ public static class FirmamentSketchService
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)
+ internal static IReadOnlyList<FirmamentSketchShape> ConstructionShapes(string source, string document, string revision)
+ => Read(source, document, revision, null, true).View.Shapes;
+
+ private static (FirmamentSketch View, Dictionary<string, Target> Targets) Read(string source, string document, string revision, string? node, bool constructionOnly = false)
{
var parsed = FirmamentSyntaxParser.Parse(source, document);
var declarations = FirmamentLanguageOutlineService.Declarations(parsed);
@@ -55,18 +62,19 @@ public static class FirmamentSketchService
}
var errors = parsed.Diagnostics.Select(d => Diagnostic(d.Code, d.Message, d.SourceSpan)).ToList();
var targets = new Dictionary<string, Target>(StringComparer.Ordinal);
+ var construction = constructionOnly ? null : FirmamentIntelliDraft.Project(source, document);
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);
+ errors.Count == 0 && frame is not null ? "ProfileResolvedNotBuilt" : "Unresolved") { Construction = construction };
+ if (node is null && !constructionOnly) return (Result(), targets);
var selected = declarations.FirstOrDefault(d => d.Id == node);
- if (selected.Syntax?.Type.Name.Text != "Profile")
+ if (!constructionOnly && 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)
+ if (!constructionOnly && 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);
@@ -75,10 +83,14 @@ public static class FirmamentSketchService
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);
+ ResolvedProfile2D? profile = null;
+ if (!constructionOnly)
+ {
+ 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 = constructionOnly ? declarations.Select(d => d.Id).ToHashSet() : 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)))
{
@@ -125,7 +137,8 @@ public static class FirmamentSketchService
}
shapes.Add(new(item.Id, item.Syntax.Name!.Text, item.Syntax.Type.Name.Text, center, controls));
}
- var plane = profile.EffectiveConstructionPlane;
+ if (constructionOnly) return (Result(shapes: shapes), targets);
+ 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]),
@@ -160,6 +173,8 @@ public static class FirmamentSketchService
public static FirmamentLanguageEdit Edit(string source, string document, string revision, FirmamentSketchEditRequest request)
{
+ if (request.Kind == "construction") return FirmamentIntelliDraft.Edit(source, document, revision,
+ request.Construction ?? throw Refuse("draft-operation-required", "Choose a construction operation."));
var operations = new List<FirmamentLanguageEditOperation>();
if (request.Kind == "create")
{
@@ -240,10 +255,10 @@ public static class FirmamentSketchService
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")
+ else if (request.Kind is "dimensions" or "constructionDimensions")
{
- 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 (view, targets) = Read(source, document, revision, request.Node, request.Kind == "constructionDimensions");
+ if (request.Kind != "constructionDimensions" && 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)>>();
@@ -276,6 +291,12 @@ public static class FirmamentSketchService
// 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 (request.Kind == "constructionDimensions" && after.Profiles.Count == 0)
+ {
+ var error = after.Construction?.Diagnostics.FirstOrDefault(d => d.Severity is "error" or "fatal");
+ if (error is not null) throw Refuse(error.Code, error.Message);
+ return result;
+ }
if (after.ValidationLevel != "ProfileResolvedNotBuilt")
throw Refuse("sketch-profile-invalid", string.Join("\n", after.Diagnostics.Select(d => d.Message)));
return result;
@@ -292,7 +313,7 @@ public static class FirmamentSketchService
CallSyntax { Target: ReferenceSyntax { Name.Text: "Point2" } } call => call.Arguments.Select(a => a.Value).ToArray(),
_ => []
};
- private static bool Literal(ExpressionSyntax expression) => expression switch
+ internal static bool Literal(ExpressionSyntax expression) => expression switch
{
LiteralSyntax { Kind: LiteralKind.Number } => true,
QuantitySyntax { Value: LiteralSyntax { Kind: LiteralKind.Number } } => true,
@@ -304,7 +325,7 @@ public static class FirmamentSketchService
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)
+ internal static FirmamentSketchCurve Curve(ResolvedProfileSegment2D segment)
{
static double[] P((double X, double Y) p) => [p.X, p.Y];
return segment.Geometry switch
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
index f76835c4..c208662f 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs
@@ -1300,7 +1300,7 @@ public static partial class FirmamentV2Parser
if (declarations.Any(d => d.Type.Name.Text == "Extrude"))
{
- var profile = ProfileAuthoringParser.Parse(adapterSource);
+ var profile = ProfileAuthoringParser.Parse(adapterSource, compileTime);
if (profile.Profile is null)
{
diagnostics.AddRange(profile.Diagnostics);
diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
index e18cf4cd..55e04731 100644
--- a/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
+++ b/Aetheris.Kernel.Firmament/FirmamentV2/ProfileAuthoringParser.cs
@@ -12,6 +12,20 @@ namespace Aetheris.Kernel.Firmament.FirmamentV2;
/// </summary>
public static class ProfileAuthoringParser
{
+ // IntelliDraft projects the same bound guides consumed by Profile, including open Paths.
+ // This is a query over the existing owner, not another geometry evaluator.
+ internal static (Dictionary<string, (double X, double Y)> Points,
+ Dictionary<string, LineArcProfileCurve2D> Guides, IReadOnlyList<string> Diagnostics)
+ InspectConstruction(string source, FirmamentCompileTimeValues values)
+ {
+ var diagnostics = new List<string>();
+ source = ExpandBuiltInPolygons(FirmamentSourceSpelling.Normalize(source), diagnostics, values);
+ var points = new Dictionary<string, (double X, double Y)>(StringComparer.Ordinal);
+ var guides = new Dictionary<string, LineArcProfileCurve2D>(StringComparer.Ordinal);
+ AddOrdinaryGuides(source, points, guides, diagnostics, applySpans: false, bind: values.NominalExpression);
+ BindPaths(source, points, guides, diagnostics);
+ return (points, guides, diagnostics);
+ }
public const string SegmentEndpointMustReferenceNamedPoint = "ProfileSegmentEndpointMustReferenceNamedPoint";
private const double Tolerance = 1e-9;
private static readonly Regex Segment = new(@"\bSegment\s+(?<n>\w+)\s*\{\s*Trace\s*:\s*(?<trace>[\w.]+)\s*;?\s*From\s*:\s*(?<from>[\w.]+)\s*;?\s*To\s*:\s*(?<to>[\w.]+)(?:\s*;?\s*Sweep\s*:\s*(?<sweep>Clockwise|CounterClockwise))?", RegexOptions.Singleline | RegexOptions.CultureInvariant);
@@ -49,7 +63,7 @@ public static class ProfileAuthoringParser
}
public static ResolvedProfile2D? ResolveNamedProfile(string source, string profileName, out IReadOnlyList<string> reportedDiagnostics)
- => ResolveNamedProfileCore(source, profileName, new(StringComparer.Ordinal), out reportedDiagnostics);
+ => ResolveNamedProfileCore(source, profileName, new(StringComparer.Ordinal), out reportedDiagnostics, new FirmamentCompileTimeValues(source));
internal static ResolvedProfile2D? ResolveNamedProfileCore(string source, string profileName, HashSet<string> visiting, out IReadOnlyList<string> reportedDiagnostics,
FirmamentCompileTimeValues? scalars=null)
@@ -177,9 +191,15 @@ public static class ProfileAuthoringParser
}
public static (ResolvedProfile2D? Profile, double Height, IReadOnlyList<string> Diagnostics) Parse(string source)
+ => Parse(source, null);
+
+ internal static (ResolvedProfile2D? Profile, double Height, IReadOnlyList<string> Diagnostics) Parse(string source, FirmamentCompileTimeValues? values)
{
var diagnostics = new List<string>();
- source = ExpandBuiltInPolygons(source, diagnostics);
+ values ??= new FirmamentCompileTimeValues(source);
+ var expanded = FirmamentV2TemplateExpansion.Expand(source, diagnostics, values);
+ if (expanded is not null) source = expanded.Source;
+ source = ExpandBuiltInPolygons(source, diagnostics, values);
var authoredProfiles = FindProfiles(source).ToArray();
var extrusion = FindBlocks(source, @"\bExtrude\s+\w+\s*\{").FirstOrDefault();
var extrudeProfile = extrusion is null ? null : Property(extrusion.Body, "Profile");
@@ -187,21 +207,21 @@ public static class ProfileAuthoringParser
if (profile is null)
return (null, 0, ["profile-source-missing-profile"]);
- if (ProfileBoundaryAuthoring.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out var conceptProfile)
- || ConceptProfileDerivation.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out conceptProfile))
+ if (ProfileBoundaryAuthoring.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out var conceptProfile, values)
+ || ConceptProfileDerivation.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out conceptProfile, values))
{
- var depths = ResolveExtrude(source, profile.Name, diagnostics);
+ var depths = ResolveExtrude(source, profile.Name, diagnostics, values.NominalExpression);
return (conceptProfile is null ? null : conceptProfile with { LocalStartDepth = depths.Start, LocalEndDepth = depths.End }, depths.Height, diagnostics);
}
var points = new Dictionary<string, (double X, double Y)>(StringComparer.Ordinal);
var guides = new Dictionary<string, LineArcProfileCurve2D>(StringComparer.Ordinal);
- AddOrdinaryGuides(source, points, guides, diagnostics);
+ AddOrdinaryGuides(source, points, guides, diagnostics, bind: values.NominalExpression);
var paths = BindPaths(source, points, guides, diagnostics);
ConstructionPlane? plane = ResolveConstructionPlane(source, profile.Frame, diagnostics);
var loops = BindProfileLoops(profile, paths, points, guides, diagnostics);
- var (start, end, height) = ResolveExtrude(source, profile.Name, diagnostics);
+ var (start, end, height) = ResolveExtrude(source, profile.Name, diagnostics, values.NominalExpression);
if (diagnostics.Count != 0)
return (null, height, diagnostics);
return (new ResolvedProfile2D(profile.Name, profile.Frame ?? "XY", loops, plane ?? ConstructionPlane.WorldXY, start, end), height, diagnostics);
@@ -213,27 +233,28 @@ public static class ProfileAuthoringParser
/// Concept Path syntax is intentionally erased at this boundary; segment
/// provenance retains the authored path and step identities.
/// </summary>
- internal static IReadOnlyDictionary<string, ResolvedProfile2D> BindPathDerivedProfiles(string source, List<string> diagnostics)
+ internal static IReadOnlyDictionary<string, ResolvedProfile2D> BindPathDerivedProfiles(string source, List<string> diagnostics, FirmamentCompileTimeValues? values = null)
{
// This is the canonical semantic-profile adapter used by Compose and SectionChain.
// Its historical name remains source-compatible; pipeline syntax is erased here too.
source = ProfileModificationTemplateLibrary.ResolveImports(source);
+ values ??= new FirmamentCompileTimeValues(source);
foreach (var authored in SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).Where(d => d.Type.Name.Text == "Profile"))
ValidateProfileBody(authored, diagnostics);
- source = ExpandBuiltInPolygons(source, diagnostics);
- var templates = FirmamentV2TemplateExpansion.Expand(source, diagnostics);
+ source = ExpandBuiltInPolygons(source, diagnostics, values);
+ var templates = FirmamentV2TemplateExpansion.Expand(source, diagnostics, values);
if (templates is not null) source = templates.Source;
var authoredProfiles = FindProfiles(source).Where(candidate => candidate.FromPath is not null || candidate.Body?.Contains("|>", StringComparison.Ordinal) == true || ProfileBoundaryAuthoring.IsDerived(candidate.Body)).ToArray();
if (authoredProfiles.Length == 0) return new Dictionary<string, ResolvedProfile2D>();
var points = new Dictionary<string, (double X, double Y)>(StringComparer.Ordinal);
var guides = new Dictionary<string, LineArcProfileCurve2D>(StringComparer.Ordinal);
- AddOrdinaryGuides(source, points, guides, diagnostics);
+ AddOrdinaryGuides(source, points, guides, diagnostics, bind: values.NominalExpression);
var paths = BindPaths(source, points, guides, diagnostics);
var profiles = new Dictionary<string, ResolvedProfile2D>(StringComparer.Ordinal);
foreach (var profile in authoredProfiles)
{
- if (ProfileBoundaryAuthoring.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out var derived)
- || ConceptProfileDerivation.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out derived))
+ if (ProfileBoundaryAuthoring.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out var derived, values)
+ || ConceptProfileDerivation.TryResolve(source, profile.Name, new(StringComparer.Ordinal) { profile.Name }, diagnostics, out derived, values))
{
if (derived is not null && !profiles.TryAdd(profile.Name, derived)) diagnostics.Add($"profile-duplicate:{profile.Name}");
continue;
@@ -1081,6 +1102,34 @@ public static class ProfileAuthoringParser
OnLine(point, line) && point.X >= Math.Min(line.Start.X, line.End.X) - Tolerance && point.X <= Math.Max(line.Start.X, line.End.X) + Tolerance
&& point.Y >= Math.Min(line.Start.Y, line.End.Y) - Tolerance && point.Y <= Math.Max(line.Start.Y, line.End.Y) + Tolerance;
+ /// <summary>Selectable spans between existing named landmarks. No points are invented and
+ /// no intersection solver is introduced. Material tracing still performs its full checks.</summary>
+ internal static IReadOnlyList<(string Guide, string From, string To, LineArcProfileCurve2D Geometry)> ConstructionSpans(
+ IReadOnlyDictionary<string, (double X, double Y)> points, IReadOnlyDictionary<string, LineArcProfileCurve2D> guides)
+ {
+ var result = new List<(string, string, string, LineArcProfileCurve2D)>();
+ foreach (var (name, geometry) in guides)
+ {
+ if (geometry is not LineArcLineSegment2D line || Distance(line.Start, line.End) <= Tolerance) continue;
+ var owner = name.Contains('.') ? name[..name.LastIndexOf('.')] : name;
+ var landmarks = new List<KeyValuePair<string, (double X, double Y)>>();
+ foreach (var point in points.Where(p => OnBoundedLine(p.Value, line))
+ .OrderBy(p => p.Key.StartsWith(owner + ".", StringComparison.Ordinal) ? 0 : 1).ThenBy(p => p.Key, StringComparer.Ordinal))
+ if (!landmarks.Any(p => Distance(p.Value, point.Value) <= Tolerance)) landmarks.Add(point);
+ var ordered = landmarks.OrderBy(p => (p.Value.X - line.Start.X) * (line.End.X - line.Start.X)
+ + (p.Value.Y - line.Start.Y) * (line.End.Y - line.Start.Y)).ToArray();
+ for (var i = 0; i + 1 < ordered.Length; i++)
+ {
+ var diagnostics = new List<string>();
+ var selected = SelectGuide(line, ordered[i].Value, ordered[i + 1].Value, "", name, name, diagnostics);
+ if (selected is not null && diagnostics.Count == 0) result.Add((name, ordered[i].Key, ordered[i + 1].Key, selected));
+ }
+ }
+ return result;
+ }
+
+ internal static bool SameConstructionPoint((double X, double Y) a, (double X, double Y) b) => Distance(a, b) <= Tolerance;
+
private static string MaskRecognizedProfileDeclarations(string body)
{
var declarationPattern = @"\b(?:(?:Concept\s+)?(?:Point2|Line2|Rect2|Square2|Circle2|Ellipse2|Ellipse2Guide|Slot2|RoundedRect2|SmoothRoundedRect2|Path)|(?:Triangle2|Polygon2|RegularPolygon2)\s*<[^>]+>)\s+[A-Za-z_]\w*\s*\{";
@@ -1270,14 +1319,14 @@ public static class ProfileAuthoringParser
return (profile, from, to);
}
- private static (double Start, double End, double Height) ResolveExtrude(string source, string profileName, List<string> diagnostics)
+ private static (double Start, double End, double Height) ResolveExtrude(string source, string profileName, List<string> diagnostics, Func<ExpressionSyntax, ExpressionSyntax>? bind = null)
{
foreach (var d in SourceDeclarations(FirmamentSyntaxParser.Parse(source).Document.Statements).Where(d => d.Type.Name.Text == "Extrude"))
{
var fields = ReadExtrudeFields(d, diagnostics);
if (FirmamentSyntaxValues.Reference(fields.Profile) != profileName) continue;
- if (!FirmamentSyntaxValues.TryMeasure(fields.From, "mm", out var start)
- || !FirmamentSyntaxValues.TryMeasure(fields.To, "mm", out var end))
+ if (!FirmamentSyntaxValues.TryMeasure(fields.From is { } from ? bind?.Invoke(from) ?? from : null, "mm", out var start)
+ || !FirmamentSyntaxValues.TryMeasure(fields.To is { } to ? bind?.Invoke(to) ?? to : null, "mm", out var end))
{
diagnostics.Add($"profile-extrusion-length-required:{d.Name?.Text}: Extrude from/to must be lengths in mm, not angles or scalars.");
continue;
diff --git a/Aetheris.Web.Runtime/sdk/README.md b/Aetheris.Web.Runtime/sdk/README.md
index e70b6d8f..46e198a7 100644
--- a/Aetheris.Web.Runtime/sdk/README.md
+++ b/Aetheris.Web.Runtime/sdk/README.md
@@ -212,6 +212,27 @@ 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).
+The additive `construction` projection exposes named points, bound guides, source
+elements, literal dimension controls and layout frames even before a Profile
+exists. Its `ConstructionResolvedNotTraced` level is not solid admission.
+`sketchEdit` also accepts `{ kind: 'construction', construction: operation }`.
+Typed operations create a layout, point, line, circle, Path, Path step, trace or
+extrusion; `movePoint` and `dimension` edit literal authoring inputs. They reuse
+the structural writer and existing Profile resolver. Keep intermediate source
+in a host-owned draft transaction and compile the complete candidate before
+committing. Preserve the preceding source and built model on refusal.
+
+`construction.shapes` retains typed closed shapes and reuses the existing driving
+dimension controls even before a Profile exists. `construction.spans` provides
+selectable rectangle-edge intervals between existing named landmarks. It does
+not invent intersections or flatten the source into editable segments.
+`rectangle` creates an independent Rect2 or a top-right inset driven by a reference
+rectangle; `parameter` changes a literal shared Length input. The existing edit
+transport also accepts `constructionDimensions` with the projected control ids.
+Connected span entries use `connect: true`; `wholeLoop: true` selects a complete
+rectangle outline. `targetProfile` explicitly replaces an authored Profile after
+the replacement resolves. All these edits remain staged until normal compilation.
+
### Pending graph authoring
`language.edit` also prepares `replaceDeclaration`, `patternFeature`,
diff --git a/Aetheris.Web.Runtime/sdk/src/index.d.ts b/Aetheris.Web.Runtime/sdk/src/index.d.ts
index 6e7b4298..61060251 100644
--- a/Aetheris.Web.Runtime/sdk/src/index.d.ts
+++ b/Aetheris.Web.Runtime/sdk/src/index.d.ts
@@ -95,7 +95,7 @@ export interface SketchCurve {
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;
+ construction?: DraftConstruction; 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;
@@ -103,7 +103,7 @@ export interface SketchProjection {
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 SketchEditRequest { kind: 'dimensions' | 'create' | 'opening' | 'construction' | 'constructionDimensions'; construction?: DraftOperation; 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 }
@@ -175,3 +175,9 @@ export interface MeasurementResult {
distanceMm: number | null; deltaMm: number[] | null; witnessA: number[] | null; witnessB: number[] | null;
angleDegrees: number | null; quality: string; explanation: string;
}
+
+export interface DraftElement { id: string; name: string; kind: string; parent: string | null; span: { start: number; length: number }; fields: readonly { name: string; value: string; number: number | null; unit: string | null; editable: boolean }[] }
+export interface DraftTrace { reference: string; from?: string; to?: string; alias?: string; reverse?: boolean; connect?: boolean; wholeLoop?: boolean }
+export interface DraftOperation { action: 'layout' | 'point' | 'line' | 'circle' | 'path' | 'step' | 'trace' | 'extrude' | 'movePoint' | 'dimension' | 'rectangle' | 'parameter'; width?: number; height?: number; reference?: string; insetX?: number; insetY?: number; sharedInset?: boolean; targetProfile?: string; field?: string; value?: number; parent?: string; name?: string; kind?: string; plane?: string; x?: number; y?: number; length?: number; radius?: number; turn?: number; from?: string; to?: string; trace?: readonly DraftTrace[] }
+export interface DraftSpan { id: string; owner: string; reference: string; from: string; to: string; curve: SketchCurve }
+export interface DraftConstruction { shapes?: readonly SketchShape[]; spans?: readonly DraftSpan[]; frames: readonly { owner: string; frame: NonNullable<SketchProjection['frame']> }[]; elements: readonly DraftElement[]; points: readonly { name: string; x: number; y: number }[]; guides: readonly SketchCurve[]; diagnostics: readonly SketchProjection['diagnostics'][number][]; validationLevel: 'ConstructionResolvedNotTraced' | 'Unresolved' }
diff --git a/docs/development/reports/2026-10/intellidraft-construction-shapes.md b/docs/development/reports/2026-10/intellidraft-construction-shapes.md
new file mode 100644
index 00000000..68bf781c
--- /dev/null
+++ b/docs/development/reports/2026-10/intellidraft-construction-shapes.md
@@ -0,0 +1,81 @@
+# IntelliDraft: retained construction shapes
+
+IntelliDraft now leads with **Shapes → Trace → Part**. The motivating L retains
+two `Rect2` constructions and a shared wall input. Selecting six boundary spans
+produces a Profile without authoring six points or six line declarations. The
+rectangles supply their intrinsic right angles and parallel, equal opposite
+sides; ordinary compile-time expressions supply the dependence between them.
+
+## Changes and ownership
+
+- The compiler projects retained shapes, writable driving dimensions, derived
+ expressions and selectable spans between existing named landmarks. The UI
+ does not solve constraints, evaluate source expressions or create intersection
+ coordinates. Advanced points, lines, circles and ordered Paths remain available.
+- A related-rectangle preset creates a top-right aligned inset in the same
+ Concept Struct. Width, height and center remain expressions of the reference
+ dimensions and a shared wall or separate insets. Derived fields are read-only;
+ independent inputs use explicit Apply/Discard transactions.
+- Trace selection preserves named references and stable edge aliases. Connected
+ spans are oriented by the existing compiler geometry owner. Existing Profiles
+ can be retraced while retaining the material consumer's Profile reference.
+- Construction inspection and mechanical profile adaptation now carry the
+ existing compile-time binding environment. Previously, a correctly resolved
+ rectangle expression could lose its bindings at the public Profile façade or
+ Model-stripping adapter and fail normal compilation.
+- Public profile/sketcher documentation and the Helios IntelliDraft guide now
+ lead with retained rectangles. The SDK exposes additive shape/span metadata
+ and source-edit operations through its existing transport.
+
+## Dogfood findings
+
+The manual production-browser run created a Layout, the outer rectangle, the
+related rectangle, six selected spans, the Profile and a 6 mm extrusion, then
+committed a solid showing **Ready / No problems**, without opening Source.
+
+Actual browser use exposed and corrected inspector scroll position after tool
+changes, competing pending dimension forms, overlapping landmark labels and
+horizontal/vertical SVG targets with zero-area accessibility bounds. Trace
+selection stays visible when switching rectangles. A final visual check caught
+a browser focus outline that scaled into a thick black bar; SVG targets now use
+a thin, non-scaling focus highlight.
+
+## Evidence
+
+- `fixtures/Regression/IntelliDraft/rectangles-l.firmament`: bounds
+ `(-30,-20,0)..(30,20,6)` mm, volume 4416 mm³, 8 faces / 18 edges / 12 vertices.
+- `rectangles-l-revised.firmament`: width 80 mm and wall 10 mm, bounds
+ `(-40,-20,0)..(40,20,6)` mm, volume 6600 mm³, unchanged topology counts.
+- Compiler tests verify retained `Rect2` source, no authored Point2/Line2 outline,
+ dependent dimensions after revision, stable curve identities, rejection of
+ an oversized wall without candidate mutation, retracing and an XZ world-bounds
+ witness. Expanded focused lane: **93 passed**.
+- Full Release solution build succeeded. Fast Core lane: **1110 passed**. Full
+ serial solution regression: **6046 passed, 2 existing Drawing Notes skips**.
+ An initial full run caught nine regressions in an attempted façade
+ consolidation. Restoring the existing Span and open-Path inspection contracts,
+ while retaining the shared binder fix, closed them without relaxing tests.
+- Helios unit suite: **157 passed**. Production AOT SDK install and production
+ frontend build succeeded. All **5 production browser workflows passed** after
+ the final SVG focus refinement. Browser qualification covers the retained-rectangle
+ L, width/wall revisions, invalid-wall refusal, whole-rectangle TraceLoop, and
+ the existing point, arc/chord and ordered-Path workflows. Each exported STEP
+ is compared against an independently built fixture for bounds, topology and
+ analytic surface/curve families; source is validated through the actual CLI.
+- The first production publish referenced a removed .NET 10.0.13 runtime file
+ after native compilation. A fresh-host retry using the installed 10.0.14
+ runtime succeeded; no runtime pin or source workaround was introduced.
+
+Logs are under ignored `artifacts/local/intellidraft-shapes/` in Aetheris and
+`artifacts/local/intellidraft-shapes-*` in HeliosCAD. Generated browser source,
+STEP, comparison JSON and screenshots are under
+`HeliosCAD/artifacts/local/intellidraft/`.
+
+## Boundaries and verdict
+
+**Success for the retained-rectangle workflow.** This is a constructive editor,
+not a simultaneous constraint solver. The current relationship preset requires
+unrotated rectangles in one Concept Struct and shares the top-right corner.
+Arbitrary intersection creation, general geometric snaps, arbitrary trim/extend,
+and general multi-loop drafting remain outside this pass. Existing code-authored
+geometry continues through its normal compiler owners.
diff --git a/docs/development/reports/2026-10/intellidraft-ui-parity.md b/docs/development/reports/2026-10/intellidraft-ui-parity.md
new file mode 100644
index 00000000..be9d1a71
--- /dev/null
+++ b/docs/development/reports/2026-10/intellidraft-ui-parity.md
@@ -0,0 +1,67 @@
+# IntelliDraft: construction-to-part UI qualification
+
+Date: 2026-10-25. Verdict: **Success for the bounded construction workflows below.** This is UI-only authoring evidence, not a claim that a fresh human usability study has taken place.
+
+## What was missing
+
+The former Sketch workspace could resize closed shapes and add circular openings. Its new-part action immediately created a rectangle, Profile and extrusion. It had no controls for named Point2/Line2 construction, circle spans, ordered Path steps or assembling a trace. It therefore could not reproduce the basic code-first construction workflow.
+
+Three reference programs were authored and validated before UI implementation:
+
+| Reference | Construction | Qualified STEP |
+|---|---|---|
+| [L plate](../../../../fixtures/Regression/IntelliDraft/named-lines-l.firmament) | Six named points, six Line2 guides, ordered outer trace | 8 faces, 18 edges, 12 vertices; bounds (0,0,0)–(60,40,6) mm; nominal volume 4,416 mm³ |
+| [D plate](../../../../fixtures/Regression/IntelliDraft/arc-chord-d.firmament) | Circle2 span between named points, plus chord | 4 faces, 6 edges, 4 vertices; bounds (0,-15,0)–(15,15,6) mm; exact semicircular cylinder wall |
+| [Rounded outline](../../../../fixtures/Regression/IntelliDraft/line-arc-path.firmament) | Named Line/Arc/Close Path steps, then Profile from Path | 7 faces, 15 edges, 10 vertices; bounds (0,0,0)–(40,30,2) mm; exact quarter-circle cylinder wall |
+
+Reported nominal coordinates above omit insignificant floating-point residuals. The source specimens are unchanged comparison references, not fixtures rewritten to match UI output.
+
+## Repairs and ownership
+
+- `FirmamentIntelliDraft` prepares bounded source operations through the existing structural writer: layout, point, line, circle, Path, step, trace, extrusion, point move and literal dimension edit.
+- `ProfileAuthoringParser.InspectConstruction` queries the existing point/guide/Path binders. No second geometry evaluator, constraint solver, parser route, whole-document rewrite or field schema was introduced.
+- `FirmamentSketchService` exposes an additive `construction` projection and edit request through the existing browser SDK transport. Normal Profile projection and closed-shape dimension edits remain compatible.
+- IntelliDraft in Helios stages source text locally. Open construction is explicitly not a built part. Rejected edits retain the preceding candidate. A complete candidate must pass the real compiler before commit; temporary model handles are disposed. Source revision checks protect newer work.
+- Existing-part updates use the normal graph transaction and undo path. New-part replacement retains the existing unsaved-work decision. The old closed-shape dimension workspace remains available through Sketch.
+- Compiler curves retain stable guide names, authored object spans and resolver provenance. Point moves update their declaration while Line2 references continue to name those points. Driven expressions are not flattened into coordinates.
+
+The structural writer exposed a real separator issue when appending an extrusion after a bodyless `Profile ... from ...` declaration. IntelliDraft emits the explicit separator; the structural parser still validates the resulting source.
+
+## Friction observed while operating the UI
+
+1. The old viewport-sized overlay was too narrow for both controls and construction. IntelliDraft now uses a larger workspace.
+2. Underlying controls remained exposed to accessibility navigation. A native modal dialog now confines interaction and focus; a manual accessibility inspection contains only the IntelliDraft controls. The browser test also checks native `:modal` state. DOM automation scopes selectors to the dialog; a DOM role query is not an accessibility-tree test.
+3. Parser category order made guide choices surprising. The UI now presents authored object order.
+4. Sequential line and trace entry required repetitive picks. Defaults advance to the preceding endpoint and next guide. Names and explicit reference choices remain editable.
+5. Construction vanished after tracing. Gold guides remain visible behind the dark material boundary.
+6. Coincident semantic endpoint aliases produced overlapping labels. Their display labels are grouped, with all names retained in the tooltip and source.
+7. Path step entry showed a redundant form and offered appending after Close. The step form is now separate, and invalid closed/empty Path actions are disabled.
+8. Upstream point and literal dimension changes were unavailable. They are now exposed in the object list, with staged Undo/Redo and full-build admission.
+
+The L, D and rounded Path were also operated manually through browser controls without editing source or injecting geometry. The Path run changed a driving length, undid it, traced and extruded the outline.
+
+## Qualification evidence
+
+- Full Release solution build: passed.
+- Fast kernel lane: 1,110 passed.
+- Full serial .NET regression: **6,043 passed, 2 existing Drawing Notes renderer skips, 0 failed**.
+- Focused sketch/construction lane: 26 passed. Four new construction tests cover source behavior, refused edits, analytic geometry parity, upstream changes and XZ placement.
+- Helios: **156 unit tests passed**; production TypeScript/Vite build passed.
+- SDK transport tests: 19 passed. Telos tests: 19 passed.
+- Production AOT browser qualification: **3 passed**. Each part is authored through controls, built, exported to STEP and compared with its code reference using the real CLI. Checks cover manifold status, body/shell/face/edge/vertex counts, bounds and analytic curve/surface families. No spline surfaces appear in these parts.
+- Independent backend comparisons import the emitted STEP and compare complete analytic curve/surface records and vertex coordinates against the references.
+- XZ witness: the asymmetric L has world bounds (0,-6,0)–(60,0,40) mm, rather than the XY variant. Normal is world -Y.
+- Broken trace, negative dimension and invalid name cases reject without changing the preceding source. The browser test additionally verifies a rejected trace, point edit, Undo/Redo and re-opening the constructed part.
+- No engineering materializer or exporter behavior was changed. Full existing corpus regressions passed.
+
+Native/CLI logs are under `Aetheris/artifacts/local/intellidraft/`. Browser-authored source, STEP, reference STEP, structured CLI analyses and screenshots are under `HeliosCAD/artifacts/local/intellidraft/`. Production build and browser logs are under `HeliosCAD/artifacts/local/intellidraft-*.log`.
+
+The isolated browser suite does not start Leviathan. Its optional AI-status requests log connection refusals; AI is not used for the modeling or qualification. The exact CLI volume query still rejects curved trimmed shells, so curved cases are qualified by their analytic geometry, topology and bounds rather than claiming a volume result that is unavailable.
+
+## Remaining limits
+
+This UI creates one authored Model with unambiguous construction names, principal-plane layouts, named Point2/Line2/Circle2 guides, XY line/arc Paths, one outer trace and a positive extrusion. It is not UI parity with every existing Profile language feature.
+
+General semantic snaps, expression builders, new inner-loop assembly, boundary edits, arbitrary trim/extend and freeform curve authoring remain outside this pass. Existing code capabilities and the prior shape dimension/opening editor remain available. Included/generated construction is not made writable by flattening expanded geometry.
+
+No new kernel capability or parser migration is required for the qualified workflows. The next ergonomic expansion should reuse the same compiler query/edit seam for named snaps and further boundary operations, rather than introducing a browser-side sketch model.
diff --git a/docs/public/firmament/sketcher.md b/docs/public/firmament/sketcher.md
index dac552c3..abf7bfad 100644
--- a/docs/public/firmament/sketcher.md
+++ b/docs/public/firmament/sketcher.md
@@ -1,8 +1,63 @@
-# Sketching in Helios
+# IntelliDraft and Profile dimensions in Helios
The sketch workspace edits ordinary Firmament source. There is no separate saved
sketch model, browser constraint solver or mesh-to-profile conversion.
+## Construction, trace, part
+
+**IntelliDraft** in the viewport toolbar authors the same retained construction
+used in Firmament code. Begin with **Layout** (a Concept Struct on XY, XZ or YZ),
+then dimensioned construction shapes. `Rect2` supplies right angles and equal,
+parallel opposite sides. Its type and dimensions remain authoritative when
+Trace selects material boundary spans from its named edges and corners.
+
+For an L, add a 60 × 40 mm rectangle at the origin, then **Add related rectangle**.
+Keep the top-right inset relationship and one shared 8 mm wall input. The second
+rectangle is driven by the first: 52 × 32 mm at center (4,4) mm. Choose **Trace**
+and select the envelope's bottom and lower-right spans, the inset's bottom and
+left edges, and the envelope's upper-left top span and left edge. **Trace Profile**
+checks the resulting closed boundary; neither rectangle is replaced by a point
+list or a mesh. **Use whole rectangle outline** traces a single full rectangle.
+
+**Shapes** edits independent dimensions. Derived values show their driving
+expressions and remain read-only; **Relationship dimensions** edits shared inputs.
+Apply or discard pending fields before leaving their editor or building. Resizing
+the envelope or changing the wall input updates both the construction and its
+trace. The source contains normal Rect2 declarations, Static inputs and explicit
+expressions, with no separate saved constraint model.
+
+Named **Point**, **Line**, **Circle** guides and Paths remain under **Advanced**.
+They support outlines that closed shapes do not express well. Circle spans select
+named start and end points; reversing a trace entry preserves its named source.
+
+Alternatively, create a **Path**, then append named Line or Arc steps with
+lengths, radii and signed turns. **Close Path with line** explicitly adds a
+closing line. **Trace this Path** resolves that boundary to a Profile. Trace's
+**Close** checks an already closed boundary and never supplies a missing edge.
+
+Complete examples:
+
+- [L plate from retained rectangles](../../../fixtures/Regression/IntelliDraft/rectangles-l.firmament)
+ and [its dimension-driven revision](../../../fixtures/Regression/IntelliDraft/rectangles-l-revised.firmament).
+- [Low-level L plate from named points and lines](../../../fixtures/Regression/IntelliDraft/named-lines-l.firmament).
+- [D plate from a circle span and chord](../../../fixtures/Regression/IntelliDraft/arc-chord-d.firmament).
+- [Rounded outline from ordered Path steps](../../../fixtures/Regression/IntelliDraft/line-arc-path.firmament).
+
+Choose an extrusion depth, **Extrude Profile**, then **Build and use part**.
+Incomplete construction is staged source, not a valid engineering part. Compiler
+rejection retains the preceding candidate and the current built model. Undo and
+Redo navigate staged edits; Cancel discards them. A complete candidate must pass
+the normal build before replacing the current document. Updating construction
+in an existing part is one normal undoable source transaction.
+
+The advanced objects list edits named points and literal driving dimensions. Point moves
+retain connected Line2 references. Expression-driven positions and dimensions
+are not replaced with coordinates. Canvas point placement rounds to a 0.1 mm
+grid; explicit typed values can use finer precision. Paths created by the UI use
+XY; the layout frame banner identifies local axes and the world-space normal.
+
+## Closed-shape dimension workspace
+
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
@@ -98,13 +153,19 @@ explicitly rejected while those support adapters still assume world XY.
## Current boundary
-This first workspace edits authored Rect2, Circle2, Slot2 and RoundedRect2 fields
+The **Sketch** dimension 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
+IntelliDraft currently authors one unambiguous Model, retained Rect2 construction,
+named Point2/Line2/Circle2 guides, line/arc Paths, one outer trace and a positive
+extrusion. The related-rectangle preset shares a top-right corner with an
+unrotated rectangle in the same Concept Struct. Its wall/inset values and the
+rectangle dimensions remain compile-time source expressions. Trace selection
+uses named landmarks on the compiler's bounded guides; it does not invent
+arbitrary intersection points. General cursor
+snaps, arbitrary one-way geometric references, boundary-edit tools, arbitrary
+trim/extend and simultaneous constraint solving are not implemented. Existing code-authored geometry
continues to use its normal compiler owners.
diff --git a/docs/public/reference/language/profiles.md b/docs/public/reference/language/profiles.md
index 55653bb3..dfbe3f53 100644
--- a/docs/public/reference/language/profiles.md
+++ b/docs/public/reference/language/profiles.md
@@ -10,6 +10,10 @@ Most parts start as a closed 2D boundary. The pattern is always the same:
There is no sketch solver. Positions and sizes are stated, so the boundary is
exactly what the numbers say.
+Helios's [IntelliDraft workspace](../../firmament/sketcher.md) follows this same
+construction → trace → material workflow. It writes named points, guides and
+Path steps into ordinary Firmament source and uses the compiler to resolve them.
+
## One-line Profiles
A single closed shape can be a Profile directly:
@@ -35,6 +39,14 @@ line and arc cuts).
Use the loop form when a Profile has inner loops, combines several guides, or
needs named edges:
+For a shape-driven example, [this L plate](../../../../fixtures/Regression/IntelliDraft/rectangles-l.firmament)
+retains two `Rect2` declarations: an envelope and an inset rectangle whose top
+and right edges follow it through shared dimensions. The Profile traces selected
+edge spans between their named corners. Changing the envelope or shared wall
+input updates the construction and boundary together, without independently
+moving six vertices. [Its revision](../../../../fixtures/Regression/IntelliDraft/rectangles-l-revised.firmament)
+changes only driving dimensions.
+
```firmament
Model ProfilePlate {
units: mm
diff --git a/fixtures/Regression/IntelliDraft/arc-chord-d.firmament b/fixtures/Regression/IntelliDraft/arc-chord-d.firmament
new file mode 100644
index 00000000..c28f0b58
--- /dev/null
+++ b/fixtures/Regression/IntelliDraft/arc-chord-d.firmament
@@ -0,0 +1,14 @@
+Model DPlate {
+ units: mm
+ Concept Struct layout on XY {
+ Point2 center { position: [0mm, 0mm] }
+ Point2 lower { position: [0mm, -15mm] }
+ Point2 upper { position: [0mm, 15mm] }
+ Circle2 rim { center: center; radius: 15mm }
+ Line2 chord { from: upper; to: lower }
+ }
+ Profile section using layout {
+ Loop Outer { rim from lower to upper as arc |> chord |> Close }
+ }
+ Extrude body { profile: section; from: 0mm; to: 6mm }
+}
diff --git a/fixtures/Regression/IntelliDraft/line-arc-path.firmament b/fixtures/Regression/IntelliDraft/line-arc-path.firmament
new file mode 100644
index 00000000..db750f23
--- /dev/null
+++ b/fixtures/Regression/IntelliDraft/line-arc-path.firmament
@@ -0,0 +1,14 @@
+Model RoundedPlate {
+ units: mm
+ Path outline {
+ start: Point2(0mm, 0mm)
+ heading: 0deg
+ Line bottom { length: 40mm }
+ Line right { turn: 90deg; length: 20mm }
+ Arc corner { radius: 10mm; turn: 90deg }
+ Line top { length: 30mm }
+ Close left
+ }
+ Profile section from outline
+ Extrude body { profile: section; from: 0mm; to: 2mm }
+}
diff --git a/fixtures/Regression/IntelliDraft/named-lines-l.firmament b/fixtures/Regression/IntelliDraft/named-lines-l.firmament
new file mode 100644
index 00000000..c33ea527
--- /dev/null
+++ b/fixtures/Regression/IntelliDraft/named-lines-l.firmament
@@ -0,0 +1,21 @@
+Model LPlate {
+ units: mm
+ Concept Struct layout on XY {
+ Point2 a { position: [0mm, 0mm] }
+ Point2 b { position: [60mm, 0mm] }
+ Point2 c { position: [60mm, 8mm] }
+ Point2 d { position: [8mm, 8mm] }
+ Point2 e { position: [8mm, 40mm] }
+ Point2 f { position: [0mm, 40mm] }
+ Line2 bottom { from: a; to: b }
+ Line2 right { from: b; to: c }
+ Line2 ledge { from: c; to: d }
+ Line2 upright { from: d; to: e }
+ Line2 top { from: e; to: f }
+ Line2 left { from: f; to: a }
+ }
+ Profile section using layout {
+ Loop Outer { bottom |> right |> ledge |> upright |> top |> left |> Close }
+ }
+ Extrude body { profile: section; from: 0mm; to: 6mm }
+}
diff --git a/fixtures/Regression/IntelliDraft/rectangles-l-revised.firmament b/fixtures/Regression/IntelliDraft/rectangles-l-revised.firmament
new file mode 100644
index 00000000..02d56323
--- /dev/null
+++ b/fixtures/Regression/IntelliDraft/rectangles-l-revised.firmament
@@ -0,0 +1,30 @@
+Model RectanglePlate {
+ units: mm
+ Static outerCenterX: Length = 0mm
+ Static outerCenterY: Length = 0mm
+ Static outerWidth: Length = 80mm
+ Static outerHeight: Length = 40mm
+ Static wall: Length = 10mm
+ Concept Struct layout on XY {
+ Rect2 outer {
+ center: [outerCenterX, outerCenterY]
+ size: [outerWidth, outerHeight]
+ }
+ Rect2 notch {
+ center: [outerCenterX + wall / 2, outerCenterY + wall / 2]
+ size: [outerWidth - wall, outerHeight - wall]
+ }
+ }
+ Profile section using layout {
+ Loop Outer {
+ outer.Bottom from outer.BottomLeft to outer.BottomRight as bottom
+ |> outer.Right from outer.BottomRight to notch.BottomRight as right
+ |> notch.Bottom from notch.BottomRight to notch.BottomLeft as ledge
+ |> notch.Left from notch.BottomLeft to notch.TopLeft as upright
+ |> outer.Top from notch.TopLeft to outer.TopLeft as top
+ |> outer.Left from outer.TopLeft to outer.BottomLeft as left
+ |> Close
+ }
+ }
+ Extrude body { profile: section; from: 0mm; to: 6mm }
+}
diff --git a/fixtures/Regression/IntelliDraft/rectangles-l.firmament b/fixtures/Regression/IntelliDraft/rectangles-l.firmament
new file mode 100644
index 00000000..986a6bf3
--- /dev/null
+++ b/fixtures/Regression/IntelliDraft/rectangles-l.firmament
@@ -0,0 +1,30 @@
+Model RectanglePlate {
+ units: mm
+ Static outerCenterX: Length = 0mm
+ Static outerCenterY: Length = 0mm
+ Static outerWidth: Length = 60mm
+ Static outerHeight: Length = 40mm
+ Static wall: Length = 8mm
+ Concept Struct layout on XY {
+ Rect2 outer {
+ center: [outerCenterX, outerCenterY]
+ size: [outerWidth, outerHeight]
+ }
+ Rect2 notch {
+ center: [outerCenterX + wall / 2, outerCenterY + wall / 2]
+ size: [outerWidth - wall, outerHeight - wall]
+ }
+ }
+ Profile section using layout {
+ Loop Outer {
+ outer.Bottom from outer.BottomLeft to outer.BottomRight as bottom
+ |> outer.Right from outer.BottomRight to notch.BottomRight as right
+ |> notch.Bottom from notch.BottomRight to notch.BottomLeft as ledge
+ |> notch.Left from notch.BottomLeft to notch.TopLeft as upright
+ |> outer.Top from notch.TopLeft to outer.TopLeft as top
+ |> outer.Left from outer.TopLeft to outer.BottomLeft as left
+ |> Close
+ }
+ }
+ Extrude body { profile: section; from: 0mm; to: 6mm }
+}