Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Add graph authoring edits and retain box cap topology
Yuechen Liad6dc5ce7ae7
diff --git a/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanBoxCylinderHoleBuilder.cs b/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanBoxCylinderHoleBuilder.csindex 2d67ceaf..264be63d 100644--- a/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanBoxCylinderHoleBuilder.cs+++ b/Aetheris.Kernel.Core/Brep/Boolean/BrepBooleanBoxCylinderHoleBuilder.cs@@ -25,7 +25,7 @@ public static class BrepBooleanBoxCylinderHoleBuilder}public static KernelResult<BrepBody> BuildComposition(SafeBooleanComposition composition, ToleranceContext tolerance,- Action<string, FaceId>? onConstructedHoleWall = null)+ Action<string, FaceId>? onConstructedHoleWall = null, Action<string, FaceId>? onConstructedHostFace = null){ArgumentNullException.ThrowIfNull(composition);_ = tolerance;@@ -128,7 +128,7 @@ public static class BrepBooleanBoxCylinderHoleBuilder}}- return CreateComposedThroughHoleBody(composition, tolerance, onConstructedHoleWall);+ return CreateComposedThroughHoleBody(composition, tolerance, onConstructedHoleWall, onConstructedHostFace);}/// <summary>@@ -721,7 +721,7 @@ public static class BrepBooleanBoxCylinderHoleBuilder}private static KernelResult<BrepBody> CreateComposedThroughHoleBody(SafeBooleanComposition composition, ToleranceContext tolerance,- Action<string, FaceId>? onConstructedHoleWall = null)+ Action<string, FaceId>? onConstructedHoleWall = null, Action<string, FaceId>? onConstructedHostFace = null){var box = composition.OuterBox;var holes = composition.Holes;@@ -802,6 +802,8 @@ public static class BrepBooleanBoxCylinderHoleBuilder// intersection is not topology authority here.var bottomFace = AddKnownFace(builder, bottomLoops);var topFace = AddKnownFace(builder, topLoops);+ onConstructedHostFace?.Invoke("-Z", bottomFace);+ onConstructedHostFace?.Invoke("+Z", topFace);var xMinFace = AddKnownFace(builder, [AddSurgeryLoop(builder, [Forward(e1), Forward(e10), Reversed(e5), Reversed(e9)])]);var xMaxFace = AddKnownFace(builder, [AddSurgeryLoop(builder, [Forward(e2), Forward(e11), Reversed(e6), Reversed(e10)])]);var yMaxFace = AddKnownFace(builder, [AddSurgeryLoop(builder, [Forward(e3), Forward(e12), Reversed(e7), Reversed(e11)])]);diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentGraphAuthoringTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentGraphAuthoringTests.csnew file mode 100644index 00000000..83b7f3c7--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentGraphAuthoringTests.cs@@ -0,0 +1,159 @@+using Aetheris.Kernel.Firmament.FirmamentV2;+using Aetheris.Kernel.Firmament.Assembly;+using Aetheris.Kernel.Firmament.Materializer;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentGraphAuthoringTests+{+ private static string Fixture(string name) => File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath("fixtures/Regression/GraphAuthoring/" + name + ".firmament")).ReplaceLineEndings("\n");+ private static string Plate => Fixture("plate");+ private static string Profile => Fixture("profile");+ private static FirmamentLanguageEdit Edit(string source, params FirmamentLanguageEditOperation[] operations) =>+ FirmamentLanguageEditService.Apply(source, "authoring.firmament", "1", operations);+ private static void Builds(string source)+ {+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, source + "\n" + string.Join('\n', built.Diagnostics.Select(d => d.Message)));+ }++ [Fact]+ public void ReplaceBaseKeepsItsNameReferencesAndSurroundingSource()+ {+ var result = Edit(Plate, new FirmamentLanguageEditOperation("replaceDeclaration") { Node = "Part/Box:Stock", Source = "Box Other { size: [90mm,60mm,8mm] }" });+ Assert.Contains("Box Stock", result.Text);+ Assert.Contains("Modify Stock {", result.Text);+ Assert.EndsWith("}\n", result.Text);+ Builds(result.Text);+ }++ [Fact]+ public void PickableRetainedCapsKeepExactGeometryForSingleAndMultipleHoles()+ {+ var multipleSource = Edit(Plate, new FirmamentLanguageEditOperation("insertFeature") { Node = "Part/Box:Stock",+ Source = "Hole<Shaft> Second { on: +Z center: Point2(20mm,0mm) diameter: 6mm end: ThroughAll }" }).Text;+ foreach (var source in new[] { Plate, multipleSource })+ {+ var built = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(built.IsSuccess, string.Join('\n', built.Diagnostics.Select(d => d.Message)));+ var caps = built.Value.RuntimeCorrespondence!.Descendants.Where(d => d.Role == SemanticTopologyRole.BoxFace).ToArray();+ Assert.Equal(2, caps.Length);+ var top = Assert.Single(caps, d => d.FirmamentSelector == "face(+Z)");+ var body = built.Value.RuntimeBody!;+ var binding = Assert.Single(body.Bindings.FaceBindings, b => b.FaceId == top.Face);+ Assert.Equal(1, body.Geometry.GetSurface(binding.SurfaceGeometryId).Plane!.Value.Normal.Z, 10);+ var selected = FirmamentBuildAndExport.CompileSource(source.Replace("on: +Z", "on: face(+Z)", StringComparison.Ordinal));+ Assert.True(selected.IsSuccess, string.Join('\n', selected.Diagnostics.Select(d => d.Message)));+ Assert.Equal(built.Value.StepText[built.Value.StepText.IndexOf("DATA;", StringComparison.Ordinal)..], selected.Value.StepText[selected.Value.StepText.IndexOf("DATA;", StringComparison.Ordinal)..]);+ }+ }++ [Fact]+ public void GridPreservesSeedIdentityAndBuildsSixActualHoles()+ {+ var result = Edit(Plate, new FirmamentLanguageEditOperation("patternFeature") { Node = "Part/Modify:Stock/Seed", Name = "Mounts", Grid = new(3, 2, 20, 20) });+ Assert.Contains("Hole<Shaft> Seed { on: +Z center: Point2(-20mm, -10mm) diameter: 4mm end: ThroughAll }", result.Text);+ Assert.Contains("r1c2 =>", result.Text);+ Assert.DoesNotContain("r0c0 =>", result.Text);+ var built = FirmamentBuildAndExport.CompileSource(result.Text);+ Assert.True(built.IsSuccess, result.Text + "\n" + string.Join('\n', built.Diagnostics.Select(d => d.Message)));+ Assert.Equal(6, built.Value.Features!.Count);+ }++ [Theory]+ [InlineData(0, 1, 20, 0)]+ [InlineData(1024, 2, 20, 20)]+ [InlineData(2, 1, 0, 0)]+ public void InvalidGridDoesNotWriteSource(int cols, int rows, double x, double y) =>+ Assert.Equal("edit-grid-invalid", Assert.Throws<FirmamentLanguageEditException>(() => Edit(Plate,+ new FirmamentLanguageEditOperation("patternFeature") { Node = "Part/Modify:Stock/Seed", Grid = new(cols, rows, x, y) })).Code);++ [Fact]+ public void ProfileExtrudesThenPocketsThroughExistingComposeOwner()+ {+ var extruded = Edit(Profile, new FirmamentLanguageEditOperation("extrudeProfile") { Node = "Part/Section", Value = "8mm" });+ Builds(extruded.Text);+ var extra = Edit(extruded.Text,+ new FirmamentLanguageEditOperation("insertDeclaration") { Parent = "Part", Source = "Circle2 Recess { center: [0mm,0mm] radius: 5mm }" },+ new FirmamentLanguageEditOperation("insertDeclaration") { Parent = "Part", Source = "Profile RecessProfile { Loop Outer { Recess |> TraceLoop } }" });+ var pocket = Edit(extra.Text, new FirmamentLanguageEditOperation("pocketProfile") { Node = "Part/RecessProfile", Parent = "Part/Body", Value = "2mm", Name = "Counterbore" });+ Assert.Contains("Compose Body", pocket.Text);+ Assert.Contains("Base Stock", pocket.Text);+ Builds(pocket.Text);+ }++ [Fact]+ public void ExtrusionEndEditPreservesTheAuthoredStartAndParameterReference()+ {+ var original = Edit(Profile, new FirmamentLanguageEditOperation("insertDeclaration") { Parent = "Part", Source = "Static End: Length = 10mm;" },+ new FirmamentLanguageEditOperation("insertDeclaration") { Parent = "Part", Source = "Extrude Body { profile: Section; from: 2mm; to: End; }" });+ var unchanged = Edit(original.Text, new FirmamentLanguageEditOperation("extrudeProfile") { Node = "Part/Section", Value = "End" });+ Assert.Contains("from: 2mm", unchanged.Text);+ Assert.Contains("to: End", unchanged.Text);+ var extended = Edit(unchanged.Text, new FirmamentLanguageEditOperation("extrudeProfile") { Node = "Part/Section", Value = "14mm" });+ Assert.Contains("from: 2mm", extended.Text);+ Assert.Contains("Static End: Length = 10mm", extended.Text);+ Builds(unchanged.Text); Builds(extended.Text);+ }++ [Fact]+ public void BoxPocketUsesTheQualifiedProfileCompositionWithoutLosingStockSize()+ {+ var result = Edit("Model Part { units: mm Box Stock { size: [80mm,60mm,8mm] } }", new FirmamentLanguageEditOperation("pocketProfile")+ {+ Parent = "Part/Stock", Name = "Recess", Value = "2mm",+ Declaration = new("Circle2", Fields: [new("center", "[0mm,0mm]"), new("diameter", "10mm")])+ });+ Assert.Contains("size: [80mm, 60mm]", result.Text);+ Assert.Contains("to: 8mm", result.Text);+ Builds(result.Text);+ }++ [Fact]+ public void ExtrudeDoesNotSilentlyReplaceAnotherBase() =>+ Assert.Equal("edit-body-occupied", Assert.Throws<FirmamentLanguageEditException>(() => Edit(+ Profile.Replace("units: mm", "units: mm Box Stock { size: [80mm,60mm,8mm] }"),+ new FirmamentLanguageEditOperation("extrudeProfile") { Node = "Part/Section", Value = "8mm" })).Code);++ [Fact]+ public void PlacementUsesReadableFrameFieldsAndReplacesOnlyTheOldPlacement()+ {+ var source = Fixture("placement");+ var result = Edit(source, new FirmamentLanguageEditOperation("setPlacement") { Node = "Pair/Pair/B", Placement = new([20, 5, 0], "Z", 90) });+ Assert.DoesNotContain("Placement Old", result.Text);+ Assert.Contains("translateLocal: [20mm, 5mm, 0mm]", result.Text);+ var built = new AssemblyM1Pipeline().Compile(result.Text, "placement.firmament");+ Assert.True(built.IsSuccess, string.Join('\n', built.Diagnostics));+ var moved = built.Ir!.Instances.Single(i => i.Path.ToString() == "Pair.B").ResolvedTransform!.Matrix;+ Assert.Equal(20, moved[12], 8); Assert.Equal(5, moved[13], 8);+ var controls = FirmamentLanguageOutlineService.Outline(result.Text, "placement", "1").Nodes.Single(n => n.Kind == "Placement").PlacementControls!;+ Assert.Null(controls.ReadOnlyReason); Assert.Equal(90, controls.AngleDegrees); Assert.Equal([20d, 5, 0], controls.TranslationMm);+ }++ [Theory]+ [InlineData("Placement { from: Origin; to: Frame.Top; }")]+ [InlineData("Placement { from: Origin; to: Parent; translateLocal: [Width,0mm,0mm]; }")]+ [InlineData("Placement Old = [0,1,0,0,-1,0,0,0,0,0,1,0,20,0,0,1];")]+ public void AdvancedPlacementControlsDoNotFreezeOrDiscardAuthoredIntent(string placement)+ {+ var outline = FirmamentLanguageOutlineService.Outline(placement, "placement", "1");+ Assert.NotNull(Assert.Single(outline.Nodes).PlacementControls!.ReadOnlyReason);+ }++ [Fact]+ public void StarterPublishedFramesMateThroughTheExistingAssemblySolver()+ {+ var source = Fixture("assembly-starter");+ var before = new AssemblyM1Pipeline().Compile(source, "starter.firmament");+ Assert.True(before.IsSuccess, string.Join('\n', before.Diagnostics));+ var node = FirmamentLanguageOutlineService.Outline(source, "starter", "1").Nodes.Single(n => n.Kind == "Placement");+ var edited = Edit(source, new FirmamentLanguageEditOperation("removeDeclaration") { Node = node.Id },+ new FirmamentLanguageEditOperation("insertDeclaration") { Parent = null, First = true, Source = "Interface<Fixed> Rigid { }" },+ new FirmamentLanguageEditOperation("insertDeclaration") { Parent = "WebBlockPair", Source = "Mate Stack: Rigid { A: WebBlockPair.Fixed.Top; B: WebBlockPair.Moving.Bottom; }" });+ var after = new AssemblyM1Pipeline().Compile(edited.Text, "starter.firmament");+ Assert.True(after.IsSuccess, string.Join('\n', after.Diagnostics));+ var transform = after.Ir!.Instances.Single(i => i.Path.ToString() == "WebBlockPair.Moving").ResolvedTransform!.Matrix;+ Assert.Equal(0, transform[12], 8); Assert.Equal(10, transform[14], 8);+ Assert.Equal(before.Geometry!.Artifact.Definitions.Select(d => d.StepSha256).Order(), after.Geometry!.Artifact.Definitions.Select(d => d.StepSha256).Order());+ }+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.Authoring.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.Authoring.csnew file mode 100644index 00000000..1ae9bfb2--- /dev/null+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.Authoring.cs@@ -0,0 +1,208 @@+using System.Globalization;+using Aetheris.Kernel.Firmament.FirmamentV2.Syntax;++namespace Aetheris.Kernel.Firmament.FirmamentV2;++public sealed record FirmamentPlacementControls(double[] TranslationMm, string Axis, double AngleDegrees, string? ReadOnlyReason = null);++// Authoring conveniences share the structural writer and parser. They do not+// admit geometry: callers must preview/build the resulting source before commit.+public static partial class FirmamentLanguageEditService+{+ internal static FirmamentPlacementControls PlacementControls(DeclarationSyntax placement)+ {+ FirmamentPlacementControls ReadOnly() => new([0, 0, 0], "Z", 0, "This placement is driven by a frame, expression or general matrix. Its source remains authoritative; use a semantic mate or edit its defining frame.");+ bool Literal(ExpressionSyntax e) => e switch { LiteralSyntax => true, QuantitySyntax q => Literal(q.Value), UnarySyntax u => Literal(u.Operand), _ => false };+ if (placement.Initializer is SequenceSyntax sequence && sequence.Items.All(i => Literal(i.Value))+ && FirmamentSyntaxValues.Vector(sequence, "", out var m) && m.Length == 16)+ {+ var identity = new double[] { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, m[12], m[13], m[14], 1 };+ return m.SequenceEqual(identity) ? new([m[12], m[13], m[14]], "Z", 0) : ReadOnly();+ }+ if (placement.Initializer is not null and not ObjectSyntax || placement.Clauses.Count > 0 || placement.Type.Arguments.Count > 0+ || BodyOf(placement)?.Statements.Any(s => s is not FieldSyntax) == true) return ReadOnly();+ var groups = Fields(placement).GroupBy(f => f.Name.Text, StringComparer.OrdinalIgnoreCase).ToArray();+ if (groups.Any(g => g.Count() != 1)) return ReadOnly();+ var fields = groups.ToDictionary(g => g.Key, g => g.Single(), StringComparer.OrdinalIgnoreCase);+ if (fields.Keys.Any(k => !new[] { "from", "to", "translateLocal", "rotateLocal" }.Contains(k, StringComparer.OrdinalIgnoreCase))+ || fields.TryGetValue("from", out var from) && FirmamentSyntaxValues.Reference(from.Value) != "Origin"+ || fields.TryGetValue("to", out var to) && FirmamentSyntaxValues.Reference(to.Value) != "Parent") return ReadOnly();+ double[] translation = [0, 0, 0]; string axis = "Z"; double angle = 0;+ if (fields.TryGetValue("translateLocal", out var move))+ {+ if (move.Value is not SequenceSyntax s || s.Items.Any(i => !Literal(i.Value))+ || !FirmamentSyntaxValues.Vector(move.Value, "mm", out translation, "mm") || translation.Length != 3) return ReadOnly();+ }+ if (fields.TryGetValue("rotateLocal", out var rotate))+ {+ if (rotate.Value is not ObjectSyntax obj) return ReadOnly();+ var rotation = obj.Body.Statements.OfType<FieldSyntax>().ToArray();+ if (rotation.Length != 2 || obj.Body.Statements.Count != 2) return ReadOnly();+ axis = FirmamentSyntaxValues.Reference(rotation.FirstOrDefault(f => f.Name.Text.Equals("axis", StringComparison.OrdinalIgnoreCase))?.Value) ?? "";+ var angleValue = rotation.FirstOrDefault(f => f.Name.Text.Equals("angle", StringComparison.OrdinalIgnoreCase))?.Value;+ if (axis is not ("X" or "Y" or "Z") || angleValue is null || !Literal(angleValue)+ || !FirmamentSyntaxValues.TryMeasure(angleValue, "deg", out angle)) return ReadOnly();+ }+ return new(translation, axis, angle);+ }++ private static (string, string?) ReplaceDeclaration(string text, SyntaxParseResult parse, FirmamentLanguageEditOperation op)+ {+ var (id, declaration) = Find(parse, op.Node);+ if (declaration.Name is null || FirmamentLanguageOutlineService.NameIsUse(declaration))+ throw new FirmamentLanguageEditException("edit-replace-owner", "Replace a named definition, not an occurrence or a Modify target.");+ if (op.Source is null && op.Declaration is null)+ throw new FirmamentLanguageEditException("edit-input-required", "Replacement needs a declaration.");+ var indent = Indent(text, declaration.Span.Start);+ var snippet = op.Declaration is { } spec+ ? Write(spec with { Name = declaration.Name.Text }, indent, Unit(text))+ : FromSource(op.Source!, declaration.Name.Text, indent);+ CheckSnippet(snippet);+ // The statement span starts at its first token, after the existing indent.+ var next = Replace(text, declaration.Span.Start, declaration.Span.Length, snippet[indent.Length..]);+ var created = FirmamentLanguageOutlineService.Declarations(Parse(next)).First(d => d.Syntax.Span.Start == declaration.Span.Start);+ return (next, created.Id);+ }++ private static (string, string?) ExtrudeProfile(string text, SyntaxParseResult parse, FirmamentLanguageEditOperation op)+ {+ var (id, profile) = Find(parse, op.Node);+ if (profile.Type.Name.Text != "Profile" || profile.Name is null)+ throw new FirmamentLanguageEditException("edit-profile-required", "Select an authored Profile to extrude.");+ var declarations = FirmamentLanguageOutlineService.Declarations(parse);+ var parent = declarations.First(d => d.Id == id).ParentId;+ var height = RequireValue(op.Value, "to");+ var bodies = Siblings(declarations, parent).Where(d => IsAuthoringBody(d.Syntax)).ToArray();+ if (bodies.Length > 0)+ {+ var existing = bodies.Length == 1 && bodies[0].Syntax.Type.Name.Text == "Extrude" ? bodies[0] : default;+ if (existing.Syntax is null || !Fields(existing.Syntax).Any(f => f.Name.Text.Equals("profile", StringComparison.OrdinalIgnoreCase)+ && Slice(text, f.Value.Span) == profile.Name.Text))+ throw new FirmamentLanguageEditException("edit-body-occupied", "This container already has a different body. Replace its base explicitly or use another Part.");+ var to = Fields(existing.Syntax).FirstOrDefault(f => f.Name.Text.Equals("to", StringComparison.OrdinalIgnoreCase));+ return SetField(text, parse, new("setField") { Node = existing.Id, Field = to?.Name.Text ?? "to", Value = height });+ }+ return InsertDeclaration(text, parse, new("insertDeclaration") { Parent = parent, Name = op.Name ?? "Body",+ Source = $"Extrude Body {{ profile: {profile.Name.Text}; from: 0mm; to: {height}; }}" });+ }++ private static (string, string?) PocketProfile(string text, SyntaxParseResult parse, FirmamentLanguageEditOperation op)+ {+ if (op.Node is null && op.Declaration is { } shape)+ {+ var (targetId, target) = Find(parse, op.Parent);+ if (shape.Kind is not ("Circle2" or "Rect2"))+ throw new FirmamentLanguageEditException("edit-pocket-shape", "Choose Circle2 or Rect2, or an existing authored Profile.");+ var parent = FirmamentLanguageOutlineService.Declarations(parse).First(d => d.Id == targetId).ParentId;+ var stem = RequireIdentifier(op.Name ?? "Recess", "pocket name");+ var taken = FirmamentLanguageOutlineService.Declarations(parse).Select(d => d.Syntax.Name?.Text).ToHashSet();+ if (new[] { stem, stem + "Outline", stem + "Profile" }.Any(taken.Contains))+ throw new FirmamentLanguageEditException("edit-name-taken", "Choose a unique pocket name.");+ var (shaped, _) = InsertDeclaration(text, parse, new("insertDeclaration") { Parent = parent,+ Declaration = shape with { Name = stem + "Outline" } });+ var (profiled, profileNode) = InsertDeclaration(shaped, Parse(shaped), new("insertDeclaration") { Parent = parent,+ Source = $"Profile {stem}Profile {{ Loop Outer {{ {stem}Outline |> TraceLoop }} }}" });+ return PocketProfile(profiled, Parse(profiled), op with { Node = profileNode, Declaration = null });+ }+ var (profileId, profile) = Find(parse, op.Node);+ var (bodyId, body) = Find(parse, op.Parent);+ if (profile.Type.Name.Text != "Profile" || profile.Name is null)+ throw new FirmamentLanguageEditException("edit-profile-required", "Select an authored closed Profile for the pocket.");+ var declarations = FirmamentLanguageOutlineService.Declarations(parse);+ if (declarations.First(d => d.Id == profileId).ParentId != declarations.First(d => d.Id == bodyId).ParentId)+ throw new FirmamentLanguageEditException("edit-profile-scope", "The pocket Profile and body must belong to the same container.");+ var pocket = $"Pocket {RequireIdentifier(op.Name ?? "Recess", "pocket name")} {{ on: Top; profile: {profile.Name.Text}; depth: {RequireValue(op.Value, "depth")}; minimumFloorThickness: 0mm; }}";+ if (body.Type.Name.Text == "Compose")+ return InsertDeclaration(text, parse, new("insertDeclaration") { Parent = bodyId, Source = pocket });+ if (body.Clauses.Count > 0 || BodyOf(body)?.Statements.Any(s => s is not FieldSyntax) == true)+ throw new FirmamentLanguageEditException("edit-pocket-base-fields", "This base has additional authored clauses or statements. Convert it to Compose explicitly so those requirements are preserved.");+ if (body.Type.Name.Text == "Box" && Fields(body).ToArray() is [var size]+ && size.Name.Text.Equals("size", StringComparison.OrdinalIgnoreCase) && size.Value is SequenceSyntax { Items.Count: 3 } dimensions)+ {+ var container = declarations.First(d => d.Id == bodyId).ParentId;+ var stem = body.Name!.Text + "Stock";+ if (declarations.Any(d => d.Syntax.Name?.Text is { } n && (n == stem + "Outline" || n == stem + "Profile")))+ throw new FirmamentLanguageEditException("edit-name-taken", "The generated stock-profile names already exist; use an explicit profile-based body.");+ var (withOutline, _) = InsertDeclaration(text, parse, new("insertDeclaration") { Parent = container,+ Source = $"Rect2 {stem}Outline {{ center: [0mm,0mm]; size: [{Slice(text, dimensions.Items[0].Value.Span)}, {Slice(text, dimensions.Items[1].Value.Span)}]; }}" });+ var (withProfile, _) = InsertDeclaration(withOutline, Parse(withOutline), new("insertDeclaration") { Parent = container,+ Source = $"Profile {stem}Profile {{ Loop Outer {{ {stem}Outline |> TraceLoop }} }}" });+ return ReplaceDeclaration(withProfile, Parse(withProfile), new("replaceDeclaration") { Node = bodyId,+ Source = $"Compose {body.Name.Text} {{\n Base Stock {{ profile: {stem}Profile; from: 0mm; to: {Slice(text, dimensions.Items[2].Value.Span)}; role: Stock; }}\n {pocket}\n}}" });+ }+ if (body.Type.Name.Text != "Extrude" || body.Name is null)+ throw new FirmamentLanguageEditException("edit-pocket-base", "A pocket requires a profile-based Extrude or Compose. Choose a sketch-based part; primitive bodies keep their existing support limits.");+ var fields = Fields(body).ToArray();+ if (fields.Any(f => !new[] { "profile", "from", "to" }.Contains(f.Name.Text, StringComparer.OrdinalIgnoreCase)))+ throw new FirmamentLanguageEditException("edit-pocket-base-fields", "This Extrude has additional authored fields. Convert it to Compose explicitly so those requirements are preserved.");+ var stock = string.Join(" ", fields.Select(f => $"{f.Name.Text}: {Slice(text, f.Value.Span)};"));+ return ReplaceDeclaration(text, parse, new("replaceDeclaration") { Node = bodyId,+ Source = $"Compose {body.Name.Text} {{\n Base Stock {{ {stock} role: Stock; }}\n {pocket}\n}}" });+ }++ private static (string, string?) PatternFeature(string text, SyntaxParseResult parse, FirmamentLanguageEditOperation op)+ {+ var (id, seed) = Find(parse, op.Node);+ var grid = op.Grid ?? throw new FirmamentLanguageEditException("edit-input-required", "Specify rows, columns and grid pitch.");+ if (grid.Columns < 1 || grid.Rows < 1 || (long)grid.Columns * grid.Rows is < 2 or > 1024+ || !double.IsFinite(grid.PitchXmm) || !double.IsFinite(grid.PitchYmm)+ || grid.Columns > 1 && grid.PitchXmm == 0 || grid.Rows > 1 && grid.PitchYmm == 0)+ throw new FirmamentLanguageEditException("edit-grid-invalid", "Use 2–1024 total instances and finite nonzero pitch along each repeated direction.");+ var declarations = FirmamentLanguageOutlineService.Declarations(parse);+ var modifyId = declarations.First(d => d.Id == id).ParentId;+ var modify = Find(parse, modifyId).Syntax;+ if (seed.Type.Name.Text != "Hole" || modify.Type.Name.Text != "Modify" || seed.Name is null || seed.Body is null || seed.Clauses.Count > 0 || seed.Initializer is not null+ || seed.Body.Statements.Any(s => s is not FieldSyntax))+ throw new FirmamentLanguageEditException("edit-pattern-seed", "Select a field-based Hole in Modify. Other feature families retain their existing Pattern authoring path.");+ var fields = Fields(seed).ToArray();+ var center = fields.FirstOrDefault(f => f.Name.Text.Equals("center", StringComparison.OrdinalIgnoreCase));+ if (center?.Value is not CallSyntax { Target: ReferenceSyntax { Name.Text: "Point2" }, Arguments.Count: 2 } point)+ throw new FirmamentLanguageEditException("edit-pattern-center", "This grid action needs an authored Point2(x,y) center. It preserves expressions inside those coordinates; other center constructions require an explicit Feature/Set Pattern.");+ var container = declarations.First(d => d.Id == modifyId).ParentId;+ var name = RequireIdentifier(op.Name ?? "Copies", "Pattern name");+ var taken = declarations.Select(d => d.Syntax.Name?.Text).ToHashSet(StringComparer.Ordinal);+ if (new[] { name, name + "Points", name + "Recipe" }.Any(taken.Contains))+ throw new FirmamentLanguageEditException("edit-name-taken", $"Choose a different Pattern name; {name} or one of its supporting declarations already exists.");+ var x = Slice(text, point.Arguments[0].Value.Span); var y = Slice(text, point.Arguments[1].Value.Span);+ var points = new List<string>();+ for (var row = 0; row < grid.Rows; row++) for (var col = 0; col < grid.Columns; col++)+ {+ if (row == 0 && col == 0) continue; // Keep the original seed and its stable identity.+ points.Add($"r{row}c{col} => Point2(({x}) + {Number(col * grid.PitchXmm)}mm, ({y}) + {Number(row * grid.PitchYmm)}mm)");+ }+ var type = Slice(text, seed.Type.Span);+ var recipeFields = string.Join(" ", fields.Select(f => $"{f.Name.Text}: {(f == center ? "center" : Slice(text, f.Value.Span))};"));+ var (withRecipe, _) = InsertDeclaration(text, parse, new("insertDeclaration") { Parent = container,+ Source = $"Feature {name}Recipe(center: Point2) -> {type} {{ return {type} {{ {recipeFields} }} }}" });+ var (withPoints, _) = InsertDeclaration(withRecipe, Parse(withRecipe), new("insertDeclaration") { Parent = container,+ Source = $"Static {name}Points: Set<Point2> {{\n{string.Join("\n", points)}\n}}" });+ return InsertDeclaration(withPoints, Parse(withPoints), new("insertDeclaration") { Parent = modifyId, After = id,+ Source = $"Pattern {name} over {name}Points {{ p => {name}Recipe(center: p) }}" });+ }++ private static (string, string?) SetPlacement(string text, SyntaxParseResult parse, FirmamentLanguageEditOperation op)+ {+ var target = FindStatement(parse, op.Node);+ if (target.Statement is not DeclarationSyntax { Occurrence: true } occurrence || occurrence.Type.Name.Text is not ("Part" or "Assembly" or "Subassembly"))+ throw new FirmamentLanguageEditException("edit-placement-owner", "Select a placed Part or Subassembly.");+ var placement = op.Placement ?? throw new FirmamentLanguageEditException("edit-input-required", "Specify translation and rotation.");+ if (placement.TranslationMm.Length != 3 || placement.TranslationMm.Any(v => !double.IsFinite(v))+ || !double.IsFinite(placement.AngleDegrees) || placement.Axis is not ("X" or "Y" or "Z"))+ throw new FirmamentLanguageEditException("edit-placement-invalid", "Use three finite millimetre coordinates, an X/Y/Z axis and a finite angle in degrees.");+ var source = $"Placement {{ from: Origin; to: Parent; translateLocal: [{string.Join(", ", placement.TranslationMm.Select(v => Number(v) + "mm"))}]; rotateLocal: {{ axis: {placement.Axis}; angle: {Number(placement.AngleDegrees)}deg }} }}";+ // Occurrence bodies use the same structural insertion boundaries as definitions.+ var outline = FirmamentLanguageOutlineService.Outline(text, "edit", "edit");+ var children = outline.Nodes.Where(n => n.ParentId == target.Id && n.Kind == "Placement").ToArray();+ if (children.Length > 1) throw new FirmamentLanguageEditException("edit-placement-ambiguous", "This occurrence has multiple placements. Reconcile them in source first.");+ if (children.Length == 1)+ {+ var old = children[0]; var indent = Indent(text, old.Span.Start);+ return (Replace(text, old.Span.Start, old.Span.Length, FromSource(source, null, indent)[indent.Length..]), target.Id);+ }+ return InsertDeclaration(text, parse, new("insertDeclaration") { Parent = target.Id, Source = source });+ }++ private static bool IsAuthoringBody(DeclarationSyntax d) => d.Type.Name.Text is "Box" or "Cylinder" or "Sphere" or "Ellipsoid" or "Polyhedron" or "Extrude" or "Compose" or "Revolve" or "Sweep" or "Loft";+ private static string Slice(string source, FirmamentV2SourceSpan span) => source.Substring(span.Start, span.Length);+ private static string Number(double value) => value.ToString("G17", CultureInfo.InvariantCulture);+}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.csindex a2e4deef..6447fedd 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageEdit.cs@@ -30,8 +30,13 @@ public sealed record FirmamentLanguageEditOperation(string Kind)public string? Source { get; init; }/// <summary>extractFeature: the fields that become parameters; the rest stay fixed in the Feature.</summary>public IReadOnlyList<string>? Parameters { get; init; }+ public FirmamentGridEdit? Grid { get; init; }+ public FirmamentPlacementEdit? Placement { get; init; }}+public sealed record FirmamentGridEdit(int Columns, int Rows, double PitchXmm, double PitchYmm);+public sealed record FirmamentPlacementEdit(double[] TranslationMm, string Axis, double AngleDegrees);+/// <summary>A declaration to write: <c>Modifiers Kind<Variant> Name { Field: Value ... }</c>.</summary>public sealed record FirmamentDeclarationSpec(string Kind, string? Variant = null, IReadOnlyList<string>? Modifiers = null,string? Name = null, IReadOnlyList<FirmamentFieldSpec>? Fields = null);@@ -58,7 +63,7 @@ public sealed class FirmamentLanguageEditException(string code, string message)/// checked by parsing its result: an edit that adds a syntax error is refused. Parsing is the only/// gate here; whether the edited model builds is the compiler's decision./// </summary>-public static class FirmamentLanguageEditService+public static partial class FirmamentLanguageEditService{private static readonly Regex Identifier = new("^[A-Za-z_][A-Za-z0-9_]*$", RegexOptions.CultureInvariant);@@ -87,6 +92,11 @@ public static class FirmamentLanguageEditService"extractFeature" => ExtractFeature(text, before, operation),"nameFeature" => NameFeature(text, before, operation),+ "replaceDeclaration" => ReplaceDeclaration(text, before, operation),+ "patternFeature" => PatternFeature(text, before, operation),+ "extrudeProfile" => ExtrudeProfile(text, before, operation),+ "pocketProfile" => PocketProfile(text, before, operation),+ "setPlacement" => SetPlacement(text, before, operation),_ => throw new FirmamentLanguageEditException("edit-unknown-operation", $"Unknown edit operation '{operation.Kind}'.")};var after = Parse(next);diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageOutline.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageOutline.csindex a8789ec1..1a3591d6 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageOutline.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageOutline.cs@@ -20,6 +20,7 @@ public sealed record FirmamentOutlineNode(string Id, string Kind, string? Varianpublic string? Annotation { get; init; }/// <summary>Declared parameters with their types and defaults, as written (Feature, Template).</summary>public IReadOnlyList<FirmamentOutlineParameter> Signature { get; init; } = [];+ public FirmamentPlacementControls? PlacementControls { get; init; }}public sealed record FirmamentOutlineParameter(string Name, string Type, string? Default);@@ -249,6 +250,7 @@ public static class FirmamentLanguageOutlineServiceparameters, fields, entry.Children.Select(c => c.Id).ToArray()){Value = value,+ PlacementControls = entry.Kind == "Placement" ? FirmamentLanguageEditService.PlacementControls(d) : null,Annotation = d.Annotation is null ? null : Text(source, d.Annotation.Span),Signature = d.Parameters.Where(p => p.Name is not null).Select(p => new FirmamentOutlineParameter(p.Name!.Text,Text(source, p.Value.Span), p.Default is null ? null : Text(source, p.Default.Span))).ToArray(),diff --git a/Aetheris.Kernel.Firmament/Materializer/AirHoleCompositeMaterializer.cs b/Aetheris.Kernel.Firmament/Materializer/AirHoleCompositeMaterializer.csindex 76751e5b..394dbd09 100644--- a/Aetheris.Kernel.Firmament/Materializer/AirHoleCompositeMaterializer.cs+++ b/Aetheris.Kernel.Firmament/Materializer/AirHoleCompositeMaterializer.cs@@ -88,9 +88,11 @@ internal static class AirHoleCompositeMaterializer}var wallFaces = new Dictionary<string, FaceId>(StringComparer.Ordinal);+ var hostFaces = new Dictionary<string, FaceId>(StringComparer.Ordinal);var duplicateWallOrigin = false;var built = BrepBooleanBoxCylinderHoleBuilder.BuildComposition(composition, ToleranceContext.Default,- (featureId, faceId) => { if (!wallFaces.TryAdd(featureId, faceId)) duplicateWallOrigin = true; });+ (featureId, faceId) => { if (!wallFaces.TryAdd(featureId, faceId)) duplicateWallOrigin = true; },+ (role, faceId) => hostFaces.Add(role, faceId));if (!built.IsSuccess || built.Value is null){diagnostics.Add("air-hole-x4 composite BRep build failed.");@@ -107,8 +109,11 @@ internal static class AirHoleCompositeMaterializer$"material:hole:{plan.SemanticFeatureId}:wall", "Face", SemanticTopologyRole.HoleWallFace,$"hole:{plan.SemanticFeatureId}", Face: wallFaces[plan.SemanticFeatureId], ParentStableId: plan.SemanticFeatureId,Addressability: SemanticTopologyAddressability.DerivedStable)).ToArray();- var correspondence = new SemanticTopologyCorrespondence(plans[0].SemanticFeature.TargetBodyId ?? "semantic-hole-host",- descendants, ["HoleAIR", "AirHoleCompositeMaterializer", "BrepBooleanBoxCylinderHoleBuilder"]);+ var hostId = plans[0].SemanticFeature.TargetBodyId ?? "semantic-hole-host";+ var retained = hostFaces.TryGetValue("-Z", out var bottom) && hostFaces.TryGetValue("+Z", out var top)+ ? BoxConstructionCorrespondence.RetainedCaps(hostId, bottom, top) : [];+ var correspondence = new SemanticTopologyCorrespondence(hostId,+ [.. descendants, .. retained], ["HoleAIR", "AirHoleCompositeMaterializer", "BrepBooleanBoxCylinderHoleBuilder", "RetainedBoxCaps"]);diagnostics.Add("air-hole-x4 composite materialization succeeded through semantic AirHoleFeature plans and safe boolean AP242 BRep composition.");return new(true, built.Value, plans, diagnostics, correspondence);}diff --git a/Aetheris.Kernel.Firmament/Materializer/AirHoleSimpleShaftMaterializer.cs b/Aetheris.Kernel.Firmament/Materializer/AirHoleSimpleShaftMaterializer.csindex 8054b259..0c344812 100644--- a/Aetheris.Kernel.Firmament/Materializer/AirHoleSimpleShaftMaterializer.cs+++ b/Aetheris.Kernel.Firmament/Materializer/AirHoleSimpleShaftMaterializer.cs@@ -258,7 +258,9 @@ internal static class AirHoleSimpleShaftMaterializernew($"material:{source}:exit-edge", "Edge", SemanticTopologyRole.BottomBoundary, source, Edge: EdgeOf(exitLoop), ParentStableId: plan.SemanticFeatureId, Addressability: SemanticTopologyAddressability.DerivedStable),new($"material:{source}:wall", "Face", SemanticTopologyRole.HoleWallFace, source, Face: wall.Id, ParentStableId: plan.SemanticFeatureId, Addressability: SemanticTopologyAddressability.DerivedStable)};- return new(plan.SemanticFeature.TargetBodyId ?? "semantic-hole-host", descendants, ["HoleAIR", "AirHoleSimpleShaftMaterializationPlan", "ThroughHoleConstructionRecipe", "BrepSurgery"]);+ var hostId = plan.SemanticFeature.TargetBodyId ?? "semantic-hole-host";+ return new(hostId, [.. descendants, .. BoxConstructionCorrespondence.RetainedCaps(hostId, bottom.Id, top.Id)],+ ["HoleAIR", "AirHoleSimpleShaftMaterializationPlan", "ThroughHoleConstructionRecipe", "BrepSurgery", "RetainedBoxCaps"]);}private static IEnumerable<ProfileStackLayer> BuildLayers(AirHoleFeature feature, AirHoleSimpleShaftHost host, double cutZMin, double cutZMax)diff --git a/Aetheris.Kernel.Firmament/Materializer/BoxConstructionCorrespondence.cs b/Aetheris.Kernel.Firmament/Materializer/BoxConstructionCorrespondence.csindex 898b9125..912adad3 100644--- a/Aetheris.Kernel.Firmament/Materializer/BoxConstructionCorrespondence.cs+++ b/Aetheris.Kernel.Firmament/Materializer/BoxConstructionCorrespondence.cs@@ -1,4 +1,5 @@using Aetheris.Kernel.Core.Brep.Features;+using Aetheris.Kernel.Core.Topology;using Aetheris.Kernel.Firmament.FirmamentV2;namespace Aetheris.Kernel.Firmament.Materializer;@@ -6,6 +7,14 @@ namespace Aetheris.Kernel.Firmament.Materializer;/// <summary>Maps the IDs captured by the Box extrusion itself to existing axis selectors.</summary>public static class BoxConstructionCorrespondence{+ /// <summary>The retained world-Z stock caps emitted by the qualified box/hole construction.</summary>+ public static IReadOnlyList<SemanticTopologyDescendant> RetainedCaps(string bodyStableId, FaceId bottom, FaceId top) =>+ [+ new($"{bodyStableId}.face(-Z)", "Face", SemanticTopologyRole.BoxFace, bodyStableId, Face: bottom, ParentStableId: bodyStableId,+ FirmamentSelector: "face(-Z)", Addressability: SemanticTopologyAddressability.DerivedStable),+ new($"{bodyStableId}.face(+Z)", "Face", SemanticTopologyRole.BoxFace, bodyStableId, Face: top, ParentStableId: bodyStableId,+ FirmamentSelector: "face(+Z)", Addressability: SemanticTopologyAddressability.DerivedStable)+ ];public static SemanticTopologyCorrespondence Create(string bodyStableId, BrepExtrudeConstructionTopology topology, FirmamentV2SourceSpan? sourceSpan = null){ArgumentNullException.ThrowIfNull(topology);diff --git a/Aetheris.Web.Runtime/sdk/README.md b/Aetheris.Web.Runtime/sdk/README.mdindex c7051828..021713c1 100644--- a/Aetheris.Web.Runtime/sdk/README.md+++ b/Aetheris.Web.Runtime/sdk/README.md@@ -211,3 +211,23 @@ error code and explanation, with no source mutation.This first contract addresses authored Profiles in one document. It does notrewrite included/generated declarations. See [the authoring guide](../../../docs/public/firmament/sketcher.md).++### Pending graph authoring++`language.edit` also prepares `replaceDeclaration`, `patternFeature`,+`extrudeProfile`, `pocketProfile`, and `setPlacement` operations. These operate on+the existing structural AST. Preparing an edit does not admit its geometry:+compile the candidate in a separate model handle before committing its exact+source splice, and dispose that preview when controls change or it is cancelled.+Keep revision checks and source undo history in the host.++`patternFeature` currently repeats a field-based Hole in Modify, keeping the seed+and keyed row/column copies. `pocketProfile` targets Compose or qualified plain+Box/Extrude stock. `extrudeProfile` changes the extrusion end while preserving+its authored start. Full compilation remains the capability authority.++Outline Placement nodes expose optional `placementControls`: literal+Origin-to-Parent translation and one-axis rotation, or a disclosed read-only+reason. General matrices, expressions and named-frame relationships must not be+flattened into editable numbers. Support picking similarly requires an actual+compiler-owned selector; display face identity alone is insufficient.diff --git a/Aetheris.Web.Runtime/sdk/src/index.d.ts b/Aetheris.Web.Runtime/sdk/src/index.d.tsindex fcb186fa..31f4fbdd 100644--- a/Aetheris.Web.Runtime/sdk/src/index.d.ts+++ b/Aetheris.Web.Runtime/sdk/src/index.d.ts@@ -49,7 +49,7 @@ export interface LanguageAnalysis { readonly document: string; readonly revisionexport interface OutlineSpan { readonly start: number; readonly length: number }export interface OutlineField { readonly name: string; readonly text: string; readonly shape: 'quantity' | 'number' | 'string' | 'boolean' | 'version' | 'entityreference' | 'reference' | 'member' | 'sequence' | 'call' | 'specialization' | 'object' | 'expression' | 'other'; readonly span: OutlineSpan; readonly valueSpan: OutlineSpan }/** One declaration. `id` is its name path (`MotorMount/Modify:Body/Pilot`): stable across edits that keep names, kinds and nesting. */-export interface OutlineNode { readonly id: string; readonly kind: string; readonly variant: string | null; readonly modifiers: readonly string[]; readonly name: string | null; readonly occurrence: boolean; readonly parentId: string | null; readonly order: number; readonly span: OutlineSpan; readonly nameSpan: OutlineSpan | null; readonly schemaId: string | null; readonly parameters: readonly string[]; readonly fields: readonly OutlineField[]; readonly children: readonly string[]; /** A bare call placed in a body (`MountHole(center: …)`): `kind` is the callee, `fields` its arguments (positional ones named `#1`…). */ readonly call?: boolean; /** The initializer of a value declaration (`Static Thickness: Length = 8mm`), named `=`. */ readonly value?: OutlineField | null; /** The declared type annotation, as written. */ readonly annotation?: string | null; /** Declared parameters with types and defaults (Feature, Template). */ readonly signature?: readonly OutlineParameter[] }+export interface OutlineNode { readonly id: string; readonly kind: string; readonly variant: string | null; readonly modifiers: readonly string[]; readonly name: string | null; readonly occurrence: boolean; readonly parentId: string | null; readonly order: number; readonly span: OutlineSpan; readonly nameSpan: OutlineSpan | null; readonly schemaId: string | null; readonly parameters: readonly string[]; readonly fields: readonly OutlineField[]; readonly children: readonly string[]; /** A bare call placed in a body (`MountHole(center: …)`): `kind` is the callee, `fields` its arguments (positional ones named `#1`…). */ readonly placementControls?: { readonly translationMm: readonly number[]; readonly axis: string; readonly angleDegrees: number; readonly readOnlyReason?: string | null } | null; readonly call?: boolean; /** The initializer of a value declaration (`Static Thickness: Length = 8mm`), named `=`. */ readonly value?: OutlineField | null; /** The declared type annotation, as written. */ readonly annotation?: string | null; /** Declared parameters with types and defaults (Feature, Template). */ readonly signature?: readonly OutlineParameter[] }export interface OutlineParameter { readonly name: string; readonly type: string; readonly default: string | null }/** A resolved name use from one declaration to another. `via` is `field:<Name>`, `clause:<Using|Over|On|From|Key>`, `target`, `body`, `argument:<Name|type>`, `annotation`, `result` or `initializer`; nested object fields append `.<Name>`. */export interface OutlineEdge { readonly from: string; readonly to: string; readonly kind: 'reference' | 'call' | 'specialization' | 'modifies' | 'asserts' | 'recognizes'; readonly via: string; readonly member: string | null; readonly span: OutlineSpan; readonly ambiguous: boolean; readonly toDocument: string | null }@@ -69,7 +69,12 @@ export type LanguageEditOperation =| { readonly kind: 'moveDeclaration'; readonly node: string; readonly after?: string; readonly first?: boolean }| { readonly kind: 'insertFeature'; readonly node: string; readonly source: string; readonly name?: string }| { readonly kind: 'extractFeature'; readonly node: string; readonly name: string; readonly parameters?: readonly string[] }- | { readonly kind: 'nameFeature'; readonly node?: string; readonly span?: OutlineSpan; readonly name?: string };+ | { readonly kind: 'nameFeature'; readonly node?: string; readonly span?: OutlineSpan; readonly name?: string }+ | { readonly kind: 'replaceDeclaration'; readonly node: string; readonly source: string }+ | { readonly kind: 'patternFeature'; readonly node: string; readonly name: string; readonly grid: { readonly columns: number; readonly rows: number; readonly pitchXmm: number; readonly pitchYmm: number } }+ | { readonly kind: 'extrudeProfile'; readonly node: string; readonly value: string; readonly name?: string }+ | { readonly kind: 'pocketProfile'; readonly node?: string; readonly parent: string; readonly value: string; readonly name?: string; readonly declaration?: DeclarationSpec }+ | { readonly kind: 'setPlacement'; readonly node: string; readonly placement: { readonly translationMm: readonly number[]; readonly axis: 'X' | 'Y' | 'Z'; readonly angleDegrees: number } };/** The edited source and the single replacement `[start, start + length)` → `replacement` that produces it from the original. `nodes` holds the outline id each operation left behind (created, renamed or edited), in order; removals add none. */export interface LanguageEdit { readonly document: string; readonly revision: string; readonly text: string; readonly changed: boolean; readonly edit: { readonly start: number; readonly length: number; readonly replacement: string }; readonly nodes: readonly string[]; readonly warnings: readonly string[] }/** 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. */diff --git a/Aetheris.Web.Runtime/telos/src/sketch.ts b/Aetheris.Web.Runtime/telos/src/sketch.tsindex 4d99b5a3..8382b435 100644--- a/Aetheris.Web.Runtime/telos/src/sketch.ts+++ b/Aetheris.Web.Runtime/telos/src/sketch.ts@@ -23,6 +23,8 @@ export interface SketchCallbacks {apply(request: SketchEditRequest): Promise<string | null>;source(span: { start: number; length: number }): void;close(): void;+ /** Host-owned new-document action, including any unsaved-source decision. */+ createPart?(): void;}const ns = 'http://www.w3.org/2000/svg';@@ -132,6 +134,12 @@ export class SketchWorkspace {button(create, text, () => void this.apply({ kind: 'create', node: parent.value, shape })).disabled = this.pending;this.host.append(create);}+ if (this.view && !this.view.profiles.length && !this.view.emptyModels.length && this.callbacks.createPart) {+ const start = document.createElement('div'); start.style.cssText = 'padding:8px 14px;display:flex;gap:12px;align-items:center';+ const explanation = document.createElement('span'); explanation.textContent = 'This part has no editable profile. Start a separate sketch part with a rectangle and extrusion.'; start.append(explanation);+ button(start, 'New sketch part', () => this.callbacks.createPart!()).disabled = this.pending;+ this.host.append(start);+ }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);@@ -194,7 +202,8 @@ export class SketchWorkspace {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.'+ ? this.callbacks.createPart ? 'No authored Profile in this document. Start a new sketch part above, or open a document containing a Profile.'+ : '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);}diff --git a/fixtures/Regression/GraphAuthoring/README.md b/fixtures/Regression/GraphAuthoring/README.mdnew file mode 100644index 00000000..75a04767--- /dev/null+++ b/fixtures/Regression/GraphAuthoring/README.md@@ -0,0 +1,8 @@+# Graph authoring inputs++These sources exercise the compiler-owned structural edit API. `plate`,+`placement`, and `assembly-starter` are complete accepted documents.+`profile.firmament` is intentionally an unfinished authoring input: its Profile+becomes an admitted solid only after `extrudeProfile`. It is not a must-build+corpus specimen. `FirmamentGraphAuthoringTests` qualifies the resulting source,+stable feature identities, retained support faces, placements and leaf geometry.diff --git a/fixtures/Regression/GraphAuthoring/assembly-starter.firmament b/fixtures/Regression/GraphAuthoring/assembly-starter.firmamentnew file mode 100644index 00000000..a38acdf5--- /dev/null+++ b/fixtures/Regression/GraphAuthoring/assembly-starter.firmament@@ -0,0 +1,19 @@+Units: mm+Template < H: Length > Struct WebBlock {+ Circle2 Circle { Center: [0mm,0mm] Radius: 4mm }+ Profile Section { Loop Outer { Circle |> TraceLoop } }+ Extrude Body { Profile: Section From: 0mm To: H }+ Expose {+ Semantic Bottom { DatumFrame Frame = [0mm,0mm,0mm] x [1,0,0] y [0,1,0] z [0,0,1]; }+ Semantic Top { DatumFrame Frame = [0mm,0mm,H] x [1,0,0] y [0,1,0] z [0,0,1]; }+ }+}+Assembly WebBlockPair {+ <Assembly WebBlockPair>+ <Part Fixed = WebBlock<H: 10mm>></Part>+ <Part Moving = WebBlock<H: 8mm>>+ Placement { from: Origin; to: Parent; translateLocal: [20mm,0mm,0mm]; rotateLocal: { axis: Z; angle: 0deg } }+ </Part>+ </Assembly>+ Anchor: WebBlockPair.Fixed;+}diff --git a/fixtures/Regression/GraphAuthoring/placement.firmament b/fixtures/Regression/GraphAuthoring/placement.firmamentnew file mode 100644index 00000000..cb086c4a--- /dev/null+++ b/fixtures/Regression/GraphAuthoring/placement.firmament@@ -0,0 +1,10 @@+Template<H: Length> Struct Post { Cylinder Body { radius: 4mm height: H } }+Assembly Pair {+ <Assembly Pair>+ <Part A = Post<H:10mm>></Part>+ <Part B = Post<H:8mm>>+ Placement Old = [1,0,0,0,0,1,0,0,0,0,1,0,20,0,0,1];+ </Part>+ </Assembly>+ Anchor: Pair.A;+}diff --git a/fixtures/Regression/GraphAuthoring/plate.firmament b/fixtures/Regression/GraphAuthoring/plate.firmamentnew file mode 100644index 00000000..758abc2e--- /dev/null+++ b/fixtures/Regression/GraphAuthoring/plate.firmament@@ -0,0 +1,7 @@+Model Part {+ units: mm+ Box Stock { size: [80mm, 60mm, 8mm] }+ Modify Stock {+ Hole<Shaft> Seed { on: +Z center: Point2(-20mm, -10mm) diameter: 4mm end: ThroughAll }+ }+}diff --git a/fixtures/Regression/GraphAuthoring/profile.firmament b/fixtures/Regression/GraphAuthoring/profile.firmamentnew file mode 100644index 00000000..535b0a5d--- /dev/null+++ b/fixtures/Regression/GraphAuthoring/profile.firmament@@ -0,0 +1,5 @@+Model Part {+ units: mm+ Rect2 Outline { center: [0mm,0mm] size: [80mm,60mm] }+ Profile Section { Loop Outer { Outline |> TraceLoop } }+}