Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Fix assembly motion admission and schema field projection
Yuechen Licb80b05a9bfa
diff --git a/Aetheris.CLI.Tests/AssemblyMotionCommandTests.cs b/Aetheris.CLI.Tests/AssemblyMotionCommandTests.csindex c5c619ce..cf5b794e 100644--- a/Aetheris.CLI.Tests/AssemblyMotionCommandTests.cs+++ b/Aetheris.CLI.Tests/AssemblyMotionCommandTests.cs@@ -4,6 +4,21 @@ namespace Aetheris.CLI.Tests;public sealed class AssemblyMotionCommandTests{+ [Theory]+ [InlineData("articulated-motion.firmament")]+ [InlineData("articulated-module-motion.firmament")]+ public void NormalValidateAndBuildAdmitTheSameClipAssembly(string name)+ {+ var root = new DirectoryInfo(AppContext.BaseDirectory);+ while (root is not null && !File.Exists(Path.Combine(root.FullName, "Aetheris.slnx"))) root = root.Parent;+ var fixture = Path.Combine(root!.FullName, "fixtures/Canonical/AssemblyInterfaces", name);+ var output = Path.Combine(root.FullName, "artifacts/local/tests/motion", Guid.NewGuid().ToString("N") + ".step");+ var stdout = new StringWriter(); var stderr = new StringWriter();+ Assert.Equal(0, CliRunner.Run(["validate", fixture, "--json"], stdout, stderr));+ Assert.Equal(0, CliRunner.Run(["build", fixture, "--output", output, "--json"], stdout, stderr));+ Assert.True(File.Exists(output));+ }+[Fact]public void CliSamplesAdmittedClipAndRejectsMissingMotion(){diff --git a/Aetheris.CLI/CliRunner.cs b/Aetheris.CLI/CliRunner.csindex ee6c0988..be3581d2 100644--- a/Aetheris.CLI/CliRunner.cs+++ b/Aetheris.CLI/CliRunner.cs@@ -497,7 +497,7 @@ public static class CliRunner{ stderr.WriteLine("garment-step-export-unsupported: Fabric is a material-space surface; use garment build or garment drape."); return 1; }if (Aetheris.Kernel.Firmament.Scene.SceneAuthoring.HasRoot(source)){ stderr.WriteLine("scene-step-export-unsupported: Scene is a spatial product; use scene export-usd or scene export-glb."); return 1; }- if (Path.GetExtension(sourcePath).Equals(".firmasm", StringComparison.OrdinalIgnoreCase) || FirmamentLanguageAnalysisService.HasAssemblyRoot(source))+ if (Path.GetExtension(sourcePath).Equals(".firmasm", StringComparison.OrdinalIgnoreCase) || FirmamentLanguageAnalysisService.HasAssemblyRoot(source, sourcePath))return RunAsmExportAp242([sourcePath, "--out", outPath ?? Path.GetFullPath(Path.Combine("artifacts", "local", "build", Path.GetFileNameWithoutExtension(sourcePath) + ".step")), .. (json ? new[] { "--json" } : [])], stdout, stderr);if (SectionChainAuthoringParser.IsSectionChainSource(source))return RunSectionChain(["build", sourcePath, .. (outPath is null ? Array.Empty<string>() : ["--out", outPath]), .. (json ? new[] { "--json" } : [])], stdout, stderr);@@ -1418,7 +1418,7 @@ Model CanonicalPanel {return GarmentCommand.Run(["inspect", .. args], stdout, stderr);if (File.Exists(input) && Aetheris.Kernel.Firmament.Scene.SceneAuthoring.HasRoot(File.ReadAllText(input)))return SceneCommand.Run(["inspect", .. args], stdout, stderr);- if (File.Exists(input) && (Path.GetExtension(input).Equals(".firmasm", StringComparison.OrdinalIgnoreCase) || FirmamentLanguageAnalysisService.HasAssemblyRoot(File.ReadAllText(input))))+ if (File.Exists(input) && (Path.GetExtension(input).Equals(".firmasm", StringComparison.OrdinalIgnoreCase) || FirmamentLanguageAnalysisService.HasAssemblyRoot(File.ReadAllText(input), input)))return RunAsmInspect(args, stdout, stderr);var json = args.Skip(1).SequenceEqual(["--json"]);if (!json && args.Length > 1) { stderr.WriteLine($"Unknown inspect option '{args[1]}'."); stderr.WriteLine(InspectUsage); return 1; }@@ -2367,7 +2367,7 @@ Model CanonicalPanel {if (Aetheris.Kernel.Firmament.Garment.GarmentAuthoring.HasRoot(validationSource)|| frontend.Schema == FirmamentFrontendSchema.Garment)return GarmentCommand.Run(["inspect", sourcePath, .. (json ? new[] { "--json" } : Array.Empty<string>())], stdout, stderr);- if (FirmamentLanguageAnalysisService.HasAssemblyRoot(validationSource))+ if (FirmamentLanguageAnalysisService.HasAssemblyRoot(validationSource, sourcePath)){var sheetMetalAssembly = validationSource.Contains("Use SheetMetal.ProductFamilies", StringComparison.Ordinal);var parsedAssembly = parseOnly ? sheetMetalAssembly@@ -4072,7 +4072,7 @@ Model CanonicalPanel {var builds = new List<object>();if (repeatRequested){- if (!FirmamentLanguageAnalysisService.HasAssemblyRoot(sourceText) || usesSheetMetalParts)+ if (!FirmamentLanguageAnalysisService.HasAssemblyRoot(sourceText, path) || usesSheetMetalParts){ stderr.WriteLine("--repeat requires a canonical authored assembly using the ordinary M1 materializer."); return 1; }using var session = new FirmamentCompilationSession();AssemblyM1CompilationResult? last = null;diff --git a/Aetheris.Firmament.SchemaGenerator/SemanticSchemaGenerator.cs b/Aetheris.Firmament.SchemaGenerator/SemanticSchemaGenerator.csindex c8b61b20..c5e5d38d 100644--- a/Aetheris.Firmament.SchemaGenerator/SemanticSchemaGenerator.cs+++ b/Aetheris.Firmament.SchemaGenerator/SemanticSchemaGenerator.cs@@ -50,8 +50,11 @@ public sealed class SemanticSchemaGenerator : IIncrementalGeneratorvar unit = unitConstant.Value is int unitValue ? EnumName(unitConstant, unitValue) : kind == "Length" ? "Length" : kind == "Angle" ? "Angle" : "None";var choiceConstant = Named(attribute, "Choices");var choices = choiceConstant.Kind == TypedConstantKind.Array ? choiceConstant.Values.Select(v => v.Value?.ToString() ?? "").ToArray() : Array.Empty<string>();+ var variantConstant = Named(attribute, "Variants");+ var variants = variantConstant.Kind == TypedConstantKind.Array ? variantConstant.Values.Select(v => v.Value?.ToString() ?? "").ToArray() : Array.Empty<string>();if (!ValidId(fieldId) || !ValidId(fieldName) || !fieldIds.Add(fieldId) || !fieldNames.Add(fieldName) || !Kinds.Contains(kind)|| kind == "Choice" && choices.Length == 0 || kind != "Choice" && choices.Length != 0+ || variants.Any(v => !ValidId(v)) || variants.Distinct(StringComparer.Ordinal).Count() != variants.Length|| unit is not ("None" or "Length" or "Angle")|| kind == "Length" && unit != "Length" || kind == "Angle" && unit != "Angle"|| kind is not ("Length" or "Angle" or "Vector" or "Point") && unit != "None")@@ -67,7 +70,7 @@ public sealed class SemanticSchemaGenerator : IIncrementalGenerator{ Error(output, symbol, $"source-editable field '{fieldName}' in {name} requires one public static double projector with one semantic-instance parameter"); continue; }fields.Add(new(fieldId, fieldName, kind, unit, Bool(attribute, "Required"), Str(attribute, "Default"), Str(attribute, "Description"), choices,editable, projectorName, projector?.Parameters[0].Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),- symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)));+ symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), variants));}else if (attribute.AttributeClass?.Name == "FirmamentOutputAttribute"){@@ -88,7 +91,7 @@ public sealed class SemanticSchemaGenerator : IIncrementalGeneratorsource.Append(" new(new FirmamentConstructId(").Append(Q(entry.Id)).Append("), ").Append(Q(entry.Name)).Append(", ").Append(Q(entry.Context)).Append(", ").Append(Q(entry.Snippet)).Append(", ").Append(Q(entry.Description)).Append(", ").Append(Q(entry.Alias)).Append(",\n System.Array.AsReadOnly(new FirmamentFieldSchema[] {\n");foreach (var field in entry.Fields){- source.Append(" new(new FirmamentFieldId(").Append(Q(entry.Id + "." + field.Id)).Append("), ").Append(Q(field.Name)).Append(", FirmamentSchemaValueKind.").Append(field.Kind).Append(", FirmamentUnitKind.").Append(field.Unit).Append(", ").Append(field.Required ? "true" : "false").Append(", ").Append(Q(field.Default)).Append(", System.Array.AsReadOnly(new string[] { ").Append(string.Join(", ", field.Choices.Select(Q))).Append(" }), ").Append(Q(field.Description)).Append(", ").Append(field.Editable ? "true" : "false").Append("),\n");+ source.Append(" new(new FirmamentFieldId(").Append(Q(entry.Id + "." + field.Id)).Append("), ").Append(Q(field.Name)).Append(", FirmamentSchemaValueKind.").Append(field.Kind).Append(", FirmamentUnitKind.").Append(field.Unit).Append(", ").Append(field.Required ? "true" : "false").Append(", ").Append(Q(field.Default)).Append(", System.Array.AsReadOnly(new string[] { ").Append(string.Join(", ", field.Choices.Select(Q))).Append(" }), ").Append(Q(field.Description)).Append(", ").Append(field.Editable ? "true" : "false").Append(") { Variants = System.Array.AsReadOnly(new string[] { ").Append(string.Join(", ", field.Variants.Select(Q))).Append(" }) },\n");}source.Append(" }), System.Array.AsReadOnly(new FirmamentOutputSchema[] {\n");foreach (var item in entry.Outputs)@@ -119,7 +122,7 @@ public sealed class SemanticSchemaGenerator : IIncrementalGeneratorprivate sealed record Entry(string Id, string Name, string? Context, string? Snippet, string? Description, string? Alias, Field[] Fields, Output[] Outputs);private sealed record Field(string Id, string Name, string Kind, string Unit, bool Required, string? Default, string? Description, string[] Choices,- bool Editable, string? ProjectorName, string? ProjectorType, string ProjectorOwner);+ bool Editable, string? ProjectorName, string? ProjectorType, string ProjectorOwner, string[] Variants);private sealed record Output(string Id, string Name, string Kind, bool Addressable, string? Role);}diff --git a/Aetheris.Kernel.Firmament.Tests/Assembly/FirmamentProjectSnapshotTests.cs b/Aetheris.Kernel.Firmament.Tests/Assembly/FirmamentProjectSnapshotTests.csindex 641cb42b..fc1811c8 100644--- a/Aetheris.Kernel.Firmament.Tests/Assembly/FirmamentProjectSnapshotTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/Assembly/FirmamentProjectSnapshotTests.cs@@ -4,6 +4,20 @@ namespace Aetheris.Kernel.Firmament.Tests.Assembly;public sealed class FirmamentProjectSnapshotTests{+ [Fact]+ public void IncludedAssemblyRootAdmitsItsMotionInAProjectSnapshot()+ {+ var directory = Path.GetDirectoryName(FirmamentCorpusHarness.ResolveFixtureFullPath(+ "fixtures/Canonical/AssemblyInterfaces/articulated-motion.firmament"))!;+ var project = new FirmamentProjectSnapshot("motion.firmament", [+ KeyValuePair.Create("motion.firmament", File.ReadAllText(Path.Combine(directory, "articulated-motion.firmament"))),+ KeyValuePair.Create("articulated-subassemblies.firmament", File.ReadAllText(Path.Combine(directory, "articulated-subassemblies.firmament")))]);+ var result = new AssemblyM1Pipeline().CompileProject(project);+ Assert.True(result.IsSuccess, string.Join(Environment.NewLine, result.Diagnostics.Select(d => $"{d.Code}: {d.Message}")));+ Assert.Single(result.Ir!.Motions);+ Assert.True(AssemblyMotion.Evaluate(result.Ir, "Cycle", 1.25).IsSuccess);+ }+[Fact]public void PathsAreNormalizedAndCannotEscapeTheProject(){diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentHeliosAuthoringFeedbackTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentHeliosAuthoringFeedbackTests.csnew file mode 100644index 00000000..4e84dbaa--- /dev/null+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentHeliosAuthoringFeedbackTests.cs@@ -0,0 +1,61 @@+using Aetheris.Kernel.Firmament.FirmamentV2;++namespace Aetheris.Kernel.Firmament.Tests;++public sealed class FirmamentHeliosAuthoringFeedbackTests+{+ private static string Source(string name) => File.ReadAllText(FirmamentCorpusHarness.ResolveFixtureFullPath(+ $"fixtures/Regression/LanguageService/{name}.firmament"));++ [Theory]+ [InlineData("Shaft", "")]+ [InlineData("Counterbore", " counterboreDiameter: 14mm\n counterboreDepth: 3mm\n")]+ [InlineData("Countersink", " countersinkDiameter: 14mm\n countersinkAngle: 90deg\n")]+ public void HoleCompletionAndProjectionExposeOnlyItsAdmittedVariant(string variant, string relief)+ {+ var source = Source("hole-variant").Replace("<Shaft>", $"<{variant}>").Replace(" end:", relief + " end:");+ var offset = source.IndexOf(" on:", StringComparison.Ordinal);+ var completion = FirmamentLanguageService.Complete(source, "bracket.firmament", "1", offset);+ Assert.Equal("Hole", completion.Context);+ Assert.Equal(variant == "Counterbore", completion.Fields.Any(f => f.Name == "CounterboreDepth"));+ Assert.Equal(variant == "Countersink", completion.Fields.Any(f => f.Name == "CountersinkAngle"));+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.NotNull(parsed.Document);+ var hole = Assert.Single(FirmamentFieldProjector.Project(parsed.Document, source, "bracket.firmament", 1), p => p.SemanticId == "Base.CenterMount");+ Assert.Equal(variant == "Counterbore", hole.Fields.Any(f => f.Name == "CounterboreDepth"));+ Assert.Equal(variant == "Countersink", hole.Fields.Any(f => f.Name == "CountersinkAngle"));+ var compiled = FirmamentBuildAndExport.CompileSource(source);+ Assert.True(compiled.IsSuccess, string.Join(';', compiled.Diagnostics.Select(d => d.Message)));+ }++ [Fact]+ public void ShaftReliefFieldsRejectAtTheirSpansWithoutAMisleadingModelError()+ {+ var source = Source("hole-variant").Replace(" end:", " counterboreDepth: 3mm\n counterboreDiameter: 14mm\n end:");+ var parsed = FirmamentV2Parser.Parse(source);+ Assert.Null(parsed.Document);+ Assert.DoesNotContain(parsed.Diagnostics, d => d == FirmamentV2Parser.CanonicalDocumentMalformed);+ var analysis = FirmamentLanguageAnalysisService.Analyze(source, "bracket.firmament", "1");+ foreach (var field in new[] { "counterboreDepth", "counterboreDiameter" })+ {+ var diagnostic = Assert.Single(analysis.Diagnostics, d => d.Code.EndsWith(":" + char.ToUpperInvariant(field[0]) + field[1..], StringComparison.Ordinal));+ Assert.Equal(source.IndexOf(field, StringComparison.Ordinal), diagnostic.Start);+ }+ var build = FirmamentBuildAndExport.CompileSource(source);+ Assert.False(build.IsSuccess);+ Assert.DoesNotContain(build.Diagnostics, d => d.Message == "firmament-v2-parse-failed");+ }++ [Fact]+ public void EmptyModifyBindsItsTargetAndBuildsExactlyTheUnmodifiedStock()+ {+ var source = Source("empty-modify");+ var actual = FirmamentBuildAndExport.CompileSource(source);+ var stock = FirmamentBuildAndExport.CompileSource(source.Replace(" Modify Base {}", ""));+ Assert.True(actual.IsSuccess, string.Join(';', actual.Diagnostics.Select(d => d.Message)));+ Assert.True(stock.IsSuccess);+ Assert.Equal(stock.Value.StepText, actual.Value.StepText);+ Assert.False(FirmamentBuildAndExport.CompileSource(source.Replace("Modify Base", "Modify Missing")).IsSuccess);+ Assert.DoesNotContain(FirmamentLanguageAnalysisService.Analyze(source, "bracket.firmament", "1").Diagnostics, d => d.Severity == "error");+ }+}diff --git a/Aetheris.Kernel.Firmament.Tests/FirmamentLanguageEditTests.cs b/Aetheris.Kernel.Firmament.Tests/FirmamentLanguageEditTests.csindex 9c976558..f35b4700 100644--- a/Aetheris.Kernel.Firmament.Tests/FirmamentLanguageEditTests.cs+++ b/Aetheris.Kernel.Firmament.Tests/FirmamentLanguageEditTests.cs@@ -5,7 +5,8 @@ namespace Aetheris.Kernel.Firmament.Tests;public sealed class FirmamentLanguageEditTests{- private const string Bracket = """+ // Assertions below deliberately use LF; keep the specimen independent of checkout line endings.+ private static readonly string Bracket = """// Mounting plateModel WebBracket {Units: mm@@ -15,7 +16,7 @@ public sealed class FirmamentLanguageEditTests}}- """;+ """.ReplaceLineEndings("\n");private static FirmamentLanguageEdit Edit(string source, params FirmamentLanguageEditOperation[] operations) =>FirmamentLanguageEditService.Apply(source, "bracket.firmament", "1", operations);diff --git a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.csindex 8cdc9860..c37f701e 100644--- a/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs+++ b/Aetheris.Kernel.Firmament/Assembly/AssemblyM1Execution.cs@@ -428,7 +428,7 @@ public sealed class AssemblyM1Pipeline{ArgumentNullException.ThrowIfNull(project);var profile = project.TryResolve(project.RootDocument, out var root)- ? FirmamentAssemblyDocumentCompiler.ValidateProfile(root, FirmamentDocumentProfile.Assembly)+ ? FirmamentAssemblyDocumentCompiler.ValidateProfile(root, FirmamentDocumentProfile.Assembly, project.RootDocument, project): [];if (profile.Any(diagnostic => diagnostic.Severity == AssemblyDiagnosticSeverity.Error))return new(null, null, profile);diff --git a/Aetheris.Kernel.Firmament/Assembly/FirmamentAssemblyDocumentProfile.cs b/Aetheris.Kernel.Firmament/Assembly/FirmamentAssemblyDocumentProfile.csindex ee2c4a97..b3e9284e 100644--- a/Aetheris.Kernel.Firmament/Assembly/FirmamentAssemblyDocumentProfile.cs+++ b/Aetheris.Kernel.Firmament/Assembly/FirmamentAssemblyDocumentProfile.cs@@ -49,7 +49,7 @@ public sealed class FirmamentAssemblyDocumentCompilermigrated = true;}- var profileDiagnostics = ValidateProfile(source, profile);+ var profileDiagnostics = ValidateProfile(source, profile, fullPath);if (profileDiagnostics.Any(diagnostic => diagnostic.Severity == AssemblyDiagnosticSeverity.Error))return new(profile, fullPath, source, migrated, new(null, null, profileDiagnostics));@@ -76,8 +76,18 @@ public sealed class FirmamentAssemblyDocumentCompiler}public static IReadOnlyList<AssemblyDiagnostic> ValidateProfile(string source, FirmamentDocumentProfile profile)+ => ValidateProfile(source, profile, null);++ public static IReadOnlyList<AssemblyDiagnostic> ValidateProfile(string source, FirmamentDocumentProfile profile,+ string? document, FirmamentProjectSnapshot? project = null){if (profile == FirmamentDocumentProfile.General) return [];+ if (document is not null && Modules.FirmamentModuleGraph.HasImports(source))+ {+ var graph = Modules.FirmamentModuleGraph.Load(source, document, project);+ if (graph.Diagnostics.Count > 0) return graph.Diagnostics;+ source = graph.ProjectSource(graph.Root).Text;+ }var syntax = Aetheris.Kernel.Firmament.FirmamentV2.Syntax.FirmamentSyntaxParser.Parse(source);// The syntax owner reports malformed source; root counting must not hide// its diagnostic behind a line-oriented profile guess.diff --git a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.csindex 2c040f3a..5de51e86 100644--- a/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs+++ b/Aetheris.Kernel.Firmament/FirmamentBuildAndExport.cs@@ -745,7 +745,8 @@ public static class FirmamentBuildAndExportprivate static KernelResult<FirmamentStepExportResult> V2ParseFailure(FirmamentV2ParseResult parse){var syntaxCodes = parse.SyntaxDiagnostics.Select(d => d.Code).ToHashSet(StringComparer.Ordinal);- var errors = parse.Diagnostics.Where(FirmamentV2Parser.IsFatalDiagnosticCode).Where(code => !syntaxCodes.Contains(code))+ // parse-failed is a result status, used only when the producer supplied no explanation.+ var errors = parse.Diagnostics.Where(FirmamentV2Parser.IsFatalDiagnosticCode).Where(code => code != "firmament-v2-parse-failed" && !syntaxCodes.Contains(code)).Concat(parse.SyntaxDiagnostics.Select(d => d.Code + ": " + d.Message)).Distinct(StringComparer.Ordinal).ToArray();if (errors.Length == 0) errors = ["firmament-v2-parse-failed"];return KernelResult<FirmamentStepExportResult>.Failure(errors.Select(code => new KernelDiagnostic(diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentAuthoringField.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentAuthoringField.csindex c0194678..4d2a3b42 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentAuthoringField.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentAuthoringField.cs@@ -20,4 +20,11 @@ public static class FirmamentSchemaAuthoringFieldspublic static IReadOnlyList<FirmamentAuthoringField> For(string construct) =>Cache.TryGetValue(construct, out var fields) ? fields : [];++ public static IReadOnlyList<FirmamentAuthoringField> For(string construct, string? variant)+ {+ var applicable = FirmamentSemanticSchemas.Get(construct)?.Fields.Where(f => f.AppliesTo(variant))+ .Select(f => f.Name).ToHashSet(StringComparer.Ordinal);+ return applicable is null ? [] : For(construct).Where(f => applicable.Contains(f.Name)).ToArray();+ }}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.csindex 90bafb5f..41680e5c 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentBuildAdmissionValidation.cs@@ -87,7 +87,10 @@ public static class FirmamentBuildAdmissionValidationvar parts = diagnostic.Code.Split(':');string? subject = parts[0] is FirmamentV2Parser.CanonicalFieldUnknown or FirmamentV2Parser.CanonicalDeclarationUnknown&& parts.Length > 1 ? parts[^1] : null;- var matches = subject is null ? [] : tokens.Where(token => token.Shape == "identifier" && token.Text == subject).ToArray();+ var matches = subject is null ? [] : tokens.Where((token, index) => token.Shape == "identifier" &&+ (parts[0] == FirmamentV2Parser.CanonicalFieldUnknown+ ? Syntax.FirmamentSyntaxFields.SameField(token.Text, subject) && index + 1 < tokens.Length && tokens[index + 1].Text == ":"+ : token.Text == subject)).ToArray();var exact = matches.Length == 1;var token = exact ? matches[0] : tokens.FirstOrDefault(token => token.Shape == "identifier"&& token.Text is "Model" or "model" or "Struct" or "Concept" or "Profile" or "Template" or "Assembly" or "Scene");diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentFieldProjection.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentFieldProjection.csindex 06f6b3c7..2a2cf656 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentFieldProjection.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentFieldProjection.cs@@ -43,7 +43,7 @@ public static class FirmamentFieldProjectorif (hole.SourceSpan is null) continue;var schema = FirmamentSemanticSchemas.Get("Hole")!;result.Add(new(schema.Id, $"{block.TargetSolid}.{hole.Name}", sourceDocument, revision, buildRevision, hole.SourceSpan,- schema.Fields.Select(field => ProjectHoleField(field, hole, source)).ToArray()));+ schema.Fields.Where(field => field.AppliesTo(hole.Variant.ToString())).Select(field => ProjectHoleField(field, hole, source)).ToArray()));}return result;}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.csindex ad685c3f..0a222f74 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageAnalysis.cs@@ -128,7 +128,9 @@ public static class FirmamentLanguageAnalysisServiceparsed.Diagnostics.Select(d => new FirmamentLanguageDiagnostic(d.Severity == AssemblyDiagnosticSeverity.Error ? "error" : "information", d.Code, d.Message, 0, 0)).ToArray());}- public static bool HasAssemblyRoot(string source)+ public static bool HasAssemblyRoot(string source) => HasAssemblyRoot(source, null);++ public static bool HasAssemblyRoot(string source, string? document, FirmamentProjectSnapshot? project = null){var tokens = Lex(source).Where(t => t.Shape != "comment").ToArray();var depth = 0;@@ -139,6 +141,12 @@ public static class FirmamentLanguageAnalysisServiceif (depth == 0 && tokens[i].Text == "<" && tokens[i + 1].Text == "Assembly") return true;if (depth == 0 && tokens[i].Text == "Assembly" && tokens[i + 1].Shape == "identifier" && (i == 0 || tokens[i - 1].Text != "/")) return true;}+ if (document is not null && Aetheris.Kernel.Firmament.Modules.FirmamentModuleGraph.HasImports(source))+ {+ var graph = Aetheris.Kernel.Firmament.Modules.FirmamentModuleGraph.Load(source, document, project);+ if (graph.Diagnostics.Count == 0)+ return HasAssemblyRoot(graph.ProjectSource(graph.Root).Text);+ }return false;}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.csindex 357352b0..ddebeb49 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentLanguageService.cs@@ -31,7 +31,7 @@ public static class FirmamentLanguageServiceif (composition is not null){beforePrefix = source[Math.Max(lineStart,composition.Value.Open+1)..prefixStart];- fields = FirmamentSchemaAuthoringFields.For(composition.Value.Name);+ fields = FirmamentSchemaAuthoringFields.For(composition.Value.Name, composition.Value.Variant);context = composition.Value.Name;}else if (interfaceFamily is not null)@@ -135,11 +135,11 @@ public static class FirmamentLanguageServicereturn header is not null && !prefix[(header.Index + header.Length)..].Contains('}');}- private static (string Name, int Open)? ActiveCompositionConstruct(string source, int offset)+ private static (string Name, int Open, string? Variant)? ActiveCompositionConstruct(string source, int offset){// Ignore comments/strings and balance nested blocks in incomplete drafts.var prefix = Regex.Replace(source[..offset], @"//[^\r\n]*|/\*[\s\S]*?\*/|""(?:\\.|[^""\\])*""", m => new string(' ', m.Length));- var names = "Scene|Room|Door|Window|Camera|WireRoute|Follow|Section|Points|Linear|Series|Appearance|Material|Placement|FrameTransform|Garment|Panel|Fabric|Drape|FigureFit|Fitting|PoseTransition|Pose|Joint|Interface";+ var names = "Scene|Room|Door|Window|Camera|WireRoute|Follow|Section|Points|Linear|Series|Appearance|Material|Placement|FrameTransform|Garment|Panel|Fabric|Drape|FigureFit|Fitting|PoseTransition|Pose|Joint|Interface|Hole";var matches = Regex.Matches(prefix, $@"\b(?<kind>{names})(?:\s*<(?<family>[^>]+)>)?(?:\s+[A-Za-z_]\w*)?\s*\{{");foreach (Match header in matches.Cast<Match>().Reverse()){@@ -154,7 +154,7 @@ public static class FirmamentLanguageService{string name = header.Groups["kind"].Value;if (name == "Interface") name += "<" + header.Groups["family"].Value.Trim() + ">";- return (name, header.Index + header.Length - 1);+ return (name, header.Index + header.Length - 1, header.Groups["family"].Value.Trim());}}return null;diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.csindex c19a6235..e5fff8f4 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2MechanicalBinding.cs@@ -111,6 +111,9 @@ public static partial class FirmamentV2Parser{if (modify.Clauses.Count > 0 || modify.Type.Arguments.Count > 0) diagnostics.Add(CanonicalModifyMalformed);if (modify.Name is null || !solids.TryGetValue(modify.Name.Text, out var solid)) { diagnostics.Add(ModifyTargetUnresolved); continue; }+ // An authored empty body is an admitted no-op after target binding.+ // Keep it out of material feature lowering, which requires real work.+ if (modify.Body is { Statements.Count: 0 }) continue;var holes = new List<FirmamentV2SemanticHoleDecl>(); var finishes = new List<FirmamentV2EdgeFinishDecl>(); var perforations = new List<FirmamentV2PerforationDecl>();foreach (var statement in modify.Body?.Statements ?? []){diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.csindex 739d2f72..04a78f1a 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/FirmamentV2Parser.cs@@ -1795,7 +1795,10 @@ public static partial class FirmamentV2Parserprivate static FirmamentV2ParseResult CanonicalFailure(List<string> diagnostics, string diagnostic){- diagnostics.Add(diagnostic);+ // A precise producer error already explains rejection. Do not append a+ // locationless document-malformed error for a semantically parsed Model.+ if (diagnostic != CanonicalDocumentMalformed || !diagnostics.Any(IsFatalDiagnosticCode))+ diagnostics.Add(diagnostic);diagnostics.Add("firmament-v2-parse-failed");return FirmamentV2ParseResult.Failure(diagnostics.Distinct(StringComparer.Ordinal).Order().ToArray());}diff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.csindex 4a0ba56a..c6e592c5 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticConstructDeclarations.cs@@ -11,10 +11,10 @@ public static class BoxSemanticDeclaration { }[FirmamentField("Center", "Center", FirmamentSchemaValueKind.Point, Required = true, Description = "Center in the support face.")][FirmamentField("Diameter", "Diameter", FirmamentSchemaValueKind.Length, Required = true, Description = "Shaft diameter.", SourceEditable = true, ProjectionMember = nameof(ProjectDiameter))][FirmamentField("End", "End", FirmamentSchemaValueKind.String, Required = true, Description = "ThroughAll or a blind termination expression.")]-[FirmamentField("CounterboreDiameter", "CounterboreDiameter", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Description = "Relief diameter for Hole<Counterbore>; larger than the shaft diameter.")]-[FirmamentField("CounterboreDepth", "CounterboreDepth", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Description = "Positive relief depth for Hole<Counterbore>.")]-[FirmamentField("CountersinkDiameter", "CountersinkDiameter", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Description = "Entry diameter for Hole<Countersink>; larger than the shaft diameter.")]-[FirmamentField("CountersinkAngle", "CountersinkAngle", FirmamentSchemaValueKind.Angle, Unit = FirmamentUnitKind.Angle, Description = "Included angle for Hole<Countersink>, strictly between 0deg and 180deg.")]+[FirmamentField("CounterboreDiameter", "CounterboreDiameter", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Variants = ["Counterbore"], Description = "Relief diameter for Hole<Counterbore>; larger than the shaft diameter.")]+[FirmamentField("CounterboreDepth", "CounterboreDepth", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Variants = ["Counterbore"], Description = "Positive relief depth for Hole<Counterbore>.")]+[FirmamentField("CountersinkDiameter", "CountersinkDiameter", FirmamentSchemaValueKind.Length, Unit = FirmamentUnitKind.Length, Variants = ["Countersink"], Description = "Entry diameter for Hole<Countersink>; larger than the shaft diameter.")]+[FirmamentField("CountersinkAngle", "CountersinkAngle", FirmamentSchemaValueKind.Angle, Unit = FirmamentUnitKind.Angle, Variants = ["Countersink"], Description = "Included angle for Hole<Countersink>, strictly between 0deg and 180deg.")][FirmamentField("PatternIdentity", "PatternIdentity", FirmamentSchemaValueKind.String, Description = "Optional pattern identity.")][FirmamentOutput("Wall", "Wall", "Face", SourceAddressable = true, SourceRole = nameof(Materializer.SemanticTopologyRole.HoleWallFace))]public static class HoleSemanticDeclarationdiff --git a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticSchema.cs b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticSchema.csindex b7caeb1e..6de60412 100644--- a/Aetheris.Kernel.Firmament/FirmamentV2/SemanticSchema.cs+++ b/Aetheris.Kernel.Firmament/FirmamentV2/SemanticSchema.cs@@ -26,6 +26,7 @@ public sealed class FirmamentFieldAttribute(string stableId, string name, Firmampublic string? Default { get; init; }public string? Description { get; init; }public string[]? Choices { get; init; }+ public string[]? Variants { get; init; }public bool SourceEditable { get; init; }public string? ProjectionMember { get; init; }}@@ -44,7 +45,11 @@ public readonly record struct FirmamentConstructId(string Value);public readonly record struct FirmamentFieldId(string Value);public readonly record struct FirmamentOutputId(string Value);public sealed record FirmamentFieldSchema(FirmamentFieldId Id, string Name, FirmamentSchemaValueKind Kind, FirmamentUnitKind Unit,- bool Required, string? Default, IReadOnlyList<string> Choices, string? Description, bool SourceEditable);+ bool Required, string? Default, IReadOnlyList<string> Choices, string? Description, bool SourceEditable)+{+ public IReadOnlyList<string> Variants { get; init; } = [];+ public bool AppliesTo(string? variant) => Variants.Count == 0 || Variants.Contains(variant, StringComparer.Ordinal);+}public sealed record FirmamentOutputSchema(FirmamentOutputId Id, string Name, string Kind, bool SourceAddressable, string? SourceRole);public sealed record FirmamentConstructSchema(FirmamentConstructId Id, string Name, string? Context, string? Entry,string? Description, string? CompatibilityAlias, IReadOnlyList<FirmamentFieldSchema> Fields,diff --git a/Aetheris.Web.Perf/VerifyMotion.cs b/Aetheris.Web.Perf/VerifyMotion.csindex 65fb87a6..8dde265c 100644--- a/Aetheris.Web.Perf/VerifyMotion.cs+++ b/Aetheris.Web.Perf/VerifyMotion.cs@@ -10,9 +10,13 @@ internal static class VerifyMotionif (args.Length != 1) { Console.Error.WriteLine("Usage: Aetheris.Web.Perf verify-motion <articulated-motion.firmament>"); return 2; }var path = Path.GetFullPath(args[0]);var motion = File.ReadAllText(path);- var source = File.ReadAllText(Path.Combine(Path.GetDirectoryName(path)!, "articulated-subassemblies.firmament"))- + "\n" + string.Join('\n', motion.Split('\n').Where(l => !l.StartsWith("include ", StringComparison.Ordinal)));- var native = new AssemblyM1Pipeline().Compile(source, "motion.firmament");+ var source = motion;+ var documents = new Dictionary<string, string>(StringComparer.Ordinal)+ {+ ["motion.firmament"] = source,+ ["articulated-subassemblies.firmament"] = File.ReadAllText(Path.Combine(Path.GetDirectoryName(path)!, "articulated-subassemblies.firmament"))+ };+ var native = new AssemblyM1Pipeline().CompileFile(path);if (!native.IsSuccess) throw new InvalidOperationException(string.Join(';', native.Diagnostics.Select(d => d.Message)));JsonElement Call(object request){@@ -20,7 +24,7 @@ internal static class VerifyMotionif (!response.RootElement.GetProperty("ok").GetBoolean()) throw new InvalidOperationException(response.RootElement.ToString());return response.RootElement.GetProperty("result").Clone();}- var built = Call(new { operation = "compile", source, sourceName = "motion.firmament" });+ var built = Call(new { operation = "compile", source, sourceName = "motion.firmament", projectDocuments = documents });if (!built.GetProperty("success").GetBoolean()) throw new InvalidOperationException(built.ToString());var model = built.GetProperty("model");var sessionId = model.GetProperty("id").GetString();diff --git a/Aetheris.Web.Runtime/Program.cs b/Aetheris.Web.Runtime/Program.csindex 3f5db654..d30c2205 100644--- a/Aetheris.Web.Runtime/Program.cs+++ b/Aetheris.Web.Runtime/Program.cs@@ -134,9 +134,10 @@ public static partial class Program? new Dictionary<string, string>(request.ProjectDocuments, StringComparer.Ordinal) { [name] = request.Source }: null;var root = request.ProjectRoot ?? name;+ var project = documents is null ? null : new FirmamentProjectSnapshot(root, documents);var analysis = documents is not null && documents.TryGetValue(root, out var rootSource) &&- FirmamentLanguageAnalysisService.HasAssemblyRoot(rootSource)- ? FirmamentLanguageAnalysisService.Analyze(new FirmamentProjectSnapshot(root, documents), name, request.SourceRevision)+ FirmamentLanguageAnalysisService.HasAssemblyRoot(rootSource, root, project)+ ? FirmamentLanguageAnalysisService.Analyze(project!, name, request.SourceRevision): FirmamentLanguageAnalysisService.Analyze(request.Source, name, request.SourceRevision);return new { document = name, revision = request.SourceRevision, analysis.Tokens,diagnostics = analysis.Diagnostics.Select(item => new WebDiagnostic(item.Severity, item.Code, item.Message,@@ -196,7 +197,7 @@ public static partial class Programfields = construct.Fields.Select(field => new{id = field.Id.Value, field.Name, kind = field.Kind.ToString(), unit = field.Unit.ToString(),- field.Required, field.Default, field.Choices, field.Description, field.SourceEditable+ field.Required, field.Default, field.Choices, field.Variants, field.Description, field.SourceEditable}),outputs = construct.Outputs.Select(item => new{@@ -270,7 +271,8 @@ public static partial class Programstring? SourceRevision = null, int? Offset = null, string? ConstructSemanticId = null,string? FieldId = null, FirmamentProjectedValue? FieldValue = null, int? BuildRevision = null,bool Performance = false, IReadOnlyDictionary<string, string>? ProjectDocuments = null, string? ProjectRoot = null,- int? Bridge = null, IReadOnlyList<FirmamentLanguageEditOperation>? Operations = null);+ int? Bridge = null, IReadOnlyList<FirmamentLanguageEditOperation>? Operations = null,+ string? Motion = null, double? TimeSeconds = null, bool PreserveEndpoint = false);/// <summary>/// BUILD-PERF-M3 response bridge (request <c>bridge: 1</c>, sent by the SDK). Large numeric arrays@@ -422,7 +424,10 @@ public static partial class Programvar index = nextProperties.FindIndex(property => property.Id == propertyId);if (index >= 0) nextProperties[index] = nextProperties[index] with { Value = value.Value };}- var assembly = Regex.IsMatch(effective, @"(?m)^\s*Assembly\s+", RegexOptions.CultureInvariant);+ var rootDocuments = new Dictionary<string, string>(_projectDocuments ?? new Dictionary<string, string>(), StringComparer.Ordinal)+ { [_sourceName] = effective };+ var assembly = FirmamentLanguageAnalysisService.HasAssemblyRoot(effective, _sourceName,+ new FirmamentProjectSnapshot(_sourceName, rootDocuments));var scene = SceneAuthoring.HasRoot(effective);var compiled = scene ? CompileScene(effective) : assembly ? CompileAssembly(effective, nextProperties) : CompilePart(effective, nextProperties);if (!compiled.Success)@@ -470,7 +475,7 @@ public static partial class ProgramcompilePhase.Dispose();var compileMs = watch.Elapsed.TotalMilliseconds;if (!build.IsSuccess || build.Value is null)- return WebBuildResult.Failed(Diagnostics(build.Diagnostics, _sourceName), compileMs);+ return WebBuildResult.Failed(Diagnostics(build.Diagnostics, _sourceName, effective), compileMs);var step = build.Value.StepText;BrepBody displayBody;if (build.Value.RuntimeBody is { } canonicalBody) displayBody = canonicalBody;@@ -627,10 +632,16 @@ public static partial class Programreturn result;}- private static IReadOnlyList<WebDiagnostic> Diagnostics(IEnumerable<KernelDiagnostic> diagnostics, string source)- => diagnostics.Select(diagnostic => new WebDiagnostic(- diagnostic.Severity switch { KernelDiagnosticSeverity.Error => "error", KernelDiagnosticSeverity.Warning => "warning", _ => "info" },- diagnostic.Code.ToString(), diagnostic.Message, SourceRef(source, 0, 0), diagnostic.Source)).ToArray();+ private static IReadOnlyList<WebDiagnostic> Diagnostics(IEnumerable<KernelDiagnostic> diagnostics, string source, string? text = null)+ => diagnostics.Select(diagnostic =>+ {+ var presented = FirmamentBuildAdmissionValidation.Present(diagnostic, source, text);+ var location = presented.SourceSpan is { } span+ ? new WebSourceRef(presented.SourceFile ?? source, presented.Line ?? 0, presented.Column ?? 0, span.Start, span.Length)+ : null;+ return new WebDiagnostic(presented.Severity is "fatal" or "error" ? "error" : presented.Severity,+ presented.Code, presented.Message, location, presented.LocationNote ?? diagnostic.Source);+ }).ToArray();private static WebSourceRef SourceRef(string source, int start, int length) => new(source, 1, 1, start, length);private static WebSourceRef SourceRefAt(string name, string text, int start, int length)diff --git a/Aetheris.Web.Runtime/sdk/README.md b/Aetheris.Web.Runtime/sdk/README.mdindex e779c8d0..60d7299b 100644--- a/Aetheris.Web.Runtime/sdk/README.md+++ b/Aetheris.Web.Runtime/sdk/README.md@@ -113,3 +113,11 @@ graph, reuses the existing mesh definitions, and does not rebuild geometry orchange the engineering STEP snapshot. Consumers own their playback clock andapply the returned occurrence matrices. An unsuccessful source rebuild retainsthe previous admitted graph together with the previous geometry.++Compiler completion and `model.describeConstruct(semanticId)` return fields+applicable to the active Hole variant. The raw `cad.language.schema()` is a+union schema: its optional field `variants` array restricts applicability;+an absent or empty array means common to all variants. Schema-driven controls+must honor this metadata or request completion. For example, `CounterboreDepth`+applies to `Counterbore`, never `Shaft`. Part build diagnostics use the shared+compiler presenter, retaining stable error codes and authored source locations.diff --git a/Aetheris.Web.Runtime/sdk/src/index.d.ts b/Aetheris.Web.Runtime/sdk/src/index.d.tsindex 48fbb367..385243de 100644--- a/Aetheris.Web.Runtime/sdk/src/index.d.ts+++ b/Aetheris.Web.Runtime/sdk/src/index.d.ts@@ -54,7 +54,7 @@ export type LanguageEditOperation =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[] }export interface LanguageHover { readonly document: string; readonly revision: string; readonly start: number; readonly length: number; readonly title: string; readonly description: string }export interface LanguageFormat { readonly document: string; readonly revision: string; readonly text: string; readonly changed: boolean }-export interface SemanticFieldSchema { readonly id: string; readonly name: string; readonly kind: string; readonly unit: 'None' | 'Length' | 'Angle'; readonly required: boolean; readonly default: string | null; readonly choices: readonly string[]; readonly description: string | null; readonly sourceEditable: boolean }+export interface SemanticFieldSchema { readonly id: string; readonly name: string; readonly kind: string; readonly unit: 'None' | 'Length' | 'Angle'; readonly required: boolean; readonly default: string | null; readonly choices: readonly string[]; readonly variants?: readonly string[]; readonly description: string | null; readonly sourceEditable: boolean }export interface SemanticOutputSchema { readonly id: string; readonly name: string; readonly kind: string; readonly sourceAddressable: boolean; readonly sourceRole: string | null }export interface SemanticConstructSchema { readonly id: string; readonly name: string; readonly context: string | null; readonly entry: string | null; readonly description: string | null; readonly compatibilityAlias: string | null; readonly fields: readonly SemanticFieldSchema[]; readonly outputs: readonly SemanticOutputSchema[] }export interface SemanticSchema { readonly version: 'firmament-semantic-schema/1'; readonly projectionVersion: 'firmament-field-projection/1'; readonly constructs: readonly SemanticConstructSchema[] }diff --git a/docs/public/firmament/syntax.md b/docs/public/firmament/syntax.mdindex bd045e1c..391af422 100644--- a/docs/public/firmament/syntax.md+++ b/docs/public/firmament/syntax.md@@ -482,6 +482,17 @@ base material interval and admitted operations inside it. Compose does notreopen a separately declared Box, and neither construct admits arbitrary Booleanor feature combinations.+In a primitive Model, `Modify Base {}` is a valid no-op once `Base` resolves to+an existing body. Deleting its last feature leaves the same stock geometry;+an unresolved target still rejects. An empty Modify does not create a feature.++Hole fields depend on the declared variant. `Hole<Shaft>` uses the common+`on`, `center`, `diameter` and `end` fields. `Hole<Counterbore>` additionally+uses `counterboreDiameter` and `counterboreDepth`; `Hole<Countersink>` uses+`countersinkDiameter` and `countersinkAngle`. Relief fields on a Shaft hole+are errors. Compiler completion and bound-field inspection project the same+variant applicability from the shared schema.+| Intent | Current vocabulary | Placement / termination || --- | --- | --- || Drill a hole | `Hole<Shaft>`, `Hole<Counterbore>`, `Hole<Countersink>` | `on`, `center`, `end: ThroughAll` or a bounded blind end. |diff --git a/docs/release/FIRMAMENT-V8-DECLARATIVE-MOTION.md b/docs/release/FIRMAMENT-V8-DECLARATIVE-MOTION.mdindex 8f3329fd..731457bd 100644--- a/docs/release/FIRMAMENT-V8-DECLARATIVE-MOTION.md+++ b/docs/release/FIRMAMENT-V8-DECLARATIVE-MOTION.md@@ -62,6 +62,8 @@ continuity. Input expressions reuse the existing typed expression evaluator.Local templated Parts in Inventory modules now keep declaration identity separatefrom invocation arguments, fixing doubled specializations during module binding.The imported two-occurrence witness qualifies public channels and geometry sharing.+Ordinary validate/build and the SDK also classify an Assembly inherited through+include via that same module graph, rather than misrouting the clip as a Part.The compiler orders coordinate writers once; duplicate writers and dependencycycles reject before sampling.@@ -115,9 +117,125 @@ error sentences.## Qualification-Evidence is generated under ignored `artifacts/local/`. Final results are-recorded below after qualification. No whole-V8 declarative-motion claim is-implied by successful rigid-joint clip qualification.+Evidence is generated under ignored `artifacts/local/`. The build uses serial+MSBuild with node reuse and shared compilation disabled. Qualification covers+the real CLI, native session runtime, public browser SDK and compiled WASM.+No whole-V8 declarative-motion claim is implied by the rigid-joint clip witness.++- Release solution build: passed. Existing analyzer, trimming and WebAssembly+ interop warnings remain; they are not represented as a warning-free build.+- Core fast lane: 1,076 passed. Focused articulated-assembly and Motion tests:+ 28 passed. SDK Node tests: 13 passed.+- Final complete solution gate, including Helios feedback: **5,198 passed across 20 test assemblies,+ zero failures**. The final focused integration rerun passed 50 tests,+ including the imported-root project and structural-editing cases.+- Native session and real browser WASM proofs passed at seven times, including+ reverse/non-key queries. All 1,232 compared matrix components matched exactly.+ Explicit endpoint sampling retained 720deg; shared definitions and the+ last-valid graph survived sampling and failed edits.+- Both include-root and Inventory-root Motion fixtures passed ordinary CLI+ validate and build. Validation reports `validationLevel: Built` and no errors;+ the builds produced STEP artifacts.+- Claude FrontendX4 corpus: 32/32 passed without changing cases or recording+ new expected geometry.+- Frozen STEP replay: 26/26 byte-identical artifacts. Scoped FrontendX2+ qualification: all nine expected validate/build outcomes held.+- Full editable V8 demo generation completed for Stages A/B/C, baseline and+ the +6mm stroke revision. Each final configuration checked 5,768 cylinder+ samples and 11,536 spring samples. Maximum rod-closure residual was+ `8.527e-14mm`; spring seat distance and drift were zero. This retains the+ existing bounded interference scope, not a general collision certificate.++The V8 comparison retains 171 physical Parts, all 21 definition STEP hashes+and occurrence identities. Maximum world-matrix and measured metric difference+is `2.842170943040401e-14`, below the existing `1e-9` qualification threshold.+No reference tolerance was widened. The resulting graph contains 193+occurrences, 140 retained mechanical relationships and 43 separate frame+dependencies; increased retained relationship counts are graph fidelity, not+new geometry.++Local evidence: `v8-relations-fast.log`, `v8-motion-focused.log`,+`v8-motion-sdk-tests.log`, `v8-relations-x4.log`, `v8-relations-demo.log`,+`v8-relations/v8-parity.json` and `v8-relations/parity/geometry-parity.json`,+all beneath `artifacts/local/`.++Final integration also tests a Motion document whose Assembly comes from an+include. Root classification and Assembly-profile admission resolve that+include through the existing module graph. The browser witness supplies real+project documents rather than concatenating their text. The concurrent+structural-editing update is retained, including its request fields alongside+the restored Motion query fields.+Its six Windows-only assertion failures came from a raw-string test specimen+inheriting CRLF while assertions require LF. The specimen now explicitly uses+LF, independent of checkout settings. Production editing and geometry logic+were not changed for those failures; the initial failing full-run log is retained+as `v8-relations-full-before-newline-fix.log`.+The final rebuilt native runtime and WASM harness passed after exposing raw+schema applicability. No task-owned dotnet, testhost or aetheris hosts remained+at closeout. Consolidated local evidence is+`artifacts/local/v8-relations/qualification.json`.++The code-quality review kept variant rules in the existing schema metadata,+source alias matching in its existing owner, and diagnostic presentation in the+compiler presenter. The only added regex vocabulary is Hole in the existing+bounded completion-context scanner; no execution parser route, global rewrite,+diagnostic-fatality allowlist or geometry workaround was added.++Reproduction commands (from the repository root):++```powershell+$env:MSBUILDDISABLENODEREUSE = '1'+dotnet build Aetheris.slnx -c Release -m:1 -nr:false -p:UseSharedCompilation=false --no-restore+dotnet test Aetheris.Kernel.Core.Tests -c Release --no-build -m:1 -nr:false --filter 'Category!=SlowCorpus'+dotnet test Aetheris.slnx -c Release --no-build -m:1 -nr:false -- RunConfiguration.MaxCpuCount=1+dotnet build Aetheris.Web.Perf -c Release -m:1 -nr:false -p:UseSharedCompilation=false+dotnet Aetheris.Web.Perf/bin/Release/net10.0/Aetheris.Web.Perf.dll verify-motion fixtures/Canonical/AssemblyInterfaces/articulated-motion.firmament+node scripts/qualify-assembly-motion-browser.mts <absolute-path-to-playwright-index.mjs>+node --test Aetheris.Web.Runtime/sdk/tests/*.test.mjs+python fixtures/Regression/FrontendX4/run.py+dotnet demos/Aetheris.EditableV8/bin/Release/net10.0/Aetheris.EditableV8.dll artifacts/local/v8-relations/demo+```++## Helios authoring feedback follow-up++The follow-up screenshots identified three compiler/language-service defects.+Hole field metadata now carries variant applicability in the generated schema;+completion and semantic field projection use that same metadata. A Shaft hole+no longer advertises counterbore or countersink fields. Those fields remain+errors when authored on the wrong variant.+The raw SDK schema also exposes additive `variants` metadata. A Helios control+using that union schema must filter by the active variant, or request compiler+completion; the compiler does not mutate the union schema per document.++The parser failure producer no longer appends a locationless generic malformed+Model error when a precise error already explains rejection. Structural failures+without a more specific diagnostic retain the generic fallback.+The build failure adapter treats `parse-failed` as a fallback result status,+not an extra diagnostic alongside an explanation. Source lookup for legacy+unknown-field diagnostics uses the existing accepted camelCase/PascalCase+aliases and requires an actual field-name token. The browser Part path now+uses the compiler's shared presenter rather than flattening errors to+`ValidationFailed` with invented `1:1` locations.++An empty Modify in a primitive Model binds its target and becomes a no-op before+material feature lowering. Tests compare its STEP text exactly with unmodified+stock and retain rejection for an unresolved target. The specimens live in+`fixtures/Regression/LanguageService/`. No separate Helios validator or+renderer fix is introduced; the viewport error pictured is outside this compiler+qualification.++Focused qualification: 24 tests passed, including all three Hole variants and+the five new feedback regressions. The real public-SDK/WASM browser harness+also passed all three variants, field completion/projection agreement, the+precise wrong-field diagnostic, and empty-Modify compilation. It simultaneously+retained the seven-time Motion proof and its 1,232 exact native/WASM component+comparisons. Evidence: `helios-authoring-focused.log` and+`helios-authoring-browser.log` beneath `artifacts/local/`.+The full follow-up gate passed all 5,198 tests; the fast lane passed 1,076.+Ordinary CLI validate and build reject both wrong-variant fields at their+actual field spans, without the generic Model or parse-status errors. Empty+Modify validates at `Built` level and exports successfully. The STEP identity+test verifies that accepting this no-op does not alter its stock geometry.## Exact remaining ownership boundarydiff --git a/fixtures/Regression/LanguageService/README.md b/fixtures/Regression/LanguageService/README.mdnew file mode 100644index 00000000..2e36ef3a--- /dev/null+++ b/fixtures/Regression/LanguageService/README.md@@ -0,0 +1,16 @@+# Helios authoring feedback++- `hole-variant.firmament` is an admitted Shaft hole. Tests specialize its+ variant and relief fields to qualify Shaft, Counterbore and Countersink+ completion, bound-field inspection and real geometry construction.+- Adding counterbore fields to the Shaft specimen must reject at those field+ tokens, without an unrelated malformed-Model diagnostic or duplicate+ parse-status error. Both accepted capitalization aliases retain locations.+- `empty-modify.firmament` deliberately keeps the Modify after deleting its last+ feature. It must compile to exactly the unmodified stock STEP. Replacing its+ target with an unresolved name must reject.++The public-SDK browser qualification in+`scripts/qualify-assembly-motion-browser.mts` exercises these cases in real+WASM alongside the articulated-motion proof. It does not qualify Helios's+viewport renderer.diff --git a/fixtures/Regression/LanguageService/empty-modify.firmament b/fixtures/Regression/LanguageService/empty-modify.firmamentnew file mode 100644index 00000000..2b118f89--- /dev/null+++ b/fixtures/Regression/LanguageService/empty-modify.firmament@@ -0,0 +1,5 @@+Model WebBracket {+ units: mm+ Box Base { size: [50mm, 40mm, 8mm] }+ Modify Base {}+}diff --git a/fixtures/Regression/LanguageService/hole-variant.firmament b/fixtures/Regression/LanguageService/hole-variant.firmamentnew file mode 100644index 00000000..a1b95072--- /dev/null+++ b/fixtures/Regression/LanguageService/hole-variant.firmament@@ -0,0 +1,12 @@+Model WebBracket {+ units: mm+ Box Base { size: [50mm, 40mm, 8mm] }+ Modify Base {+ Hole<Shaft> CenterMount {+ on: +Z+ center: Point2(0mm, 0mm)+ diameter: 8mm+ end: ThroughAll+ }+ }+}diff --git a/scripts/qualify-assembly-motion-browser.mts b/scripts/qualify-assembly-motion-browser.mtsindex e321b9ef..462e6f39 100644--- a/scripts/qualify-assembly-motion-browser.mts+++ b/scripts/qualify-assembly-motion-browser.mts@@ -11,8 +11,13 @@ const modulePath = process.argv[2];if (!modulePath) throw new Error('Pass an explicit Playwright module path.');const { chromium } = await import(pathToFileURL(resolve(modulePath)).href);const fixture = resolve(repo, 'fixtures/Canonical/AssemblyInterfaces/articulated-motion.firmament');-const source = await readFile(resolve(repo, 'fixtures/Canonical/AssemblyInterfaces/articulated-subassemblies.firmament'), 'utf8')- + '\n' + (await readFile(fixture, 'utf8')).split('\n').filter(line => !line.startsWith('include ')).join('\n');+const source = await readFile(fixture, 'utf8');+const holeSource = await readFile(resolve(repo, 'fixtures/Regression/LanguageService/hole-variant.firmament'), 'utf8');+const emptyModifySource = await readFile(resolve(repo, 'fixtures/Regression/LanguageService/empty-modify.firmament'), 'utf8');+const documents = {+ 'motion.firmament': source,+ 'articulated-subassemblies.firmament': await readFile(resolve(repo, 'fixtures/Canonical/AssemblyInterfaces/articulated-subassemblies.firmament'), 'utf8'),+};const times = [0, 1.25, .231, 1.749, 2, -.75, 3.25];const expected = times.map(time => JSON.parse(execFileSync('dotnet', [resolve(repo, 'Aetheris.CLI/bin/Release/net10.0/aetheris.dll'),'asm', 'motion', fixture, '--clip', 'Cycle', '--time', String(time), '--json'], { cwd: repo, encoding: 'utf8', maxBuffer: 8 * 1024 * 1024 })));@@ -37,11 +42,11 @@ try {browser = await chromium.launch({ executablePath: 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', headless: true });const page = await browser.newPage();await page.goto(`http://127.0.0.1:${address.port}/`);- const result = await page.evaluate(async ({ source, times, expected }) => {+ const result = await page.evaluate(async ({ source, documents, times, expected, holeSource, emptyModifySource }) => {const { Aetheris } = await import('/Aetheris.Web.Runtime/sdk/src/index.js');const cad = await Aetheris.create({ wasmUrl: new URL('/Aetheris.Web.Runtime/bin/Release/net10.0/wwwroot/', location.href) });try {- const built = await cad.compile(source, { sourceName: 'motion.firmament' });+ const built = await cad.compile(source, { sourceName: 'motion.firmament', projectDocuments: documents });const model = built.model;if (!model) throw new Error(JSON.stringify(built.diagnostics));if (model.motions.length !== 1) throw new Error('Missing compiled clip');@@ -67,10 +72,40 @@ try {const retained = await model.sampleMotion('Cycle', 1.25);if (retained.revision !== revision) throw new Error('Last-valid graph revision changed');await model.dispose();+ const schema = await cad.language.schema();+ const holeSchema = schema.constructs.find((c: {name: string}) => c.name === 'Hole');+ if (holeSchema?.fields.find((f: {name: string}) => f.name === 'CounterboreDepth')?.variants?.join(',') !== 'Counterbore')+ throw new Error('Raw schema lost Hole variant applicability');+ for (const [variant, relief] of [['Shaft', ''], ['Counterbore', 'counterboreDiameter: 14mm; counterboreDepth: 3mm; '],+ ['Countersink', 'countersinkDiameter: 14mm; countersinkAngle: 90deg; ']]) {+ const authored = holeSource.replace('<Shaft>', `<${variant}>`).replace(' end:', ' ' + relief + 'end:');+ const completion = await cad.language.complete(authored, authored.indexOf(' on:'), { sourceName: 'bracket.firmament', sourceRevision: '1' });+ const part = (await cad.compile(authored, { sourceName: 'bracket.firmament' })).model;+ if (!part) throw new Error('Hole variant rejected ' + variant);+ try {+ const projection = await part.describeConstruct('Base.CenterMount');+ for (const fields of [completion.fields, projection.fields]) {+ if (fields.some((f: {name: string}) => f.name === 'CounterboreDepth') !== (variant === 'Counterbore')+ || fields.some((f: {name: string}) => f.name === 'CountersinkAngle') !== (variant === 'Countersink'))+ throw new Error('Wrong variant field projection ' + variant);+ }+ if (variant === 'Shaft') {+ const invalid = authored.replace(' end:', ' counterboreDepth: 3mm; end:');+ const failed = await part.setSource(invalid);+ const error = failed.diagnostics.find((d: {code: string}) => d.code.includes('canonical-field-unknown'));+ if (failed.success || !error || error.source?.start !== invalid.indexOf('counterboreDepth')+ || failed.diagnostics.some((d: {code: string}) => d.code === 'firmament-v2-canonical-document-malformed'))+ throw new Error('Wrong-field error projection: ' + JSON.stringify({ expectedStart: invalid.indexOf('counterboreDepth'), failed }));+ }+ } finally { await part.dispose(); }+ }+ const empty = await cad.compile(emptyModifySource, { sourceName: 'bracket.firmament' });+ if (!empty.model) throw new Error('Empty Modify rejected: ' + JSON.stringify(empty.diagnostics));+ await empty.model.dispose();return { status: 'pass', runtime: 'real browser WASM via public SDK', samples: times.length, compared, maximumError: maximum,- sharedDefinitionsRetained: true, lastValidGraphRetained: true };+ sharedDefinitionsRetained: true, lastValidGraphRetained: true, holeVariants: 3, emptyModify: 'pass', locatedFieldError: 'pass' };} finally { await cad.dispose(); }- }, { source, times, expected });+ }, { source, documents, times, expected, holeSource, emptyModifySource });const output = resolve(repo, 'artifacts/local/v8-relations');await mkdir(output, { recursive: true });await writeFile(resolve(output, 'motion-browser.json'), JSON.stringify(result, null, 2));